assert.h(0p)

<assert.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

assert.h - verify program assertion

SYNOPSIS

#include <assert.h>

DESCRIPTION

The <assert.h> header shall define the assert() macro. It refers to the macro NDEBUG which is not defined in the header. If NDEBUG is defined as a macro name before the inclusion of this header, the assert() macro shall be defined simply as:

#define assert(ignore)((void) 0)

Otherwise, the macro behaves as described in assert().

The assert() macro shall be redefined according to the current state of NDEBUG each time <assert.h> is included.

The assert() macro shall be implemented as a macro, not as a function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, assert()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


libgen.h(0p)

<libgen.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

libgen.h - definitions for pattern matching functions

SYNOPSIS

#include <libgen.h>

DESCRIPTION

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

char  *basename(char *);
char  *dirname(char *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, basename(), dirname()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


utsname.h(0p)

Status: 403 Forbidden utsname.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/utsname.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


shm.h(0p)

Status: 403 Forbidden shm.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/shm.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


sys_utsname.h(0p)

<sys/utsname.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/utsname.h - system name structure

SYNOPSIS

#include <sys/utsname.h>

DESCRIPTION

The <sys/utsname.h> header shall define the structure utsname which shall include at least the following members:

char  sysname[]  Name of this implementation of the operating system.
char  nodename[] Name of this node within an implementation-defined
                 communications network.
char  release[]  Current release level of this implementation.
char  version[]  Current version level of this release.
char  machine[]  Name of the hardware type on which the system is running.

The character arrays are of unspecified size, but the data stored in them shall be terminated by a null byte.

The following shall be declared as a function and may also be defined as a macro:

int uname(struct utsname *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, uname()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tgmath.h(0p)

<tgmath.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tgmath.h - type-generic macros

SYNOPSIS

#include <tgmath.h>

DESCRIPTION

The <tgmath.h> header shall include the headers <math.h> and <complex.h> and shall define several type-generic macros.

Of the functions contained within the <math.h> and <complex.h> headers without an f ( float) or l ( long double) suffix, several have one or more parameters whose corresponding real type is double. For each such function, except modf(), there shall be a corresponding type-generic macro. The parameters whose corresponding real type is double in the function synopsis are generic parameters. Use of the macro invokes a function whose corresponding real type and type domain are determined by the arguments for the generic parameters.

Use of the macro invokes a function whose generic parameters have the corresponding real type determined as follows:

*
First, if any argument for generic parameters has type long double, the type determined is long double.

*
Otherwise, if any argument for generic parameters has type double or is of integer type, the type determined is double.

*
Otherwise, the type determined is float.

For each unsuffixed function in the <math.h> header for which there is a function in the <complex.h> header with the same name except for a c prefix, the corresponding type-generic macro (for both functions) has the same name as the function in the <math.h> header. The corresponding type-generic macro for fabs() and cabs() is fabs().
<math.h> | <complex.h> | Type-Generic
Function | Function | Macro
acos() | cacos() | acos()
asin() | casin() | asin()
atan() | catan() | atan()
acosh() | cacosh() | acosh()
asinh() | casinh() | asinh()
atanh() | catanh() | atanh()
cos() | ccos() | cos()
sin() | csin() | sin()
tan() | ctan() | tan()
cosh() | ccosh() | cosh()
sinh() | csinh() | sinh()
tanh() | ctanh() | tanh()
exp() | cexp() | exp()
log() | clog() | log()
pow() | cpow() | pow()
sqrt() | csqrt() | sqrt()
fabs() | cabs() | fabs()

If at least one argument for a generic parameter is complex, then use of the macro invokes a complex function; otherwise, use of the macro invokes a real function.

For each unsuffixed function in the <math.h> header without a c-prefixed counterpart in the <complex.h> header, the corresponding type-generic macro has the same name as the function. These type-generic macros are:

atan2()
cbrt()
ceil()
copysign()
erf()
erfc()
exp2()
expm1()
fdim()
floor()

fma()
fmax()
fmin()
fmod()
frexp()
hypot()
ilogb()
ldexp()
lgamma()
llrint()

llround()
log10()
log1p()
log2()
logb()
lrint()
lround()
nearbyint()
nextafter()
nexttoward()

remainder()
remquo()
rint()
round()
scalbn()
scalbln()
tgamma()
trunc()

If all arguments for generic parameters are real, then use of the macro invokes a real function; otherwise, use of the macro results in undefined behavior.

For each unsuffixed function in the <complex.h> header that is not a c-prefixed counterpart to a function in the <math.h> header, the corresponding type-generic macro has the same name as the function. These type-generic macros are:

carg()
cimag()
conj()
cproj()
creal()

Use of the macro with any real or complex argument invokes a complex function.

The following sections are informative.

APPLICATION USAGE

With the declarations:

#include <tgmath.h>
int n;
float f;
double d;
long double ld;
float complex fc;
double complex dc;
long double complex ldc;

functions invoked by use of type-generic macros are shown in the following table:
Macro | Use Invokes
exp(n) | exp(n), the function
acosh(f) | acoshf(f)
sin(d) | sin(d), the function
atan(ld) | atanl(ld)
log(fc) | clogf(fc)
sqrt(dc) | csqrt(dc)
pow(ldc,f) | cpowl(ldc, f)
remainder(n,n) | remainder(n, n), the function
nextafter(d,f) | nextafter(d, f), the function
nexttoward(f,ld) | nexttowardf(f, ld)
copysign(n,ld) | copysignl(n, ld)
ceil(fc) | Undefined behavior
rint(dc) | Undefined behavior
fmax(ldc,ld) | Undefined behavior
carg(n) | carg(n), the function
cproj(f) | cprojf(f)
creal(d) | creal(d), the function
cimag(ld) | cimagl(ld)
cabs(fc) | cabsf(fc)
carg(dc) | carg(dc), the function
cproj(ldc) | cprojl(ldc)

RATIONALE

Type-generic macros allow calling a function whose type is determined by the argument type, as is the case for C operators such as '+' and '*' . For example, with a type-generic cos() macro, the expression cos(( float) x) will have type float. This feature enables writing more portably efficient code and alleviates need for awkward casting and suffixing in the process of porting or adjusting precision. Generic math functions are a widely appreciated feature of Fortran.

The only arguments that affect the type resolution are the arguments corresponding to the parameters that have type double in the synopsis. Hence the type of a type-generic call to nexttoward(), whose second parameter is long double in the synopsis, is determined solely by the type of the first argument.

The term "type-generic" was chosen over the proposed alternatives of intrinsic and overloading. The term is more specific than intrinsic, which already is widely used with a more general meaning, and reflects a closer match to Fortran's generic functions than to C++ overloading.

The macros are placed in their own header in order not to silently break old programs that include the <math.h> header; for example, with:

printf ("%e", sin(x))

modf( double, double *) is excluded because no way was seen to make it safe without complicating the type resolution.

The implementation might, as an extension, endow appropriate ones of the macros that IEEE Std 1003.1-2001 specifies only for real arguments with the ability to invoke the complex functions.

IEEE Std 1003.1-2001 does not prescribe any particular implementation mechanism for generic macros. It could be implemented simply with built-in macros. The generic macro for sqrt(), for example, could be implemented with:

#undef sqrt
#define sqrt(x) __BUILTIN_GENERIC_sqrt(x)

Generic macros are designed for a useful level of consistency with C++ overloaded math functions.

The great majority of existing C programs are expected to be unaffected when the <tgmath.h> header is included instead of the <math.h> or <complex.h> headers. Generic macros are similar to the ISO/IEC 9899:1999 standard library masking macros, though the semantic types of return values differ.

The ability to overload on integer as well as floating types would have been useful for some functions; for example, copysign(). Overloading with different numbers of arguments would have allowed reusing names; for example, remainder() for remquo(). However, these facilities would have complicated the specification; and their natural consistent use, such as for a floating abs() or a two-argument atan(), would have introduced further inconsistencies with the ISO/IEC 9899:1999 standard for insufficient benefit.

The ISO C standard in no way limits the implementation's options for efficiency, including inlining library functions.

FUTURE DIRECTIONS

None.

SEE ALSO

<math.h> , <complex.h> , the System Interfaces volume of IEEE Std 1003.1-2001, cabs(), fabs(), modf()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ftw.h(0p)

<ftw.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ftw.h - file tree traversal

SYNOPSIS

#include <ftw.h>

DESCRIPTION

The <ftw.h> header shall define the FTW structure that includes at least the following members:

int  base
int  level

The <ftw.h> header shall define macros for use as values of the third argument to the application-supplied function that is passed as the second argument to ftw() and nftw():

FTW_F
File.
FTW_D
Directory.
FTW_DNR
Directory without read permission.
FTW_DP
Directory with subdirectories visited.
FTW_NS
Unknown type; stat() failed.
FTW_SL
Symbolic link.
FTW_SLN
Symbolic link that names a nonexistent file.

The <ftw.h> header shall define macros for use as values of the fourth argument to nftw():

FTW_PHYS
Physical walk, does not follow symbolic links. Otherwise, nftw() follows links but does not walk down any path that crosses itself.
FTW_MOUNT
The walk does not cross a mount point.
FTW_DEPTH
All subdirectories are visited before the directory itself.
FTW_CHDIR
The walk changes to each directory before reading it.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int ftw(const char *, int (*)(const char *, const struct stat *,
    int), int);
int nftw(const char *, int (*)(const char *, const struct stat *,
    int, struct FTW*), int, int);

The <ftw.h> header shall define the stat structure and the symbolic names for st_mode and the file type test macros as described in <sys/stat.h> .

Inclusion of the <ftw.h> header may also make visible all symbols from <sys/stat.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/stat.h> , the System Interfaces volume of IEEE Std 1003.1-2001, ftw(), nftw()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


unistd.h(0p)

<unistd.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unistd.h - standard symbolic constants and types

SYNOPSIS

#include <unistd.h>

DESCRIPTION

The <unistd.h> header defines miscellaneous symbolic constants and types, and declares miscellaneous functions. The actual values of the constants are unspecified except as shown. The contents of this header are shown below.

Version Test Macros

The following symbolic constants shall be defined:

_POSIX_VERSION
Integer value indicating version of IEEE Std 1003.1 (C-language binding) to which the implementation conforms. For implementations conforming to IEEE Std 1003.1-2001, the value shall be 200112L.
_POSIX2_VERSION
Integer value indicating version of the Shell and Utilities volume of IEEE Std 1003.1 to which the implementation conforms. For implementations conforming to IEEE Std 1003.1-2001, the value shall be 200112L.

The following symbolic constant shall be defined only if the implementation supports the XSI option; see XSI Conformance .

_XOPEN_VERSION

Integer value indicating version of the X/Open Portability Guide to which the implementation conforms. The value shall be 600.

Constants for Options and Option Groups

The following symbolic constants, if defined in <unistd.h>, shall have a value of -1, 0, or greater, unless otherwise specified below. If these are undefined, the fpathconf(), pathconf(), or sysconf() functions can be used to determine whether the option is provided for a particular invocation of the application.

If a symbolic constant is defined with the value -1, the option is not supported. Headers, data types, and function interfaces required only for the option need not be supplied. An application that attempts to use anything associated only with the option is considered to be requiring an extension.

If a symbolic constant is defined with a value greater than zero, the option shall always be supported when the application is executed. All headers, data types, and functions shall be present and shall operate as specified.

If a symbolic constant is defined with the value zero, all headers, data types, and functions shall be present. The application can check at runtime to see whether the option is supported by calling fpathconf(), pathconf(), or sysconf() with the indicated name parameter.

Unless explicitly specified otherwise, the behavior of functions associated with an unsupported option is unspecified, and an application that uses such functions without first checking fpathconf(), pathconf(), or sysconf() is considered to be requiring an extension.

For conformance requirements, refer to Conformance .

_POSIX_ADVISORY_INFO

The implementation supports the Advisory Information option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_ASYNCHRONOUS_IO

The implementation supports the Asynchronous Input and Output option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_BARRIERS

The implementation supports the Barriers option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_CHOWN_RESTRICTED
The use of chown() and fchown() is restricted to a process with appropriate privileges, and to changing the group ID of a file only to the effective group ID of the process or to one of its supplementary group IDs. This symbol shall always be set to a value other than -1.
_POSIX_CLOCK_SELECTION

The implementation supports the Clock Selection option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_CPUTIME

The implementation supports the Process CPU-Time Clocks option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_FSYNC

The implementation supports the File Synchronization option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_IPV6
The implementation supports the IPv6 option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.
_POSIX_JOB_CONTROL
The implementation supports job control. This symbol shall always be set to a value greater than zero.
_POSIX_MAPPED_FILES

The implementation supports the Memory Mapped Files option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_MEMLOCK

The implementation supports the Process Memory Locking option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_MEMLOCK_RANGE

The implementation supports the Range Memory Locking option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_MEMORY_PROTECTION

The implementation supports the Memory Protection option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_MESSAGE_PASSING

The implementation supports the Message Passing option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_MONOTONIC_CLOCK

The implementation supports the Monotonic Clock option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_NO_TRUNC
Pathname components longer than {NAME_MAX} generate an error. This symbol shall always be set to a value other than -1.
_POSIX_PRIORITIZED_IO

The implementation supports the Prioritized Input and Output option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_PRIORITY_SCHEDULING

The implementation supports the Process Scheduling option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_RAW_SOCKETS

The implementation supports the Raw Sockets option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_READER_WRITER_LOCKS

The implementation supports the Read-Write Locks option. This is always set to a value greater than zero if the Threads option is supported. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_REALTIME_SIGNALS

The implementation supports the Realtime Signals Extension option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_REGEXP
The implementation supports the Regular Expression Handling option. This symbol shall always be set to a value greater than zero.
_POSIX_SAVED_IDS
Each process has a saved set-user-ID and a saved set-group-ID. This symbol shall always be set to a value greater than zero.
_POSIX_SEMAPHORES

The implementation supports the Semaphores option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_SHARED_MEMORY_OBJECTS

The implementation supports the Shared Memory Objects option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_SHELL
The implementation supports the POSIX shell. This symbol shall always be set to a value greater than zero.
_POSIX_SPAWN

The implementation supports the Spawn option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_SPIN_LOCKS

The implementation supports the Spin Locks option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_SPORADIC_SERVER

The implementation supports the Process Sporadic Server option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_SYNCHRONIZED_IO

The implementation supports the Synchronized Input and Output option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_ATTR_STACKADDR

The implementation supports the Thread Stack Address Attribute option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_ATTR_STACKSIZE

The implementation supports the Thread Stack Size Attribute option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_CPUTIME

The implementation supports the Thread CPU-Time Clocks option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_PRIO_INHERIT

The implementation supports the Thread Priority Inheritance option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_PRIO_PROTECT

The implementation supports the Thread Priority Protection option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_PRIORITY_SCHEDULING

The implementation supports the Thread Execution Scheduling option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_PROCESS_SHARED

The implementation supports the Thread Process-Shared Synchronization option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_SAFE_FUNCTIONS

The implementation supports the Thread-Safe Functions option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREAD_SPORADIC_SERVER

The implementation supports the Thread Sporadic Server option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_THREADS

The implementation supports the Threads option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_TIMEOUTS

The implementation supports the Timeouts option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_TIMERS

The implementation supports the Timers option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_TRACE

The implementation supports the Trace option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_TRACE_EVENT_FILTER

The implementation supports the Trace Event Filter option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_TRACE_INHERIT

The implementation supports the Trace Inherit option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_TRACE_LOG

The implementation supports the Trace Log option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_TYPED_MEMORY_OBJECTS

The implementation supports the Typed Memory Objects option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX_VDISABLE
This symbol shall be defined to be the value of a character that shall disable terminal special character handling as described in <termios.h> . This symbol shall always be set to a value other than -1.
_POSIX2_C_BIND
The implementation supports the C-Language Binding option. This symbol shall always have the value 200112L.
_POSIX2_C_DEV

The implementation supports the C-Language Development Utilities option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_CHAR_TERM
The implementation supports at least one terminal type.
_POSIX2_FORT_DEV

The implementation supports the FORTRAN Development Utilities option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_FORT_RUN

The implementation supports the FORTRAN Runtime Utilities option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_LOCALEDEF
The implementation supports the creation of locales by the localedef utility. If this symbol has a value other than -1 or 0, it shall have the value 200112L.
_POSIX2_PBS

The implementation supports the Batch Environment Services and Utilities option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_PBS_ACCOUNTING

The implementation supports the Batch Accounting option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_PBS_CHECKPOINT

The implementation supports the Batch Checkpoint/Restart option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_PBS_LOCATE

The implementation supports the Locate Batch Job Request option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_PBS_MESSAGE

The implementation supports the Batch Job Message Request option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_PBS_TRACK

The implementation supports the Track Batch Job Request option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_SW_DEV

The implementation supports the Software Development Utilities option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_POSIX2_UPE

The implementation supports the User Portability Utilities option. If this symbol has a value other than -1 or 0, it shall have the value 200112L.

_V6_ILP32_OFF32
The implementation provides a C-language compilation environment with 32-bit int, long, pointer, and off_t types.
_V6_ILP32_OFFBIG
The implementation provides a C-language compilation environment with 32-bit int, long, and pointer types and an off_t type using at least 64 bits.
_V6_LP64_OFF64
The implementation provides a C-language compilation environment with 32-bit int and 64-bit long, pointer, and off_t types.
_V6_LPBIG_OFFBIG
The implementation provides a C-language compilation environment with an int type using at least 32 bits and long, pointer, and off_t types using at least 64 bits.
_XBS5_ILP32_OFF32 (LEGACY)

The implementation provides a C-language compilation environment with 32-bit int, long, pointer, and off_t types.

_XBS5_ILP32_OFFBIG (LEGACY)

The implementation provides a C-language compilation environment with 32-bit int, long, and pointer types and an off_t type using at least 64 bits.

_XBS5_LP64_OFF64 (LEGACY)

The implementation provides a C-language compilation environment with 32-bit int and 64-bit long, pointer, and off_t types.

_XBS5_LPBIG_OFFBIG (LEGACY)

The implementation provides a C-language compilation environment with an int type using at least 32 bits and long, pointer, and off_t types using at least 64 bits.

_XOPEN_CRYPT

The implementation supports the X/Open Encryption Option Group.

_XOPEN_ENH_I18N
The implementation supports the Issue 4, Version 2 Enhanced Internationalization Option Group. This symbol shall always be set to a value other than -1.
_XOPEN_LEGACY
The implementation supports the Legacy Option Group.
_XOPEN_REALTIME
The implementation supports the X/Open Realtime Option Group.
_XOPEN_REALTIME_THREADS
The implementation supports the X/Open Realtime Threads Option Group.
_XOPEN_SHM
The implementation supports the Issue 4, Version 2 Shared Memory Option Group. This symbol shall always be set to a value other than -1.
_XOPEN_STREAMS
The implementation supports the XSI STREAMS Option Group.
_XOPEN_UNIX

The implementation supports the XSI extension.

Execution-Time Symbolic Constants

If any of the following constants are not defined in the <unistd.h> header, the value shall vary depending on the file to which it is applied.

If any of the following constants are defined to have value -1 in the <unistd.h> header, the implementation shall not provide the option on any file; if any are defined to have a value other than -1 in the <unistd.h> header, the implementation shall provide the option on all applicable files.

All of the following constants, whether defined in <unistd.h> or not, may be queried with respect to a specific file using the pathconf() or fpathconf() functions:

_POSIX_ASYNC_IO
Asynchronous input or output operations may be performed for the associated file.
_POSIX_PRIO_IO
Prioritized input or output operations may be performed for the associated file.
_POSIX_SYNC_IO
Synchronized input or output operations may be performed for the associated file.

Constants for Functions

The following symbolic constant shall be defined:

NULL
Null pointer

The following symbolic constants shall be defined for the access() function:

F_OK
Test for existence of file.
R_OK
Test for read permission.
W_OK
Test for write permission.
X_OK
Test for execute (search) permission.

The constants F_OK, R_OK, W_OK, and X_OK and the expressions R_OK|W_OK, R_OK|X_OK, and R_OK|W_OK|X_OK shall all have distinct values.

The following symbolic constants shall be defined for the confstr() function:

_CS_PATH
This is the value for the PATH environment variable that finds all standard utilities.
_CS_POSIX_V6_ILP32_OFF32_CFLAGS
If sysconf(_SC_V6_ILP32_OFF32) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of initial options to be given to the c99 utility to build an application using a programming model with 32-bit int, long, pointer, and off_t types.
_CS_POSIX_V6_ILP32_OFF32_LDFLAGS
If sysconf(_SC_V6_ILP32_OFF32) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of final options to be given to the c99 utility to build an application using a programming model with 32-bit int, long, pointer, and off_t types.
_CS_POSIX_V6_ILP32_OFF32_LIBS
If sysconf(_SC_V6_ILP32_OFF32) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of libraries to be given to the c99 utility to build an application using a programming model with 32-bit int, long, pointer, and off_t types.
_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS
If sysconf(_SC_V6_ILP32_OFFBIG) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of initial options to be given to the c99 utility to build an application using a programming model with 32-bit int, long, and pointer types, and an off_t type using at least 64 bits.
_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS
If sysconf(_SC_V6_ILP32_OFFBIG) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of final options to be given to the c99 utility to build an application using a programming model with 32-bit int, long, and pointer types, and an off_t type using at least 64 bits.
_CS_POSIX_V6_ILP32_OFFBIG_LIBS
If sysconf(_SC_V6_ILP32_OFFBIG) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of libraries to be given to the c99 utility to build an application using a programming model with 32-bit int, long, and pointer types, and an off_t type using at least 64 bits.
_CS_POSIX_V6_LP64_OFF64_CFLAGS
If sysconf(_SC_V6_LP64_OFF64) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of initial options to be given to the c99 utility to build an application using a programming model with 32-bit int and 64-bit long, pointer, and off_t types.
_CS_POSIX_V6_LP64_OFF64_LDFLAGS
If sysconf(_SC_V6_LP64_OFF64) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of final options to be given to the c99 utility to build an application using a programming model with 32-bit int and 64-bit long, pointer, and off_t types.
_CS_POSIX_V6_LP64_OFF64_LIBS
If sysconf(_SC_V6_LP64_OFF64) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of libraries to be given to the c99 utility to build an application using a programming model with 32-bit int and 64-bit long, pointer, and off_t types.
_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS
If sysconf(_SC_V6_LPBIG_OFFBIG) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of initial options to be given to the c99 utility to build an application using a programming model with an int type using at least 32 bits and long, pointer, and off_t types using at least 64 bits.
_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS
If sysconf(_SC_V6_LPBIG_OFFBIG) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of final options to be given to the c99 utility to build an application using a programming model with an int type using at least 32 bits and long, pointer, and off_t types using at least 64 bits.
_CS_POSIX_V6_LPBIG_OFFBIG_LIBS
If sysconf(_SC_V6_LPBIG_OFFBIG) returns -1, the meaning of this value is unspecified. Otherwise, this value is the set of libraries to be given to the c99 utility to build an application using a programming model with an int type using at least 32 bits and long, pointer, and off_t types using at least 64 bits.
_CS_POSIX_V6_WIDTH_RESTRICTED_ENVS
This value is a <newline>-separated list of names of programming environments supported by the implementation in which the widths of the blksize_t, cc_t, mode_t, nfds_t, pid_t, ptrdiff_t, size_t, speed_t, ssize_t, suseconds_t, tcflag_t, useconds_t, wchar_t, and wint_t types are no greater than the width of type long.

The following symbolic constants are reserved for compatibility with Issue 5:

_CS_XBS5_ILP32_OFF32_CFLAGS (LEGACY)
_CS_XBS5_ILP32_OFF32_LDFLAGS (LEGACY)
_CS_XBS5_ILP32_OFF32_LIBS (LEGACY)
_CS_XBS5_ILP32_OFF32_LINTFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_CFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LDFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LIBS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LINTFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_CFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_LDFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_LIBS (LEGACY)
_CS_XBS5_LP64_OFF64_LINTFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_CFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LDFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LIBS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LINTFLAGS (LEGACY)

The following symbolic constants shall be defined for the lseek() and fcntl() functions and shall have distinct values:

SEEK_CUR
Set file offset to current plus offset.
SEEK_END
Set file offset to EOF plus offset.
SEEK_SET
Set file offset to offset.

The following symbolic constants shall be defined as possible values for the function argument to the lockf() function:

F_LOCK
Lock a section for exclusive use.
F_TEST
Test section for locks by other processes.
F_TLOCK
Test and lock a section for exclusive use.
F_ULOCK
Unlock locked sections.

The following symbolic constants shall be defined for pathconf():

_PC_ALLOC_SIZE_MIN
_PC_ASYNC_IO
_PC_CHOWN_RESTRICTED
_PC_FILESIZEBITS
_PC_LINK_MAX
_PC_MAX_CANON
_PC_MAX_INPUT
_PC_NAME_MAX
_PC_NO_TRUNC
_PC_PATH_MAX
_PC_PIPE_BUF
_PC_PRIO_IO
_PC_REC_INCR_XFER_SIZE
_PC_REC_MIN_XFER_SIZE
_PC_REC_XFER_ALIGN
_PC_SYMLINK_MAX
_PC_SYNC_IO
_PC_VDISABLE

The following symbolic constants shall be defined for sysconf():

_SC_2_C_BIND
_SC_2_C_DEV
_SC_2_C_VERSION
_SC_2_CHAR_TERM
_SC_2_FORT_DEV
_SC_2_FORT_RUN
_SC_2_LOCALEDEF
_SC_2_PBS
_SC_2_PBS_ACCOUNTING
_SC_2_PBS_CHECKPOINT
_SC_2_PBS_LOCATE
_SC_2_PBS_MESSAGE
_SC_2_PBS_TRACK
_SC_2_SW_DEV
_SC_2_UPE
_SC_2_VERSION
_SC_ADVISORY_INFO
_SC_ARG_MAX
_SC_AIO_LISTIO_MAX
_SC_AIO_MAX
_SC_AIO_PRIO_DELTA_MAX
_SC_ASYNCHRONOUS_IO
_SC_ATEXIT_MAX
_SC_BARRIERS
_SC_BC_BASE_MAX
_SC_BC_DIM_MAX
_SC_BC_SCALE_MAX
_SC_BC_STRING_MAX
_SC_CHILD_MAX
_SC_CLK_TCK
_SC_CLOCK_SELECTION
_SC_COLL_WEIGHTS_MAX
_SC_CPUTIME
_SC_DELAYTIMER_MAX
_SC_EXPR_NEST_MAX
_SC_FILE_LOCKING
_SC_FSYNC
_SC_GETGR_R_SIZE_MAX
_SC_GETPW_R_SIZE_MAX
_SC_HOST_NAME_MAX
_SC_IOV_MAX
_SC_IPV6
_SC_JOB_CONTROL
_SC_LINE_MAX
_SC_LOGIN_NAME_MAX
_SC_MAPPED_FILES
_SC_MEMLOCK
_SC_MEMLOCK_RANGE
_SC_MEMORY_PROTECTION
_SC_MESSAGE_PASSING
_SC_MONOTONIC_CLOCK
_SC_MQ_OPEN_MAX
_SC_MQ_PRIO_MAX
_SC_NGROUPS_MAX
_SC_OPEN_MAX
_SC_PAGE_SIZE
_SC_PAGESIZE
_SC_PRIORITIZED_IO
_SC_PRIORITY_SCHEDULING
_SC_RAW_SOCKETS
_SC_RE_DUP_MAX
_SC_READER_WRITER_LOCKS
_SC_REALTIME_SIGNALS
_SC_REGEXP
_SC_RTSIG_MAX
_SC_SAVED_IDS
_SC_SEMAPHORES
_SC_SEM_NSEMS_MAX
_SC_SEM_VALUE_MAX
_SC_SHARED_MEMORY_OBJECTS
_SC_SHELL
_SC_SIGQUEUE_MAX
_SC_SPAWN
_SC_SPIN_LOCKS
_SC_SPORADIC_SERVER
_SC_STREAM_MAX
_SC_SYMLOOP_MAX
_SC_SYNCHRONIZED_IO
_SC_THREAD_ATTR_STACKADDR
_SC_THREAD_ATTR_STACKSIZE
_SC_THREAD_CPUTIME
_SC_THREAD_DESTRUCTOR_ITERATIONS
_SC_THREAD_KEYS_MAX
_SC_THREAD_PRIO_INHERIT
_SC_THREAD_PRIO_PROTECT
_SC_THREAD_PRIORITY_SCHEDULING
_SC_THREAD_PROCESS_SHARED
_SC_THREAD_SAFE_FUNCTIONS
_SC_THREAD_SPORADIC_SERVER
_SC_THREAD_STACK_MIN
_SC_THREAD_THREADS_MAX
_SC_TIMEOUTS
_SC_THREADS
_SC_TIMER_MAX
_SC_TIMERS
_SC_TRACE
_SC_TRACE_EVENT_FILTER
_SC_TRACE_INHERIT
_SC_TRACE_LOG
_SC_TTY_NAME_MAX
_SC_TYPED_MEMORY_OBJECTS
_SC_TZNAME_MAX
_SC_V6_ILP32_OFF32
_SC_V6_ILP32_OFFBIG
_SC_V6_LP64_OFF64
_SC_V6_LPBIG_OFFBIG
_SC_VERSION
_SC_XBS5_ILP32_OFF32 (LEGACY)
_SC_XBS5_ILP32_OFFBIG (LEGACY)
_SC_XBS5_LP64_OFF64 (LEGACY)
_SC_XBS5_LPBIG_OFFBIG (LEGACY)
_SC_XOPEN_CRYPT
_SC_XOPEN_ENH_I18N
_SC_XOPEN_LEGACY
_SC_XOPEN_REALTIME
_SC_XOPEN_REALTIME_THREADS
_SC_XOPEN_SHM
_SC_XOPEN_STREAMS
_SC_XOPEN_UNIX
_SC_XOPEN_VERSION
_SC_XOPEN_XCU_VERSION

The two constants _SC_PAGESIZE and _SC_PAGE_SIZE may be defined to have the same value.

The following symbolic constants shall be defined for file streams:

STDERR_FILENO
File number of stderr; 2.
STDIN_FILENO
File number of stdin; 0.
STDOUT_FILENO
File number of stdout; 1.

Type Definitions

The size_t, ssize_t, uid_t, gid_t, off_t, pid_t, and useconds_t types shall be defined as described in <sys/types.h>.

The intptr_t type shall be defined as described in <inttypes.h>.

Declarations

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int          access(const char *, int);
unsigned     alarm(unsigned);
int          chdir(const char *);
int          chown(const char *, uid_t, gid_t);
int          close(int);
size_t       confstr(int, char *, size_t);

char        *crypt(const char *, const char *);
char        *ctermid(char *);

int          dup(int);

int          dup2(int, int);

void         encrypt(char[64], int);

int          execl(const char *, const char *, ...);
int          execle(const char *, const char *, ...);
int          execlp(const char *, const char *, ...);
int          execv(const char *, char *const []);
int          execve(const char *, char *const [], char *const []);
int          execvp(const char *, char *const []);
void        _exit(int);
int          fchown(int, uid_t, gid_t);

int          fchdir(int);

int          fdatasync(int);

pid_t        fork(void);
long         fpathconf(int, int);

int          fsync(int);

int          ftruncate(int, off_t);
char        *getcwd(char *, size_t);
gid_t        getegid(void);
uid_t        geteuid(void);
gid_t        getgid(void);
int          getgroups(int, gid_t []);

long         gethostid(void);

int          gethostname(char *, size_t);
char        *getlogin(void);
int          getlogin_r(char *, size_t);
int          getopt(int, char * const [], const char *);

pid_t        getpgid(pid_t);

pid_t        getpgrp(void);
pid_t        getpid(void);
pid_t        getppid(void);

pid_t        getsid(pid_t);

uid_t        getuid(void);

char        *getwd(char *); (LEGACY )

int          isatty(int);

int          lchown(const char *, uid_t, gid_t);

int          link(const char *, const char *);

int          lockf(int, int, off_t);

off_t        lseek(int, off_t, int);

int          nice(int);

long         pathconf(const char *, int);
int          pause(void);
int          pipe(int [2]);

ssize_t      pread(int, void *, size_t, off_t);
ssize_t      pwrite(int, const void *, size_t, off_t);

ssize_t      read(int, void *, size_t);
ssize_t      readlink(const char *restrict, char *restrict, size_t);
int          rmdir(const char *);
int          setegid(gid_t);
int          seteuid(uid_t);
int          setgid(gid_t);

int          setpgid(pid_t, pid_t);

pid_t        setpgrp(void);
int          setregid(gid_t, gid_t);
int          setreuid(uid_t, uid_t);

pid_t        setsid(void);
int          setuid(uid_t);
unsigned     sleep(unsigned);

void         swab(const void *restrict, void *restrict, ssize_t);
int          symlink(const char *, const char *);
void         sync(void);

long         sysconf(int);
pid_t        tcgetpgrp(int);
int          tcsetpgrp(int, pid_t);

int          truncate(const char *, off_t);

char        *ttyname(int);
int          ttyname_r(int, char *, size_t);

useconds_t   ualarm(useconds_t, useconds_t);

int          unlink(const char *);

int          usleep(useconds_t);
pid_t        vfork(void);

ssize_t      write(int, const void *, size_t);

Implementations may also include the pthread_atfork() prototype as defined in <pthread.h> .

The following external variables shall be declared:

extern char  *optarg;
extern int    optind, opterr, optopt;

The following sections are informative.

APPLICATION USAGE

IEEE Std 1003.1-2001 only describes the behavior of systems that claim conformance to it. However, application developers who want to write applications that adapt to other versions of IEEE Std 1003.1 (or to systems that do not conform to any POSIX standard) may find it useful to code them so as to conditionally compile different code depending on the value of _POSIX_VERSION, for example:

#if _POSIX_VERSION >= 200112L
/* Use the newer function that copes with large files. */
off_t pos=ftello(fp);
#else
/* Either this is an old version of POSIX, or _POSIX_VERSION is
   not even defined, so use the traditional function. */
long pos=ftell(fp);
#endif

Earlier versions of IEEE Std 1003.1 and of the Single UNIX Specification can be identified by the following macros:

POSIX.1-1988 standard
_POSIX_VERSION==198808L
POSIX.1-1990 standard
_POSIX_VERSION==199009L
ISO POSIX-1:1996 standard
_POSIX_VERSION==199506L
Single UNIX Specification, Version 1
_XOPEN_UNIX and _XOPEN_VERSION==4
Single UNIX Specification, Version 2
_XOPEN_UNIX and _XOPEN_VERSION==500

IEEE Std 1003.1-2001 does not make any attempt to define application binary interaction with the underlying operating system. However, application developers may find it useful to query _SC_VERSION at runtime via sysconf() to determine whether the current version of the operating system supports the necessary functionality as in the following program fragment:

if (sysconf(_SC_VERSION) < 200112L) {
    fprintf(stderr, "POSIX.1-2001 system required, terminating \n");
    exit(1);
}

New applications should not use _XOPEN_SHM or _XOPEN_ENH_I18N.

RATIONALE

As IEEE Std 1003.1-2001 evolved, certain options became sufficiently standardized that it was concluded that simply requiring one of the option choices was simpler than retaining the option. However, for backwards-compatibility, the option flags (with required constant values) are retained.

Version Test Macros

The standard developers considered altering the definition of _POSIX_VERSION and removing _SC_VERSION from the specification of sysconf() since the utility to an application was deemed by some to be minimal, and since the implementation of the functionality is potentially problematic. However, they recognized that support for existing application binaries is a concern to manufacturers, application developers, and the users of implementations conforming to IEEE Std 1003.1-2001.

While the example using _SC_VERSION in the APPLICATION USAGE section does not provide the greatest degree of imaginable utility to the application developer or user, it is arguably better than a core file or some other equally obscure result. (It is also possible for implementations to encode and recognize application binaries compiled in various POSIX.1-conforming environments, and modify the semantics of the underlying system to conform to the expectations of the application.) For the reasons outlined in the preceding paragraphs and in the APPLICATION USAGE section, the standard developers elected to retain the _POSIX_VERSION and _SC_VERSION functionality.

Compile-Time Symbolic Constants for System-Wide Options

IEEE Std 1003.1-2001 now includes support in certain areas for the newly adopted policy governing options and stubs.

This policy provides flexibility for implementations in how they support options. It also specifies how conforming applications can adapt to different implementations that support different sets of options. It allows the following:

1.
If an implementation has no interest in supporting an option, it does not have to provide anything associated with that option beyond the announcement that it does not support it.

2.
An implementation can support a partial or incompatible version of an option (as a non-standard extension) as long as it does not claim to support the option.

3.
An application can determine whether the option is supported. A strictly conforming application must check this announcement mechanism before first using anything associated with the option.

There is an important implication of this policy. IEEE Std 1003.1-2001 cannot dictate the behavior of interfaces associated with an option when the implementation does not claim to support the option. In particular, it cannot require that a function associated with an unsupported option will fail if it does not perform as specified. However, this policy does not prevent a standard from requiring certain functions to always be present, but that they shall always fail on some implementations. The setpgid() function in the POSIX.1-1990 standard, for example, is considered appropriate.

The POSIX standards include various options, and the C-language binding support for an option implies that the implementation must supply data types and function interfaces. An application must be able to discover whether the implementation supports each option.

Any application must consider the following three cases for each option:

1.
Option never supported.

The implementation advertises at compile time that the option will never be supported. In this case, it is not necessary for the implementation to supply any of the data types or function interfaces that are provided only as part of the option. The implementation might provide data types and functions that are similar to those defined by IEEE Std 1003.1-2001, but there is no guarantee for any particular behavior.

2.
Option always supported.

The implementation advertises at compile time that the option will always be supported. In this case, all data types and function interfaces shall be available and shall operate as specified.

3.
Option might or might not be supported.

Some implementations might not provide a mechanism to specify support of options at compile time. In addition, the implementation might be unable or unwilling to specify support or non-support at compile time. In either case, any application that might use the option at runtime must be able to compile and execute. The implementation must provide, at compile time, all data types and function interfaces that are necessary to allow this. In this situation, there must be a mechanism that allows the application to query, at runtime, whether the option is supported. If the application attempts to use the option when it is not supported, the result is unspecified unless explicitly specified otherwise in IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

<inttypes.h> , <limits.h> , <sys/socket.h> , <sys/types.h>
, <termios.h> , <wctype.h> , the System Interfaces volume
of IEEE Std 1003.1-2001, access(), alarm(), chdir(),
chown(), close(), crypt(), ctermid(), dup(),
encrypt(), environ, exec, exit(), fchdir(),
fchown(), fcntl(), fork(), fpathconf(), fsync(),
ftruncate(), getcwd(), getegid(), geteuid(),
getgid(), getgroups(), gethostid(), gethostname(),
getlogin(), getpgid(), getpgrp(), getpid(),
getppid(), getsid(), getuid(), isatty(), lchown(),
link(), lockf(), lseek(), nice(), pathconf(),
pause(), pipe(), read(), readlink(), rmdir(),
setgid(), setpgid(), setpgrp(), setregid(),
setreuid(), setsid(), setuid(), sleep(), swab(),
symlink(), sync(), sysconf(), tcgetpgrp(),
tcsetpgrp(), truncate(), ttyname(), ualarm(),
unlink(), usleep(), vfork(), write()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_ipc.h(0p)

<sys/ipc.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/ipc.h - XSI interprocess communication access structure

SYNOPSIS

#include <sys/ipc.h>

DESCRIPTION

The <sys/ipc.h> header is used by three mechanisms for XSI interprocess communication (IPC): messages, semaphores, and shared memory. All use a common structure type, ipc_perm, to pass information used in determining permission to perform an IPC operation.

The ipc_perm structure shall contain the following members:

uid_t    uid    Owner's user ID.
gid_t    gid    Owner's group ID.
uid_t    cuid   Creator's user ID.
gid_t    cgid   Creator's group ID.
mode_t   mode   Read/write permission.

The uid_t, gid_t, mode_t, and key_t types shall be defined as described in <sys/types.h> .

Definitions shall be provided for the following constants:

Mode bits:

IPC_CREAT
Create entry if key does not exist.
IPC_EXCL
Fail if key exists.
IPC_NOWAIT
Error if request must wait.

Keys:

IPC_PRIVATE
Private key.

Control commands:

IPC_RMID
Remove identifier.
IPC_SET
Set options.
IPC_STAT
Get options.

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

key_t  ftok(const char *, int);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, ftok()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


monetary.h(0p)

<monetary.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

monetary.h - monetary types

SYNOPSIS

#include <monetary.h>

DESCRIPTION

The <monetary.h> header shall define the following types:

size_t
As described in <stddef.h> .
ssize_t
As described in <sys/types.h> .

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

ssize_t  strfmon(char *restrict, size_t, const char *restrict, ...);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, strfmon()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_shm.h(0p)

<sys/shm.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/shm.h - XSI shared memory facility

SYNOPSIS

#include <sys/shm.h>

DESCRIPTION

The <sys/shm.h> header shall define the following symbolic constants:

SHM_RDONLY
Attach read-only (else read-write).
SHM_RND
Round attach address to SHMLBA.

The <sys/shm.h> header shall define the following symbolic value:

SHMLBA
Segment low boundary address multiple.

The following data types shall be defined through typedef:

shmatt_t
Unsigned integer used for the number of current attaches that must be able to store values at least as large as a type unsigned short.

The shmid_ds structure shall contain the following members:

struct ipc_perm shm_perm   Operation permission structure.
size_t          shm_segsz  Size of segment in bytes.
pid_t           shm_lpid   Process ID of last shared memory operation.
pid_t           shm_cpid   Process ID of creator.
shmatt_t        shm_nattch Number of current attaches.
time_t          shm_atime  Time of last shmat
 ().
time_t          shm_dtime  Time of last shmdt
 ().
time_t          shm_ctime  Time of last change by shmctl
 ().

The pid_t, time_t, key_t, and size_t types shall be defined as described in <sys/types.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void *shmat(int, const void *, int);
int   shmctl(int, int, struct shmid_ds *);
int   shmdt(const void *);
int   shmget(key_t, size_t, int);

In addition, all of the symbols from <sys/ipc.h> shall be defined when this header is included.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/ipc.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, shmat(), shmctl(), shmdt(), shmget()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stddef.h(0p)

<stddef.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stddef.h - standard type definitions

SYNOPSIS

#include <stddef.h>

DESCRIPTION

The <stddef.h> header shall define the following macros:

NULL
Null pointer constant.
offsetof(type, member-designator)

Integer constant expression of type size_t, the value of which is the offset in bytes to the structure member (member-designator), from the beginning of its structure (type).

The <stddef.h> header shall define the following types:

ptrdiff_t
Signed integer type of the result of subtracting two pointers.
wchar_t
Integer type whose range of values can represent distinct wide-character codes for all members of the largest character set specified among the locales supported by the compilation environment: the null character has the code value 0 and each member of the portable character set has a code value equal to its value when used as the lone character in an integer character constant.
size_t
Unsigned integer type of the result of the sizeof operator.

The implementation shall support one or more programming environments in which the widths of ptrdiff_t, size_t, and wchar_t are no greater than the width of type long. The names of these programming environments can be obtained using the confstr() function or the getconf utility.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<wchar.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, confstr(), the Shell and Utilities volume of IEEE Std 1003.1-2001, getconf

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fenv.h(0p)

<fenv.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fenv.h - floating-point environment

SYNOPSIS

#include <fenv.h>

DESCRIPTION

The <fenv.h> header shall define the following data types through typedef:

fenv_t
Represents the entire floating-point environment. The floating-point environment refers collectively to any floating-point status flags and control modes supported by the implementation.
fexcept_t
Represents the floating-point status flags collectively, including any status the implementation associates with the flags. A floating-point status flag is a system variable whose value is set (but never cleared) when a floating-point exception is raised, which occurs as a side effect of exceptional floating-point arithmetic to provide auxiliary information. A floating-point control mode is a system variable whose value may be set by the user to affect the subsequent behavior of floating-point arithmetic.

The <fenv.h> header shall define the following constants if and only if the implementation supports the floating-point exception by means of the floating-point functions feclearexcept(), fegetexceptflag(), feraiseexcept(), fesetexceptflag(), and fetestexcept(). Each expands to an integer constant expression with values such that bitwise-inclusive ORs of all combinations of the constants result in distinct values.

FE_DIVBYZERO
FE_INEXACT
FE_INVALID
FE_OVERFLOW
FE_UNDERFLOW

The <fenv.h> header shall define the following constant, which is simply the bitwise-inclusive OR of all floating-point exception constants defined above:

FE_ALL_EXCEPT

The <fenv.h> header shall define the following constants if and only if the implementation supports getting and setting the represented rounding direction by means of the fegetround() and fesetround() functions. Each expands to an integer constant expression whose values are distinct non-negative vales.

FE_DOWNWARD
FE_TONEAREST
FE_TOWARDZERO
FE_UPWARD

The <fenv.h> header shall define the following constant, which represents the default floating-point environment (that is, the one installed at program startup) and has type pointer to const-qualified fenv_t. It can be used as an argument to the functions within the <fenv.h> header that manage the floating-point environment.

FE_DFL_ENV

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int  feclearexcept(int);
int  fegetexceptflag(fexcept_t *, int);
int  feraiseexcept(int);
int  fesetexceptflag(const fexcept_t *, int);
int  fetestexcept(int);
int  fegetround(void);
int  fesetround(int);
int  fegetenv(fenv_t *);
int  feholdexcept(fenv_t *);
int  fesetenv(const fenv_t *);
int  feupdateenv(const fenv_t *);

The FENV_ACCESS pragma provides a means to inform the implementation when an application might access the floating-point environment to test floating-point status flags or run under non-default floating-point control modes. The pragma shall occur either outside external declarations or preceding all explicit declarations and statements inside a compound statement. When outside external declarations, the pragma takes effect from its occurrence until another FENV_ACCESS pragma is encountered, or until the end of the translation unit. When inside a compound statement, the pragma takes effect from its occurrence until another FENV_ACCESS pragma is encountered (including within a nested compound statement), or until the end of the compound statement; at the end of a compound statement the state for the pragma is restored to its condition just before the compound statement. If this pragma is used in any other context, the behavior is undefined. If part of an application tests floating-point status flags, sets floating-point control modes, or runs under non-default mode settings, but was translated with the state for the FENV_ACCESS pragma off, the behavior is undefined. The default state (on or off) for the pragma is implementation-defined. (When execution passes from a part of the application translated with FENV_ACCESS off to a part translated with FENV_ACCESS on, the state of the floating-point status flags is unspecified and the floating-point control modes have their default settings.)

The following sections are informative.

APPLICATION USAGE

This header is designed to support the floating-point exception status flags and directed-rounding control modes required by the IEC 60559:1989 standard, and other similar floating-point state information. Also it is designed to facilitate code portability among all systems.

Certain application programming conventions support the intended model of use for the floating-point environment:

*
A function call does not alter its caller's floating-point control modes, clear its caller's floating-point status flags, nor depend on the state of its caller's floating-point status flags unless the function is so documented.

*
A function call is assumed to require default floating-point control modes, unless its documentation promises otherwise.

*
A function call is assumed to have the potential for raising floating-point exceptions, unless its documentation promises otherwise.

With these conventions, an application can safely assume default floating-point control modes (or be unaware of them). The responsibilities associated with accessing the floating-point environment fall on the application that does so explicitly.

Even though the rounding direction macros may expand to constants corresponding to the values of FLT_ROUNDS, they are not required to do so.

For example:

#include <fenv.h>
void f(double x)
{
    #pragma STDC FENV_ACCESS ON
    void g(double);
    void h(double);
    /* ... */
    g(x + 1);
    h(x + 1);
    /* ... */
}

If the function g() might depend on status flags set as a side effect of the first x+1, or if the second x+1 might depend on control modes set as a side effect of the call to function g(), then the application shall contain an appropriately placed invocation as follows:

#pragma STDC FENV_ACCESS ON

RATIONALE

The fexcept_t Type

fexcept_t does not have to be an integer type. Its values must be obtained by a call to fegetexceptflag(), and cannot be created by logical operations from the exception macros. An implementation might simply implement fexcept_t as an int and use the representations reflected by the exception macros, but is not required to; other representations might contain extra information about the exceptions. fexcept_t might be a struct with a member for each exception (that might hold the address of the first or last floating-point instruction that caused that exception). The ISO/IEC 9899:1999 standard makes no claims about the internals of an fexcept_t, and so the user cannot inspect it.

Exception and Rounding Macros

Macros corresponding to unsupported modes and rounding directions are not defined by the implementation and must not be defined by the application. An application might use #ifdef to test for this.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, feclearexcept(),
fegetenv(), fegetexceptflag(), fegetround(),
feholdexcept(), feraiseexcept(), fesetenv(), fesetexceptflag(),
fesetround(),
fetestexcept(), feupdateenv()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


semaphore.h(0p)

<semaphore.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

semaphore.h - semaphores (REALTIME)

SYNOPSIS

#include <semaphore.h>

DESCRIPTION

The <semaphore.h> header shall define the sem_t type, used in performing semaphore operations. The semaphore may be implemented using a file descriptor, in which case applications are able to open up at least a total of {OPEN_MAX} files and semaphores. The symbol SEM_FAILED shall be defined (see sem_open()).

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    sem_close(sem_t *);
int    sem_destroy(sem_t *);
int    sem_getvalue(sem_t *restrict, int *restrict);
int    sem_init(sem_t *, int, unsigned);
sem_t *sem_open(const char *, int, ...);
int    sem_post(sem_t *);

int    sem_timedwait(sem_t *restrict, const struct timespec *restrict);

int    sem_trywait(sem_t *);
int    sem_unlink(const char *);
int    sem_wait(sem_t *);

Inclusion of the <semaphore.h> header may make visible symbols defined in the headers <fcntl.h> and <sys/types.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<fcntl.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, sem_destroy(), sem_getvalue(), sem_init(), sem_open(), sem_post(), sem_timedwait(), sem_trywait(), sem_unlink(), sem_wait()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wctype.h(0p)

<wctype.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wctype.h - wide-character classification and mapping utilities

SYNOPSIS

#include <wctype.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <wctype.h> header shall define the following types:

wint_t
As described in <wchar.h> .
wctrans_t
A scalar type that can hold values which represent locale-specific character mappings.
wctype_t
As described in <wchar.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int       iswalnum(wint_t);
int       iswalpha(wint_t);
int       iswblank(wint_t);
int       iswcntrl(wint_t);
int       iswdigit(wint_t);
int       iswgraph(wint_t);
int       iswlower(wint_t);
int       iswprint(wint_t);
int       iswpunct(wint_t);
int       iswspace(wint_t);
int       iswupper(wint_t);
int       iswxdigit(wint_t);
int       iswctype(wint_t, wctype_t);
wint_t    towctrans(wint_t, wctrans_t);
wint_t    towlower(wint_t);
wint_t    towupper(wint_t);
wctrans_t wctrans(const char *);
wctype_t  wctype(const char *);

The <wctype.h> header shall define the following macro name:

WEOF
Constant expression of type wint_t that is returned by several MSE functions to indicate end-of-file.

For all functions described in this header that accept an argument of type wint_t, the value is representable as a wchar_t or equals the value of WEOF. If this argument has any other value, the behavior is undefined.

The behavior of these functions shall be affected by the LC_CTYPE category of the current locale.

Inclusion of the <wctype.h> header may make visible all symbols from the headers <ctype.h>, <stdarg.h>, <stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, and <wchar.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<ctype.h> , <locale.h> , <stdarg.h> , <stddef.h>
, <stdio.h> , <stdlib.h> , <string.h> , <time.h>
, <wchar.h> , the System Interfaces volume of IEEE Std 1003.1-2001,
iswalnum(), iswalpha(), iswblank(), iswcntrl(),
iswctype(), iswdigit(), iswgraph(), iswlower(),
iswprint(), iswpunct(), iswspace(), iswupper(),
iswxdigit(), setlocale(), towctrans(), towlower(),
towupper(), wctrans(), wctype()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


time.h(0p)

<time.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

time.h - time types

SYNOPSIS

#include <time.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <time.h> header shall declare the structure tm, which shall include at least the following members:

int    tm_sec   Seconds [0,60].
int    tm_min   Minutes [0,59].
int    tm_hour  Hour [0,23].
int    tm_mday  Day of month [1,31].
int    tm_mon   Month of year [0,11].
int    tm_year  Years since 1900.
int    tm_wday  Day of week [0,6] (Sunday =0).
int    tm_yday  Day of year [0,365].
int    tm_isdst Daylight Savings flag.

The value of tm_isdst shall be positive if Daylight Savings Time is in effect, 0 if Daylight Savings Time is not in effect, and negative if the information is not available.

The <time.h> header shall define the following symbolic names:

NULL
Null pointer constant.
CLOCKS_PER_SEC
A number used to convert the value returned by the clock() function into seconds.
CLOCK_PROCESS_CPUTIME_ID

The identifier of the CPU-time clock associated with the process making a clock() or timer*() function call.

CLOCK_THREAD_CPUTIME_ID

The identifier of the CPU-time clock associated with the thread making a clock() or timer*() function call.

The <time.h> header shall declare the structure timespec, which has at least the following members:

time_t  tv_sec    Seconds.
long    tv_nsec   Nanoseconds.

The <time.h> header shall also declare the itimerspec structure, which has at least the following members:

struct timespec  it_interval  Timer period.
struct timespec  it_value     Timer expiration.

The following manifest constants shall be defined:

CLOCK_REALTIME
The identifier of the system-wide realtime clock.
TIMER_ABSTIME
Flag indicating time is absolute. For functions taking timer objects, this refers to the clock associated with the timer.
CLOCK_MONOTONIC

The identifier for the system-wide monotonic clock, which is defined as a clock whose value cannot be set via clock_settime() and which cannot have backward clock jumps. The maximum possible clock jump shall be implementation-defined.

The clock_t, size_t, time_t, clockid_t, and timer_t types shall be defined as described in <sys/types.h> .

Although the value of CLOCKS_PER_SEC is required to be 1 million on all XSI-conformant systems, it may be variable on other systems, and it should not be assumed that CLOCKS_PER_SEC is a compile-time constant.

The <time.h> header shall provide a declaration for getdate_err.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

char      *asctime(const struct tm *);

char      *asctime_r(const struct tm *restrict, char *restrict);

clock_t    clock(void);

int        clock_getcpuclockid(pid_t, clockid_t *);

int        clock_getres(clockid_t, struct timespec *);
int        clock_gettime(clockid_t, struct timespec *);

int        clock_nanosleep(clockid_t, int, const struct timespec *,
               struct timespec *);

int        clock_settime(clockid_t, const struct timespec *);

char      *ctime(const time_t *);

char      *ctime_r(const time_t *, char *);

double     difftime(time_t, time_t);

struct tm *getdate(const char *);

struct tm *gmtime(const time_t *);

struct tm *gmtime_r(const time_t *restrict, struct tm *restrict);

struct tm *localtime(const time_t *);

struct tm *localtime_r(const time_t *restrict, struct tm *restrict);

time_t     mktime(struct tm *);

int        nanosleep(const struct timespec *, struct timespec *);

size_t     strftime(char *restrict, size_t, const char *restrict,
           const struct tm *restrict);

char      *strptime(const char *restrict, const char *restrict,
               struct tm *restrict);

time_t     time(time_t *);

int        timer_create(clockid_t, struct sigevent *restrict,
               timer_t *restrict);
int        timer_delete(timer_t);
int        timer_gettime(timer_t, struct itimerspec *);
int        timer_getoverrun(timer_t);
int        timer_settime(timer_t, int, const struct itimerspec *restrict,
               struct itimerspec *restrict);

void       tzset(void);

The following shall be declared as variables:

extern int    daylight;
extern long   timezone;

extern char  *tzname[];

Inclusion of the <time.h> header may make visible all symbols from the <signal.h> header.

The following sections are informative.

APPLICATION USAGE

The range [0,60] for tm_sec allows for the occasional leap second.

tm_year is a signed value; therefore, years before 1900 may be represented.

To obtain the number of clock ticks per second returned by the times() function, applications should call sysconf(_SC_CLK_TCK).

RATIONALE

The range [0,60] seconds allows for positive or negative leap seconds. The formal definition of UTC does not permit double leap seconds, so all mention of double leap seconds has been removed, and the range shortened from the former [0,61] seconds seen in previous versions of POSIX.

FUTURE DIRECTIONS

None.

SEE ALSO

<signal.h> , <sys/types.h> , the System
Interfaces volume of IEEE Std 1003.1-2001, asctime(), clock(),
clock_getcpuclockid(), clock_getres(), clock_nanosleep(),
ctime(), difftime(), getdate(), gmtime(),
localtime(), mktime(), nanosleep(), strftime(),
strptime(), sysconf(), time(), timer_create(),
timer_delete(), timer_getoverrun(), tzname, tzset(),
utime()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ndbm.h(0p)

<ndbm.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ndbm.h - definitions for ndbm database operations

SYNOPSIS

#include <ndbm.h>

DESCRIPTION

The <ndbm.h> header shall define the datum type as a structure that includes at least the following members:

void   *dptr  A pointer to the application's data.
size_t  dsize The size of the object pointed to by dptr.

The size_t type shall be defined as described in <stddef.h> .

The <ndbm.h> header shall define the DBM type.

The following constants shall be defined as possible values for the store_mode argument to dbm_store():

DBM_INSERT
Insertion of new entries only.
DBM_REPLACE
Allow replacing existing entries.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int     dbm_clearerr(DBM *);
void    dbm_close(DBM *);
int     dbm_delete(DBM *, datum);
int     dbm_error(DBM *);
datum   dbm_fetch(DBM *, datum);
datum   dbm_firstkey(DBM *);
datum   dbm_nextkey(DBM *);
DBM    *dbm_open(const char *, int, mode_t);
int     dbm_store(DBM *, datum, datum, int);

The mode_t type shall be defined through typedef as described in <sys/types.h> .

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<stddef.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, dbm_clearerr()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


syslog.h(0p)

<syslog.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

syslog.h - definitions for system error logging

SYNOPSIS

#include <syslog.h>

DESCRIPTION

The <syslog.h> header shall define the following symbolic constants, zero or more of which may be OR'ed together to form the logopt option of openlog():

LOG_PID
Log the process ID with each message.
LOG_CONS
Log to the system console on error.
LOG_NDELAY
Connect to syslog daemon immediately.
LOG_ODELAY
Delay open until syslog() is called.
LOG_NOWAIT
Do not wait for child processes.

The following symbolic constants shall be defined as possible values of the facility argument to openlog():

LOG_KERN
Reserved for message generated by the system.
LOG_USER
Message generated by a process.
LOG_MAIL
Reserved for message generated by mail system.
LOG_NEWS
Reserved for message generated by news system.
LOG_UUCP
Reserved for message generated by UUCP system.
LOG_DAEMON
Reserved for message generated by system daemon.
LOG_AUTH
Reserved for message generated by authorization daemon.
LOG_CRON
Reserved for message generated by clock daemon.
LOG_LPR
Reserved for message generated by printer system.
LOG_LOCAL0
Reserved for local use.
LOG_LOCAL1
Reserved for local use.
LOG_LOCAL2
Reserved for local use.
LOG_LOCAL3
Reserved for local use.
LOG_LOCAL4
Reserved for local use.
LOG_LOCAL5
Reserved for local use.
LOG_LOCAL6
Reserved for local use.
LOG_LOCAL7
Reserved for local use.

The following shall be declared as macros for constructing the maskpri argument to setlogmask(). The following macros expand to an expression of type int when the argument pri is an expression of type int:

LOG_MASK(pri)
A mask for priority pri.

The following constants shall be defined as possible values for the priority argument of syslog():

LOG_EMERG
A panic condition was reported to all processes.
LOG_ALERT
A condition that should be corrected immediately.
LOG_CRIT
A critical condition.
LOG_ERR
An error message.
LOG_WARNING
A warning message.
LOG_NOTICE
A condition requiring special handling.
LOG_INFO
A general information message.
LOG_DEBUG
A message useful for debugging programs.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void  closelog(void);
void  openlog(const char *, int, int);
int   setlogmask(int);
void  syslog(int, const char *, ...);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, closelog()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stdarg.h(0p)

<stdarg.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stdarg.h - handle variable argument list

SYNOPSIS

#include <stdarg.h>

void va_start(va_list ap, argN);
void va_copy(va_list dest, va_list src);
type va_arg(va_list ap, type);
void va_end(va_list ap);

DESCRIPTION

The <stdarg.h> header shall contain a set of macros which allows portable functions that accept variable argument lists to be written. Functions that have variable argument lists (such as printf()) but do not use these macros are inherently non-portable, as different systems use different argument-passing conventions.

The type va_list shall be defined for variables used to traverse the list.

The va_start() macro is invoked to initialize ap to the beginning of the list before any calls to va_arg().

The va_copy() macro initializes dest as a copy of src, as if the va_start() macro had been applied to dest followed by the same sequence of uses of the va_arg() macro as had previously been used to reach the present state of src. Neither the va_copy() nor va_start() macro shall be invoked to reinitialize dest without an intervening invocation of the va_end() macro for the same dest.

The object ap may be passed as an argument to another function; if that function invokes the va_arg() macro with parameter ap, the value of ap in the calling function is unspecified and shall be passed to the va_end() macro prior to any further reference to ap. The parameter argN is the identifier of the rightmost parameter in the variable parameter list in the function definition (the one just before the ...). If the parameter argN is declared with the register storage class, with a function type or array type, or with a type that is not compatible with the type that results after application of the default argument promotions, the behavior is undefined.

The va_arg() macro shall return the next argument in the list pointed to by ap. Each invocation of va_arg() modifies ap so that the values of successive arguments are returned in turn. The type parameter shall be a type name specified such that the type of a pointer to an object that has the specified type can be obtained simply by postfixing a '*' to type. If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases:

*
One type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types.

*
One type is a pointer to void and the other is a pointer to a character type.

*
Both types are pointers.

Different types can be mixed, but it is up to the routine to know what type of argument is expected.

The va_end() macro is used to clean up; it invalidates ap for use (unless va_start() or va_copy() is invoked again).

Each invocation of the va_start() and va_copy() macros shall be matched by a corresponding invocation of the va_end() macro in the same function.

Multiple traversals, each bracketed by va_start() ... va_end(), are possible.

EXAMPLES

This example is a possible implementation of execl():

#include <stdarg.h>

#define  MAXARGS     31

/*
 * execl is called by
 * execl(file, arg1, arg2, ..., (char *)(0));
 */
int execl(const char *file, const char *args, ...)
{
    va_list ap;
    char *array[MAXARGS +1];
    int argno = 0;

    va_start(ap, args);
    while (args != 0 && argno < MAXARGS)
    {
        array[argno++] = args;
        args = va_arg(ap, const char *);
    }
    array[argno] = (char *) 0;
    va_end(ap);
    return execv(file, array);
}

The following sections are informative.

APPLICATION USAGE

It is up to the calling routine to communicate to the called routine how many arguments there are, since it is not always possible for the called routine to determine this in any other way. For example, execl() is passed a null pointer to signal the end of the list. The printf() function can tell how many arguments are there by the format argument.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, exec, printf()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


trace.h(0p)

<trace.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

trace.h - tracing

SYNOPSIS

#include <trace.h>

DESCRIPTION

The <trace.h> header shall define the posix_trace_event_info structure that includes at least the following members:

trace_event_id_t  posix_event_id
pid_t             posix_pid
void             *posix_prog_address
int               posix_truncation_status
struct timespec   posix_timestamp

pthread_t         posix_thread_id

The <trace.h> header shall define the posix_trace_status_info structure that includes at least the following members:

int     posix_stream_status
int     posix_stream_full_status
int     posix_stream_overrun_status

int     posix_stream_flush_status
int     posix_stream_flush_error
int     posix_log_overrun_status
int     posix_log_full_status

The <trace.h> header shall define the following symbols:

POSIX_TRACE_ALL_EVENTS

POSIX_TRACE_APPEND

POSIX_TRACE_CLOSE_FOR_CHILD

POSIX_TRACE_FILTER

POSIX_TRACE_FLUSH
POSIX_TRACE_FLUSH_START
POSIX_TRACE_FLUSH_STOP
POSIX_TRACE_FLUSHING

POSIX_TRACE_FULL
POSIX_TRACE_LOOP
POSIX_TRACE_NO_OVERRUN

POSIX_TRACE_NOT_FLUSHING

POSIX_TRACE_NOT_FULL

POSIX_TRACE_INHERITED

POSIX_TRACE_NOT_TRUNCATED
POSIX_TRACE_OVERFLOW
POSIX_TRACE_OVERRUN
POSIX_TRACE_RESUME
POSIX_TRACE_RUNNING
POSIX_TRACE_START
POSIX_TRACE_STOP
POSIX_TRACE_SUSPENDED
POSIX_TRACE_SYSTEM_EVENTS
POSIX_TRACE_TRUNCATED_READ
POSIX_TRACE_TRUNCATED_RECORD
POSIX_TRACE_UNNAMED_USER_EVENT
POSIX_TRACE_UNTIL_FULL
POSIX_TRACE_WOPID_EVENTS

The following types shall be defined as described in <sys/types.h> :

trace_attr_t
trace_id_t
trace_event_id_t

trace_event_set_t

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int  posix_trace_attr_destroy(trace_attr_t *);
int  posix_trace_attr_getclockres(const trace_attr_t *,
         struct timespec *);
int  posix_trace_attr_getcreatetime(const trace_attr_t *,
         struct timespec *);
int  posix_trace_attr_getgenversion(const trace_attr_t *, char *);

int  posix_trace_attr_getinherited(const trace_attr_t *restrict,
         int *restrict);

int  posix_trace_attr_getlogfullpolicy(const trace_attr_t *restrict,
         int *restrict);
int  posix_trace_attr_getlogsize(const trace_attr_t *restrict,
         size_t *restrict);

int  posix_trace_attr_getmaxdatasize(const trace_attr_t *restrict,
         size_t *restrict);
int  posix_trace_attr_getmaxsystemeventsize(const trace_attr_t *restrict,
         size_t *restrict);
int  posix_trace_attr_getmaxusereventsize(const trace_attr_t *restrict,
         size_t, size_t *restrict);
int  posix_trace_attr_getname(const trace_attr_t *, char *);
int  posix_trace_attr_getstreamfullpolicy(const trace_attr_t *restrict,
         int *restrict);
int  posix_trace_attr_getstreamsize(const trace_attr_t *restrict,
         size_t *restrict);
int  posix_trace_attr_init(trace_attr_t *);

int  posix_trace_attr_setinherited(trace_attr_t *, int);

int  posix_trace_attr_setlogfullpolicy(trace_attr_t *, int);
int  posix_trace_attr_setlogsize(trace_attr_t *, size_t);

int  posix_trace_attr_setmaxdatasize(trace_attr_t *, size_t);
int  posix_trace_attr_setname(trace_attr_t *, const char *);
int  posix_trace_attr_setstreamsize(trace_attr_t *, size_t);
int  posix_trace_attr_setstreamfullpolicy(trace_attr_t *, int);
int  posix_trace_clear(trace_id_t);

int  posix_trace_close(trace_id_t);

int  posix_trace_create(pid_t, const trace_attr_t *restrict,
         trace_id_t *restrict);

int  posix_trace_create_withlog(pid_t, const trace_attr_t *restrict,
         int, trace_id_t *restrict);

void posix_trace_event(trace_event_id_t, const void *restrict, size_t);
int  posix_trace_eventid_equal(trace_id_t, trace_event_id_t,
         trace_event_id_t);
int  posix_trace_eventid_get_name(trace_id_t, trace_event_id_t, char *);
int  posix_trace_eventid_open(const char *restrict,
         trace_event_id_t *restrict);

int  posix_trace_eventset_add(trace_event_id_t, trace_event_set_t *);
int  posix_trace_eventset_del(trace_event_id_t, trace_event_set_t *);
int  posix_trace_eventset_empty(trace_event_set_t *);
int  posix_trace_eventset_fill(trace_event_set_t *, int);
int  posix_trace_eventset_ismember(trace_event_id_t,
         const trace_event_set_t *restrict, int *restrict);

int  posix_trace_eventtypelist_getnext_id(trace_id_t,
         trace_event_id_t *restrict, int *restrict);
int  posix_trace_eventtypelist_rewind(trace_id_t);

int  posix_trace_flush(trace_id_t);

int  posix_trace_get_attr(trace_id_t, trace_attr_t *);

int  posix_trace_get_filter(trace_id_t, trace_event_set_t *);

int  posix_trace_get_status(trace_id_t,
         struct posix_trace_status_info *);
int  posix_trace_getnext_event(trace_id_t,
         struct posix_trace_event_info *restrict , void *restrict,
         size_t, size_t *restrict, int *restrict);

int  posix_trace_open(int, trace_id_t *);
int  posix_trace_rewind(trace_id_t);

int  posix_trace_set_filter(trace_id_t, const trace_event_set_t *, int);

int  posix_trace_shutdown(trace_id_t);
int  posix_trace_start(trace_id_t);
int  posix_trace_stop(trace_id_t);

int  posix_trace_timedgetnext_event(trace_id_t,
         struct posix_trace_event_info *restrict, void *restrict,
         size_t, size_t *restrict, int *restrict,
         const struct timespec *restrict);

int  posix_trace_trid_eventid_open(trace_id_t, const char *restrict,
         trace_event_id_t *restrict);

int  posix_trace_trygetnext_event(trace_id_t,
         struct posix_trace_event_info *restrict, void *restrict, size_t,
         size_t *restrict, int *restrict);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001,
Section 2.11, Tracing, posix_trace_attr_destroy(), posix_trace_attr_getclockres(),
posix_trace_attr_getcreatetime(), posix_trace_attr_getgenversion(),
posix_trace_attr_getinherited(), posix_trace_attr_getlogfullpolicy(),
posix_trace_attr_getlogsize(), posix_trace_attr_getmaxdatasize(),
posix_trace_attr_getmaxsystemeventsize(), posix_trace_attr_getmaxusereventsize(),
posix_trace_attr_getname(), posix_trace_attr_getstreamfullpolicy(),
posix_trace_attr_getstreamsize(), posix_trace_attr_init(),
posix_trace_attr_setinherited(), posix_trace_attr_setlogfullpolicy(),
posix_trace_attr_setlogsize(), posix_trace_attr_setmaxdatasize(),
posix_trace_attr_setname(), posix_trace_attr_setstreamsize(),
posix_trace_attr_setstreamfullpolicy(), posix_trace_clear(),
posix_trace_close(), posix_trace_create(), posix_trace_create_withlog(),
posix_trace_event(), posix_trace_eventid_equal(), posix_trace_eventid_get_name(),
posix_trace_eventid_open(), posix_trace_eventtypelist_getnext_id(),
posix_trace_eventtypelist_rewind(), posix_trace_eventset_add(),
posix_trace_eventset_del(), posix_trace_eventset_empty(),
posix_trace_eventset_fill(), posix_trace_eventset_ismember(),
posix_trace_flush(), posix_trace_get_attr(), posix_trace_get_filter(),
posix_trace_get_status(), posix_trace_getnext_event(),
posix_trace_open(), posix_trace_rewind(), posix_trace_set_filter(),
posix_trace_shutdown(), posix_trace_start(), posix_trace_stop(),
posix_trace_timedgetnext_event(), posix_trace_trid_eventid_open(),
posix_trace_trygetnext_event()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_timeb.h(0p)

<sys/timeb.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/timeb.h - additional definitions for date and time

SYNOPSIS

#include <sys/timeb.h>

DESCRIPTION

The <sys/timeb.h> header shall define the timeb structure that includes at least the following members:

time_t         time     The seconds portion of the current time.
unsigned short millitm  The milliseconds portion of the current time.
short          timezone The local timezone in minutes west of Greenwich.
short          dstflag  TRUE if Daylight Savings Time is in effect.

The time_t type shall be defined as described in <sys/types.h> .

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

int   ftime(struct timeb *); (LEGACY )

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_select.h(0p)

<sys/select.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/select.h - select types

SYNOPSIS

#include <sys/select.h>

DESCRIPTION

The <sys/select.h> header shall define the timeval structure that includes at least the following members:

time_t         tv_sec      Seconds.
suseconds_t    tv_usec     Microseconds.

The time_t and suseconds_t types shall be defined as described in <sys/types.h> .

The sigset_t type shall be defined as described in <signal.h> .

The timespec structure shall be defined as described in <time.h> .

The <sys/select.h> header shall define the fd_set type as a structure.

Each of the following may be declared as a function, or defined as a macro, or both:

void FD_CLR(int fd, fd_set *fdset)

Clears the bit for the file descriptor fd in the file descriptor set fdset.

int FD_ISSET(int fd, fd_set *fdset)

Returns a non-zero value if the bit for the file descriptor fd is set in the file descriptor set by fdset, and 0 otherwise.

void FD_SET(int fd, fd_set *fdset)

Sets the bit for the file descriptor fd in the file descriptor set fdset.

void FD_ZERO(fd_set *fdset)

Initializes the file descriptor set fdset to have zero bits for all file descriptors.

If implemented as macros, these may evaluate their arguments more than once, so applications should ensure that the arguments they supply are never expressions with side effects.

The following shall be defined as a macro:

FD_SETSIZE

Maximum number of file descriptors in an fd_set structure.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int  pselect(int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
         const struct timespec *restrict, const sigset_t *restrict);
int  select(int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
         struct timeval *restrict);

Inclusion of the <sys/select.h> header may make visible all symbols from the headers <signal.h>, <sys/time.h>, and <time.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<signal.h> , <sys/time.h> , <sys/types.h> , <time.h> , the System Interfaces volume of IEEE Std 1003.1-2001, pselect(), select()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cpio.h(0p)

<cpio.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cpio.h - cpio archive values

SYNOPSIS

#include <cpio.h>

DESCRIPTION

Values needed by the c_mode field of the cpio archive format are described as follows:
Name | Description | Value (Octal)
C_IRUSR | Read by owner. | 0000400
C_IWUSR | Write by owner. | 0000200
C_IXUSR | Execute by owner. | 0000100
C_IRGRP | Read by group. | 0000040
C_IWGRP | Write by group. | 0000020
C_IXGRP | Execute by group. | 0000010
C_IROTH | Read by others. | 0000004
C_IWOTH | Write by others. | 0000002
C_IXOTH | Execute by others. | 0000001
C_ISUID | Set user ID. | 0004000
C_ISGID | Set group ID. | 0002000
C_ISVTX | On directories, restricted deletion flag. | 0001000
C_ISDIR | Directory. | 0040000
C_ISFIFO | FIFO. | 0010000
C_ISREG | Regular file. | 0100000
C_ISBLK | Block special. | 0060000
C_ISCHR | Character special. | 0020000
C_ISCTG | Reserved. | 0110000
C_ISLNK | Symbolic link. | 0120000
C_ISSOCK | Socket. | 0140000

The header shall define the symbolic constant:

MAGIC    "070707"

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Shell and Utilities volume of IEEE Std 1003.1-2001, pax

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


langinfo.h(0p)

<langinfo.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

langinfo.h - language information constants

SYNOPSIS

#include <langinfo.h>

DESCRIPTION

The <langinfo.h> header contains the constants used to identify items of langinfo data (see nl_langinfo()). The type of the constant, nl_item, shall be defined as described in <nl_types.h> .

The following constants shall be defined. The entries under Category indicate in which setlocale() category each item is defined.
Constant | Category | Meaning
CODESET | LC_CTYPE | Codeset name.
D_T_FMT | LC_TIME | String for formatting date and time.
D_FMT | LC_TIME | Date format string.
T_FMT | LC_TIME | Time format string.
T_FMT_AMPM | LC_TIME | a.m. or p.m. time format string.
AM_STR | LC_TIME | Ante-meridiem affix.
PM_STR | LC_TIME | Post-meridiem affix.
DAY_1 | LC_TIME | Name of the first day of the week (for example, Sunday).
DAY_2 | LC_TIME | Name of the second day of the week (for example, Monday).
DAY_3 | LC_TIME | Name of the third day of the week (for example, Tuesday).
DAY_4 | LC_TIME | Name of the fourth day of the week
 |  | (for example, Wednesday).
DAY_5 | LC_TIME | Name of the fifth day of the week (for example, Thursday).
DAY_6 | LC_TIME | Name of the sixth day of the week (for example, Friday).
DAY_7 | LC_TIME | Name of the seventh day of the week
 |  | (for example, Saturday).
ABDAY_1 | LC_TIME | Abbreviated name of the first day of the week.
ABDAY_2 | LC_TIME | Abbreviated name of the second day of the week.
ABDAY_3 | LC_TIME | Abbreviated name of the third day of the week.
ABDAY_4 | LC_TIME | Abbreviated name of the fourth day of the week.
ABDAY_5 | LC_TIME | Abbreviated name of the fifth day of the week.
ABDAY_6 | LC_TIME | Abbreviated name of the sixth day of the week.
ABDAY_7 | LC_TIME | Abbreviated name of the seventh day of the week.
MON_1 | LC_TIME | Name of the first month of the year.
MON_2 | LC_TIME | Name of the second month.
MON_3 | LC_TIME | Name of the third month.
MON_4 | LC_TIME | Name of the fourth month.
MON_5 | LC_TIME | Name of the fifth month.
MON_6 | LC_TIME | Name of the sixth month.
MON_7 | LC_TIME | Name of the seventh month.
MON_8 | LC_TIME | Name of the eighth month.
MON_9 | LC_TIME | Name of the ninth month.
MON_10 | LC_TIME | Name of the tenth month.
MON_11 | LC_TIME | Name of the eleventh month.
MON_12 | LC_TIME | Name of the twelfth month.
ABMON_1 | LC_TIME | Abbreviated name of the first month.
ABMON_2 | LC_TIME | Abbreviated name of the second month.
ABMON_3 | LC_TIME | Abbreviated name of the third month.
ABMON_4 | LC_TIME | Abbreviated name of the fourth month.
ABMON_5 | LC_TIME | Abbreviated name of the fifth month.
ABMON_6 | LC_TIME | Abbreviated name of the sixth month.
ABMON_7 | LC_TIME | Abbreviated name of the seventh month.
ABMON_8 | LC_TIME | Abbreviated name of the eighth month.
ABMON_9 | LC_TIME | Abbreviated name of the ninth month.
ABMON_10 | LC_TIME | Abbreviated name of the tenth month.
ABMON_11 | LC_TIME | Abbreviated name of the eleventh month.
ABMON_12 | LC_TIME | Abbreviated name of the twelfth month.
ERA | LC_TIME | Era description segments.
ERA_D_FMT | LC_TIME | Era date format string.
ERA_D_T_FMT | LC_TIME | Era date and time format string.
ERA_T_FMT | LC_TIME | Era time format string.
ALT_DIGITS | LC_TIME | Alternative symbols for digits.
RADIXCHAR | LC_NUMERIC | Radix character.
THOUSEP | LC_NUMERIC | Separator for thousands.
YESEXPR | LC_MESSAGES | Affirmative response expression.
NOEXPR | LC_MESSAGES | Negative response expression.
CRNCYSTR | LC_MONETARY | Local currency symbol, preceded by '-' if the symbol should appear before the value, '+' if the symbol should appear after the value, or '.' if the symbol should replace the radix character. If the local currency symbol is the empty string, implementations may return the empty string ( "" ).

If the locale's values for p_cs_precedes and n_cs_precedes do not match, the value of nl_langinfo(CRNCYSTR) is unspecified.

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

char *nl_langinfo(nl_item);

Inclusion of the <langinfo.h> header may also make visible all symbols from <nl_types.h>.

The following sections are informative.

APPLICATION USAGE

Wherever possible, users are advised to use functions compatible with those in the ISO C standard to access items of langinfo data. In particular, the strftime() function should be used to access date and time information defined in category LC_TIME . The localeconv() function should be used to access information corresponding to RADIXCHAR, THOUSEP, and CRNCYSTR.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, nl_langinfo(), localeconv(), strfmon(), strftime(), Locale

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


grp.h(0p)

<grp.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

grp.h - group structure

SYNOPSIS

#include <grp.h>

DESCRIPTION

The <grp.h> header shall declare the structure group which shall include the following members:

char   *gr_name The name of the group.
gid_t   gr_gid  Numerical group ID.
char  **gr_mem  Pointer to a null-terminated array of character
                pointers to member names.

The gid_t type shall be defined as described in <sys/types.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

struct group  *getgrgid(gid_t);
struct group  *getgrnam(const char *);

int            getgrgid_r(gid_t, struct group *, char *,
                   size_t, struct group **);
int            getgrnam_r(const char *, struct group *, char *,
                   size_t , struct group **);

struct group  *getgrent(void);
void           endgrent(void);
void           setgrent(void);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, endgrent(), getgrgid(), getgrnam()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


complex.h(0p)

<complex.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

complex.h - complex arithmetic

SYNOPSIS

#include <complex.h>

DESCRIPTION

The <complex.h> header shall define the following macros:

complex
Expands to _Complex.
_Complex_I
Expands to a constant expression of type const float _Complex, with the value of the imaginary unit (that is, a number i such that i**2=-1).
imaginary
Expands to _Imaginary.
_Imaginary_I
Expands to a constant expression of type const float _Imaginary with the value of the imaginary unit.
I
Expands to either _Imaginary_I or _Complex_I. If _Imaginary_I is not defined, I expands to _Complex_I.

The macros imaginary and _Imaginary_I shall be defined if and only if the implementation supports imaginary types.

An application may undefine and then, perhaps, redefine the complex, imaginary, and I macros.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

double               cabs(double complex);
float                cabsf(float complex);
long double          cabsl(long double complex);
double complex       cacos(double complex);
float complex        cacosf(float complex);
double complex       cacosh(double complex);
float complex        cacoshf(float complex);
long double complex  cacoshl(long double complex);
long double complex  cacosl(long double complex);
double               carg(double complex);
float                cargf(float complex);
long double          cargl(long double complex);
double complex       casin(double complex);
float complex        casinf(float complex);
double complex       casinh(double complex);
float complex        casinhf(float complex);
long double complex  casinhl(long double complex);
long double complex  casinl(long double complex);
double complex       catan(double complex);
float complex        catanf(float complex);
double complex       catanh(double complex);
float complex        catanhf(float complex);
long double complex  catanhl(long double complex);
long double complex  catanl(long double complex);
double complex       ccos(double complex);
float complex        ccosf(float complex);
double complex       ccosh(double complex);
float complex        ccoshf(float complex);
long double complex  ccoshl(long double complex);
long double complex  ccosl(long double complex);
double complex       cexp(double complex);
float complex        cexpf(float complex);
long double complex  cexpl(long double complex);
double               cimag(double complex);
float                cimagf(float complex);
long double          cimagl(long double complex);
double complex       clog(double complex);
float complex        clogf(float complex);
long double complex  clogl(long double complex);
double complex       conj(double complex);
float complex        conjf(float complex);
long double complex  conjl(long double complex);
double complex       cpow(double complex, double complex);
float complex        cpowf(float complex, float complex);
long double complex  cpowl(long double complex, long double complex);
double complex       cproj(double complex);
float complex        cprojf(float complex);
long double complex  cprojl(long double complex);
double               creal(double complex);
float                crealf(float complex);
long double          creall(long double complex);
double complex       csin(double complex);
float complex        csinf(float complex);
double complex       csinh(double complex);
float complex        csinhf(float complex);
long double complex  csinhl(long double complex);
long double complex  csinl(long double complex);
double complex       csqrt(double complex);
float complex        csqrtf(float complex);
long double complex  csqrtl(long double complex);
double complex       ctan(double complex);
float complex        ctanf(float complex);
double complex       ctanh(double complex);
float complex        ctanhf(float complex);
long double complex  ctanhl(long double complex);
long double complex  ctanl(long double complex);

The following sections are informative.

APPLICATION USAGE

Values are interpreted as radians, not degrees.

RATIONALE

The choice of I instead of i for the imaginary unit concedes to the widespread use of the identifier i for other purposes. The application can use a different identifier, say j, for the imaginary unit by following the inclusion of the <complex.h> header with:

#undef I
#define j _Imaginary_I

An I suffix to designate imaginary constants is not required, as multiplication by I provides a sufficiently convenient and more generally useful notation for imaginary terms. The corresponding real type for the imaginary unit is float, so that use of I for algorithmic or notational convenience will not result in widening types.

On systems with imaginary types, the application has the ability to control whether use of the macro I introduces an imaginary type, by explicitly defining I to be _Imaginary_I or _Complex_I. Disallowing imaginary types is useful for some applications intended to run on implementations without support for such types.

The macro _Imaginary_I provides a test for whether imaginary types are supported.

The cis() function (cos(x) + I*sin(x)) was considered but rejected because its implementation is easy and straightforward, even though some implementations could compute sine and cosine more efficiently in tandem.

FUTURE DIRECTIONS

The following function names and the same names suffixed with f or l are reserved for future use, and may be added to the declarations in the <complex.h> header.

cerf()
cerfc()
cexp2()

cexpm1()
clog10()
clog1p()

clog2()
clgamma()
ctgamma()

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, cabs(),
cacos(), cacosh(), carg(), casin(), casinh(),
catan(), catanh(), ccos(), ccosh(), cexp(),
cimag(), clog(), conj(), cpow(), cproj(),
creal(), csin(), csinh(), csqrt(), ctan(),
ctanh()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pwd.h(0p)

<pwd.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pwd.h - password structure

SYNOPSIS

#include <pwd.h>

DESCRIPTION

The <pwd.h> header shall provide a definition for struct passwd, which shall include at least the following members:

char    *pw_name   User's login name.
uid_t    pw_uid    Numerical user ID.
gid_t    pw_gid    Numerical group ID.
char    *pw_dir    Initial working directory.
char    *pw_shell  Program to use as shell.

The gid_t and uid_t types shall be defined as described in <sys/types.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

struct passwd *getpwnam(const char *);
struct passwd *getpwuid(uid_t);

int            getpwnam_r(const char *, struct passwd *, char *,
                   size_t, struct passwd **);
int            getpwuid_r(uid_t, struct passwd *, char *,
                   size_t, struct passwd **);

void           endpwent(void);
struct passwd *getpwent(void);
void           setpwent(void);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, endpwent(), getpwnam(), getpwuid()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_un.h(0p)

<sys/un.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/un.h - definitions for UNIX domain sockets

SYNOPSIS

#include <sys/un.h>

DESCRIPTION

The <sys/un.h> header shall define the sockaddr_un structure that includes at least the following members:

sa_family_t  sun_family  Address family.
char         sun_path[]  Socket pathname.

The sockaddr_un structure is used to store addresses for UNIX domain sockets. Values of this type shall be cast by applications to struct sockaddr for use with socket functions.

The sa_family_t type shall be defined as described in <sys/socket.h> .

The following sections are informative.

APPLICATION USAGE

The size of sun_path has intentionally been left undefined. This is because different implementations use different sizes. For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size of 104. Since most implementations originate from BSD versions, the size is typically in the range 92 to 108.

Applications should not assume a particular length for sun_path or assume that it can hold {_POSIX_PATH_MAX} characters (255).

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/socket.h> , the System Interfaces volume of IEEE Std 1003.1-2001, bind(), socket(), socketpair()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iso646.h(0p)

<iso646.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iso646.h - alternative spellings

SYNOPSIS

#include <iso646.h>

DESCRIPTION

The <iso646.h> header shall define the following eleven macros (on the left) that expand to the corresponding tokens (on the right):

and
&&
and_eq
&=
bitand
&
bitor
|
compl
~
not
!
not_eq
!=
or
||
or_eq
|=
xor
^
xor_eq
^=

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

None.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


select.h(0p)

Status: 403 Forbidden select.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/select.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


sys_wait.h(0p)

<sys/wait.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/wait.h - declarations for waiting

SYNOPSIS

#include <sys/wait.h>

DESCRIPTION

The <sys/wait.h> header shall define the following symbolic constants for use with waitpid():

WNOHANG
Do not hang if no status is available; return immediately.
WUNTRACED
Report status of stopped child process.

The <sys/wait.h> header shall define the following macros for analysis of process status values:

WEXITSTATUS
Return exit status.
WIFCONTINUED
True if child has been continued.
WIFEXITED
True if child exited normally.
WIFSIGNALED
True if child exited due to uncaught signal.
WIFSTOPPED
True if child is currently stopped.
WSTOPSIG
Return signal number that caused process to stop.
WTERMSIG
Return signal number that caused process to terminate.

The following symbolic constants shall be defined as possible values for the options argument to waitid():

WEXITED
Wait for processes that have exited.
WSTOPPED
Status is returned for any child that has stopped upon receipt of a signal.
WCONTINUED
Status is returned for any child that was stopped and has been continued.
WNOHANG
Return immediately if there are no children to wait for.
WNOWAIT
Keep the process whose status is returned in infop in a waitable state.

The type idtype_t shall be defined as an enumeration type whose possible values shall include at least the following: P_ALL P_PID P_PGID

The id_t and pid_t types shall be defined as described in <sys/types.h> .

The siginfo_t type shall be defined as described in <signal.h> .

The rusage structure shall be defined as described in <sys/resource.h> .

Inclusion of the <sys/wait.h> header may also make visible all symbols from <signal.h> and <sys/resource.h>.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

pid_t  wait(int *);

int    waitid(idtype_t, id_t, siginfo_t *, int);

pid_t  waitpid(pid_t, int *, int);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<signal.h> , <sys/resource.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, wait(), waitid()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_stat.h(0p)

<sys/stat.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/stat.h - data returned by the stat() function

SYNOPSIS

#include <sys/stat.h>

DESCRIPTION

The <sys/stat.h> header shall define the structure of the data returned by the functions fstat(), lstat(), and stat().

The stat structure shall contain at least the following members:

dev_t     st_dev     Device ID of device containing file.
ino_t     st_ino     File serial number.
mode_t    st_mode    Mode of file (see below).
nlink_t   st_nlink   Number of hard links to the file.
uid_t     st_uid     User ID of file.
gid_t     st_gid     Group ID of file.

dev_t     st_rdev    Device ID (if file is character or block special).

off_t     st_size    For regular files, the file size in bytes.
                     For symbolic links, the length in bytes of the
                     pathname contained in the symbolic link.

                     For a shared memory object, the length in bytes.

                     For a typed memory object, the length in bytes.

                     For other file types, the use of this field is
                     unspecified.
time_t    st_atime   Time of last access.
time_t    st_mtime   Time of last data modification.
time_t    st_ctime   Time of last status change.

blksize_t st_blksize A file system-specific preferred I/O block size for
                     this object. In some file system types, this may
                     vary from file to file.
blkcnt_t  st_blocks  Number of blocks allocated for this object.

The st_ino and st_dev fields taken together uniquely identify the file within the system. The blkcnt_t, blksize_t, dev_t, ino_t, mode_t, nlink_t, uid_t, gid_t, off_t, and time_t types shall be defined as described in <sys/types.h> . Times shall be given in seconds since the Epoch.

Unless otherwise specified, the structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime shall have meaningful values for all file types defined in IEEE Std 1003.1-2001.

For symbolic links, the st_mode member shall contain meaningful information, which can be used with the file type macros described below, that take a mode argument. The st_size member shall contain the length, in bytes, of the pathname contained in the symbolic link. File mode bits and the contents of the remaining members of the stat structure are unspecified. The value returned in the st_size field shall be the length of the contents of the symbolic link, and shall not count a trailing null if one is present.

The following symbolic names for the values of type mode_t shall also be defined.

File type:

S_IFMT
Type of file.
S_IFBLK
Block special.
S_IFCHR
Character special.
S_IFIFO
FIFO special.
S_IFREG
Regular.
S_IFDIR
Directory.
S_IFLNK
Symbolic link.
S_IFSOCK
Socket.

File mode bits:

S_IRWXU
Read, write, execute/search by owner.
S_IRUSR
Read permission, owner.
S_IWUSR
Write permission, owner.
S_IXUSR
Execute/search permission, owner.

S_IRWXG
Read, write, execute/search by group.
S_IRGRP
Read permission, group.
S_IWGRP
Write permission, group.
S_IXGRP
Execute/search permission, group.

S_IRWXO
Read, write, execute/search by others.
S_IROTH
Read permission, others.
S_IWOTH
Write permission, others.
S_IXOTH
Execute/search permission, others.

S_ISUID
Set-user-ID on execution.
S_ISGID
Set-group-ID on execution.
S_ISVTX
On directories, restricted deletion flag.

The bits defined by S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH, S_ISUID, S_ISGID, and S_ISVTX shall be unique.

S_IRWXU is the bitwise-inclusive OR of S_IRUSR, S_IWUSR, and S_IXUSR.

S_IRWXG is the bitwise-inclusive OR of S_IRGRP, S_IWGRP, and S_IXGRP.

S_IRWXO is the bitwise-inclusive OR of S_IROTH, S_IWOTH, and S_IXOTH.

Implementations may OR other implementation-defined bits into S_IRWXU, S_IRWXG, and S_IRWXO, but they shall not overlap any of the other bits defined in this volume of IEEE Std 1003.1-2001. The file permission bits are defined to be those corresponding to the bitwise-inclusive OR of S_IRWXU, S_IRWXG, and S_IRWXO.

The following macros shall be provided to test whether a file is of the specified type. The value m supplied to the macros is the value of st_mode from a stat structure. The macro shall evaluate to a non-zero value if the test is true; 0 if the test is false.

S_ISBLK(m)
Test for a block special file.
S_ISCHR(m)
Test for a character special file.
S_ISDIR(m)
Test for a directory.
S_ISFIFO(m)
Test for a pipe or FIFO special file.
S_ISREG(m)
Test for a regular file.
S_ISLNK(m)
Test for a symbolic link.
S_ISSOCK(m)
Test for a socket.

The implementation may implement message queues, semaphores, or shared memory objects as distinct file types. The following macros shall be provided to test whether a file is of the specified type. The value of the buf argument supplied to the macros is a pointer to a stat structure. The macro shall evaluate to a non-zero value if the specified object is implemented as a distinct file type and the specified file type is contained in the stat structure referenced by buf. Otherwise, the macro shall evaluate to zero.

S_TYPEISMQ(buf)
Test for a message queue.
S_TYPEISSEM(buf)
Test for a semaphore.
S_TYPEISSHM(buf)
Test for a shared memory object.

The implementation may implement typed memory objects as distinct file types, and the following macro shall test whether a file is of the specified type. The value of the buf argument supplied to the macros is a pointer to a stat structure. The macro shall evaluate to a non-zero value if the specified object is implemented as a distinct file type and the specified file type is contained in the stat structure referenced by buf. Otherwise, the macro shall evaluate to zero.

S_TYPEISTMO(buf)
Test macro for a typed memory object.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    chmod(const char *, mode_t);
int    fchmod(int, mode_t);
int    fstat(int, struct stat *);
int    lstat(const char *restrict, struct stat *restrict);
int    mkdir(const char *, mode_t);
int    mkfifo(const char *, mode_t);

int    mknod(const char *, mode_t, dev_t);

int    stat(const char *restrict, struct stat *restrict);
mode_t umask(mode_t);

The following sections are informative.

APPLICATION USAGE

Use of the macros is recommended for determining the type of a file.

RATIONALE

A conforming C-language application must include <sys/stat.h> for functions that have arguments or return values of type mode_t, so that symbolic values for that type can be used. An alternative would be to require that these constants are also defined by including <sys/types.h>.

The S_ISUID and S_ISGID bits may be cleared on any write, not just on open(), as some historical implementations do.

System calls that update the time entry fields in the stat structure must be documented by the implementors. POSIX-conforming systems should not update the time entry fields for functions listed in the System Interfaces volume of IEEE Std 1003.1-2001 unless the standard requires that they do, except in the case of documented extensions to the standard.

Note that st_dev must be unique within a Local Area Network (LAN) in a ``system'' made up of multiple computers' file systems connected by a LAN.

Networked implementations of a POSIX-conforming system must guarantee that all files visible within the file tree (including parts of the tree that may be remotely mounted from other machines on the network) on each individual processor are uniquely identified by the combination of the st_ino and st_dev fields.

The unit for the st_blocks member of the stat structure is not defined within IEEE Std 1003.1-2001. In some implementations it is 512 bytes. It may differ on a file system basis. There is no correlation between values of the st_blocks and st_blksize, and the f_bsize (from <sys/statvfs.h>) structure members.

Traditionally, some implementations defined the multiplier for st_blocks in <sys/param.h> as the symbol DEV_BSIZE.

FUTURE DIRECTIONS

No new S_IFMT symbolic names for the file type values of mode_t will be defined by IEEE Std 1003.1-2001; if new file types are required, they will only be testable through S_ISxx() or S_TYPEISxxx() macros instead.

SEE ALSO

<sys/statvfs.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, chmod(), fchmod(), fstat(), lstat(), mkdir(), mkfifo(), mknod(), stat(), umask()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setjmp.h(0p)

<setjmp.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setjmp.h - stack environment declarations

SYNOPSIS

#include <setjmp.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <setjmp.h> header shall define the array types jmp_buf and sigjmp_buf.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void   longjmp(jmp_buf, int);

void   siglongjmp(sigjmp_buf, int);

void  _longjmp(jmp_buf, int);

The following may be declared as a function, or defined as a macro, or both. Function prototypes shall be provided.

int    setjmp(jmp_buf);

int    sigsetjmp(sigjmp_buf, int);

int   _setjmp(jmp_buf);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, longjmp(), _longjmp(), setjmp(), siglongjmp(), sigsetjmp()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


aio.h(0p)

<aio.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio.h - asynchronous input and output (REALTIME)

SYNOPSIS

#include <aio.h>

DESCRIPTION

The <aio.h> header shall define the aiocb structure which shall include at least the following members:

int             aio_fildes     File descriptor.
off_t           aio_offset     File offset.
volatile void  *aio_buf        Location of buffer.
size_t          aio_nbytes     Length of transfer.
int             aio_reqprio    Request priority offset.
struct sigevent aio_sigevent   Signal number and value.
int             aio_lio_opcode Operation to be performed.

This header shall also include the following constants:

AIO_ALLDONE
A return value indicating that none of the requested operations could be canceled since they are already complete.
AIO_CANCELED
A return value indicating that all requested operations have been canceled.
AIO_NOTCANCELED

A return value indicating that some of the requested operations could not be canceled since they are in progress.

LIO_NOP
A lio_listio() element operation option indicating that no transfer is requested.
LIO_NOWAIT
A lio_listio() synchronization operation indicating that the calling thread is to continue execution while the lio_listio() operation is being performed, and no notification is given when the operation is complete.
LIO_READ
A lio_listio() element operation option requesting a read.
LIO_WAIT
A lio_listio() synchronization operation indicating that the calling thread is to suspend until the lio_listio() operation is complete.
LIO_WRITE
A lio_listio() element operation option requesting a write.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int      aio_cancel(int, struct aiocb *);
int      aio_error(const struct aiocb *);
int      aio_fsync(int, struct aiocb *);
int      aio_read(struct aiocb *);
ssize_t  aio_return(struct aiocb *);
int      aio_suspend(const struct aiocb *const[], int,
             const struct timespec *);
int      aio_write(struct aiocb *);
int      lio_listio(int, struct aiocb *restrict const[restrict], int,
             struct sigevent *restrict);

Inclusion of the <aio.h> header may make visible symbols defined in the headers <fcntl.h>, <signal.h>, <sys/types.h>, and <time.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<fcntl.h> , <signal.h> , <sys/types.h> , <time.h> , the System Interfaces volume of IEEE Std 1003.1-2001, fsync(), lseek(), read(), write()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


regex.h(0p)

<regex.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

regex.h - regular expression matching types

SYNOPSIS

#include <regex.h>

DESCRIPTION

The <regex.h> header shall define the structures and symbolic constants used by the regcomp(), regexec(), regerror(), and regfree() functions.

The structure type regex_t shall contain at least the following member:

size_t    re_nsub    Number of parenthesized subexpressions.

The type size_t shall be defined as described in <sys/types.h> .

The type regoff_t shall be defined as a signed integer type that can hold the largest value that can be stored in either a type off_t or type ssize_t. The structure type regmatch_t shall contain at least the following members:

regoff_t    rm_so    Byte offset from start of string
                     to start of substring.
regoff_t    rm_eo    Byte offset from start of string of the
                     first character after the end of substring.

Values for the cflags parameter to the regcomp() function are as follows:

REG_EXTENDED
Use Extended Regular Expressions.
REG_ICASE
Ignore case in match.
REG_NOSUB
Report only success or fail in regexec().
REG_NEWLINE
Change the handling of <newline>.

Values for the eflags parameter to the regexec() function are as follows:

REG_NOTBOL
The circumflex character ( '^' ), when taken as a special character, does not match the beginning of string.
REG_NOTEOL
The dollar sign ( '$' ), when taken as a special character, does not match the end of string.

The following constants shall be defined as error return values:

REG_NOMATCH
regexec() failed to match.
REG_BADPAT
Invalid regular expression.
REG_ECOLLATE
Invalid collating element referenced.
REG_ECTYPE
Invalid character class type referenced.
REG_EESCAPE
Trailing '\' in pattern.
REG_ESUBREG
Number in \digit invalid or in error.
REG_EBRACK
"[]" imbalance.
REG_EPAREN
"\(\)" or "()" imbalance.
REG_EBRACE
"\{\}" imbalance.
REG_BADBR
Content of "\{\}" invalid: not a number, number too large, more than two numbers, first larger than second.
REG_ERANGE
Invalid endpoint in range expression.
REG_ESPACE
Out of memory.
REG_BADRPT
'?' , '*' , or '+' not preceded by valid regular expression.
REG_ENOSYS
Reserved.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    regcomp(regex_t *restrict, const char *restrict, int);
size_t regerror(int, const regex_t *restrict, char *restrict, size_t);
int    regexec(const regex_t *restrict, const char *restrict, size_t,
           regmatch_t[restrict], int);
void   regfree(regex_t *);

The implementation may define additional macros or constants using names beginning with REG_.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, regcomp(), the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fcntl.h(0p)

<fcntl.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fcntl.h - file control options

SYNOPSIS

#include <fcntl.h>

DESCRIPTION

The <fcntl.h> header shall define the following requests and arguments for use by the functions fcntl() and open().

Values for cmd used by fcntl() (the following values are unique) are as follows:

F_DUPFD
Duplicate file descriptor.
F_GETFD
Get file descriptor flags.
F_SETFD
Set file descriptor flags.
F_GETFL
Get file status flags and file access modes.
F_SETFL
Set file status flags.
F_GETLK
Get record locking information.
F_SETLK
Set record locking information.
F_SETLKW
Set record locking information; wait if blocked.
F_GETOWN
Get process or process group ID to receive SIGURG signals.
F_SETOWN
Set process or process group ID to receive SIGURG signals.

File descriptor flags used for fcntl() are as follows:

FD_CLOEXEC
Close the file descriptor upon execution of an exec family function.

Values for l_type used for record locking with fcntl() (the following values are unique) are as follows:

F_RDLCK
Shared or read lock.
F_UNLCK
Unlock.
F_WRLCK
Exclusive or write lock.

The values used for l_whence, SEEK_SET, SEEK_CUR, and SEEK_END shall be defined as described in <unistd.h> .

The following values are file creation flags and are used in the oflag value to open(). They shall be bitwise-distinct.

O_CREAT
Create file if it does not exist.
O_EXCL
Exclusive use flag.
O_NOCTTY
Do not assign controlling terminal.
O_TRUNC
Truncate flag.

File status flags used for open() and fcntl() are as follows:

O_APPEND
Set append mode.
O_DSYNC
Write according to synchronized I/O data integrity completion.
O_NONBLOCK
Non-blocking mode.
O_RSYNC
Synchronized read I/O operations.
O_SYNC
Write according to synchronized I/O file integrity completion.

Mask for use with file access modes is as follows:

O_ACCMODE
Mask for file access modes.

File access modes used for open() and fcntl() are as follows:

O_RDONLY
Open for reading only.
O_RDWR
Open for reading and writing.
O_WRONLY
Open for writing only.

The symbolic names for file modes for use as values of mode_t shall be defined as described in <sys/stat.h> .

Values for advice used by posix_fadvise() are as follows:

POSIX_FADV_NORMAL

The application has no advice to give on its behavior with respect to the specified data. It is the default characteristic if no advice is given for an open file.

POSIX_FADV_SEQUENTIAL

The application expects to access the specified data sequentially from lower offsets to higher offsets.

POSIX_FADV_RANDOM

The application expects to access the specified data in a random order.

POSIX_FADV_WILLNEED

The application expects to access the specified data in the near future.

POSIX_FADV_DONTNEED

The application expects that it will not access the specified data in the near future.

POSIX_FADV_NOREUSE

The application expects to access the specified data once and then not reuse it thereafter.

The structure flock describes a file lock. It shall include the following members:

short  l_type   Type of lock; F_RDLCK, F_WRLCK, F_UNLCK.
short  l_whence Flag for starting offset.
off_t  l_start  Relative offset in bytes.
off_t  l_len    Size; if 0 then until EOF.
pid_t  l_pid    Process ID of the process holding the lock; returned with F_GETLK.

The mode_t, off_t, and pid_t types shall be defined as described in <sys/types.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int  creat(const char *, mode_t);
int  fcntl(int, int, ...);
int  open(const char *, int, ...);

int  posix_fadvise(int, off_t, size_t, int);
int  posix_fallocate(int, off_t, size_t);

Inclusion of the <fcntl.h> header may also make visible all symbols from <sys/stat.h> and <unistd.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/stat.h> , <sys/types.h> , <unistd.h> , the System Interfaces volume of IEEE Std 1003.1-2001, creat(), exec, fcntl(), open(), posix_fadvise(), posix_fallocate(), posix_madvise()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctype.h(0p)

<ctype.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ctype.h - character types

SYNOPSIS

#include <ctype.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int   isalnum(int);
int   isalpha(int);

int   isascii(int);

int   isblank(int);
int   iscntrl(int);
int   isdigit(int);
int   isgraph(int);
int   islower(int);
int   isprint(int);
int   ispunct(int);
int   isspace(int);
int   isupper(int);
int   isxdigit(int);

int   toascii(int);

int   tolower(int);
int   toupper(int);

The following are defined as macros:

int   _toupper(int);
int   _tolower(int);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<locale.h> , the System Interfaces volume of IEEE Std 1003.1-2001,
isalnum(), isalpha(), isascii(), iscntrl(),
isdigit(), isgraph(), islower(), isprint(),
ispunct(), isspace(), isupper(), isxdigit(),
mblen(), mbstowcs(), mbtowc(), setlocale(),
toascii(), tolower(), _tolower(), toupper(),
_toupper(), wcstombs(), wctomb()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


math.h(0p)

<math.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

math.h - mathematical declarations

SYNOPSIS

#include <math.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <math.h> header shall include definitions for at least the following types:

float_t
A real-floating type at least as wide as float.
double_t
A real-floating type at least as wide as double, and at least as wide as float_t.

If FLT_EVAL_METHOD equals 0, float_t and double_t shall be float and double, respectively; if FLT_EVAL_METHOD equals 1, they shall both be double; if FLT_EVAL_METHOD equals 2, they shall both be long double; for other values of FLT_EVAL_METHOD, they are otherwise implementation-defined.

The <math.h> header shall define the following macros, where real-floating indicates that the argument shall be an expression of real-floating type:

int fpclassify(real-floating x);
int isfinite(real-floating x);
int isinf(real-floating x);
int isnan(real-floating x);
int isnormal(real-floating x);
int signbit(real-floating x);
int isgreater(real-floating x, real-floating y);
int isgreaterequal(real-floating x, real-floating y);
int isless(real-floating x, real-floating y);
int islessequal(real-floating x, real-floating y);
int islessgreater(real-floating x, real-floating y);
int isunordered(real-floating x, real-floating y);

The <math.h> header shall provide for the following constants. The values are of type double and are accurate within the precision of the double type.

M_E
Value of e
M_LOG2E
Value of log_2e
M_LOG10E
Value of log_10e
M_LN2
Value of log_e2
M_LN10
Value of log_e10
M_PI
Value of pi
M_PI_2
Value of pi/2
M_PI_4
Value of pi/4
M_1_PI
Value of 1/pi
M_2_PI
Value of 2/pi
M_2_SQRTPI
Value of 2/ sqrt pi
M_SQRT2
Value of sqrt 2
M_SQRT1_2
Value of 1/sqrt 2

The header shall define the following symbolic constants:

MAXFLOAT
Value of maximum non-infinite single-precision floating-point number.
HUGE_VAL
A positive double expression, not necessarily representable as a float. Used as an error value returned by the mathematics library. HUGE_VAL evaluates to +infinity on systems supporting IEEE Std 754-1985.
HUGE_VALF
A positive float constant expression. Used as an error value returned by the mathematics library. HUGE_VALF evaluates to +infinity on systems supporting IEEE Std 754-1985.
HUGE_VALL
A positive long double constant expression. Used as an error value returned by the mathematics library. HUGE_VALL evaluates to +infinity on systems supporting IEEE Std 754-1985.
INFINITY
A constant expression of type float representing positive or unsigned infinity, if available; else a positive constant of type float that overflows at translation time.
NAN
A constant expression of type float representing a quiet NaN. This symbolic constant is only defined if the implementation supports quiet NaNs for the float type.

The following macros shall be defined for number classification. They represent the mutually-exclusive kinds of floating-point values. They expand to integer constant expressions with distinct values. Additional implementation-defined floating-point classifications, with macro definitions beginning with FP_ and an uppercase letter, may also be specified by the implementation.

FP_INFINITE
FP_NAN
FP_NORMAL
FP_SUBNORMAL
FP_ZERO

The following optional macros indicate whether the fma() family of functions are fast compared with direct code:

FP_FAST_FMA
FP_FAST_FMAF
FP_FAST_FMAL

The FP_FAST_FMA macro shall be defined to indicate that the fma() function generally executes about as fast as, or faster than, a multiply and an add of double operands. The other macros have the equivalent meaning for the float and long double versions.

The following macros shall expand to integer constant expressions whose values are returned by ilogb( x) if x is zero or NaN, respectively. The value of FP_ILOGB0 shall be either {INT_MIN} or - {INT_MAX}. The value of FP_ILOGBNAN shall be either {INT_MAX} or {INT_MIN}.

FP_ILOGB0
FP_ILOGBNAN

The following macros shall expand to the integer constants 1 and 2, respectively;

MATH_ERRNO
MATH_ERREXCEPT

The following macro shall expand to an expression that has type int and the value MATH_ERRNO, MATH_ERREXCEPT, or the bitwise-inclusive OR of both:

math_errhandling

The value of math_errhandling is constant for the duration of the program. It is unspecified whether math_errhandling is a macro or an identifier with external linkage. If a macro definition is suppressed or a program defines an identifier with the name math_errhandling , the behavior is undefined. If the expression (math_errhandling & MATH_ERREXCEPT) can be non-zero, the implementation shall define the macros FE_DIVBYZERO, FE_INVALID, and FE_OVERFLOW in <fenv.h>.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

double      acos(double);
float       acosf(float);
double      acosh(double);
float       acoshf(float);
long double acoshl(long double);
long double acosl(long double);
double      asin(double);
float       asinf(float);
double      asinh(double);
float       asinhf(float);
long double asinhl(long double);
long double asinl(long double);
double      atan(double);
double      atan2(double, double);
float       atan2f(float, float);
long double atan2l(long double, long double);
float       atanf(float);
double      atanh(double);
float       atanhf(float);
long double atanhl(long double);
long double atanl(long double);
double      cbrt(double);
float       cbrtf(float);
long double cbrtl(long double);
double      ceil(double);
float       ceilf(float);
long double ceill(long double);
double      copysign(double, double);
float       copysignf(float, float);
long double copysignl(long double, long double);
double      cos(double);
float       cosf(float);
double      cosh(double);
float       coshf(float);
long double coshl(long double);
long double cosl(long double);
double      erf(double);
double      erfc(double);
float       erfcf(float);
long double erfcl(long double);
float       erff(float);
long double erfl(long double);
double      exp(double);
double      exp2(double);
float       exp2f(float);
long double exp2l(long double);
float       expf(float);
long double expl(long double);
double      expm1(double);
float       expm1f(float);
long double expm1l(long double);
double      fabs(double);
float       fabsf(float);
long double fabsl(long double);
double      fdim(double, double);
float       fdimf(float, float);
long double fdiml(long double, long double);
double      floor(double);
float       floorf(float);
long double floorl(long double);
double      fma(double, double, double);
float       fmaf(float, float, float);
long double fmal(long double, long double, long double);
double      fmax(double, double);
float       fmaxf(float, float);
long double fmaxl(long double, long double);
double      fmin(double, double);
float       fminf(float, float);
long double fminl(long double, long double);
double      fmod(double, double);
float       fmodf(float, float);
long double fmodl(long double, long double);
double      frexp(double, int *);
float       frexpf(float value, int *);
long double frexpl(long double value, int *);
double      hypot(double, double);
float       hypotf(float, float);
long double hypotl(long double, long double);
int         ilogb(double);
int         ilogbf(float);
int         ilogbl(long double);

double      j0(double);
double      j1(double);
double      jn(int, double);

double      ldexp(double, int);
float       ldexpf(float, int);
long double ldexpl(long double, int);
double      lgamma(double);
float       lgammaf(float);
long double lgammal(long double);
long long   llrint(double);
long long   llrintf(float);
long long   llrintl(long double);
long long   llround(double);
long long   llroundf(float);
long long   llroundl(long double);
double      log(double);
double      log10(double);
float       log10f(float);
long double log10l(long double);
double      log1p(double);
float       log1pf(float);
long double log1pl(long double);
double      log2(double);
float       log2f(float);
long double log2l(long double);
double      logb(double);
float       logbf(float);
long double logbl(long double);
float       logf(float);
long double logl(long double);
long        lrint(double);
long        lrintf(float);
long        lrintl(long double);
long        lround(double);
long        lroundf(float);
long        lroundl(long double);
double      modf(double, double *);
float       modff(float, float *);
long double modfl(long double, long double *);
double      nan(const char *);
float       nanf(const char *);
long double nanl(const char *);
double      nearbyint(double);
float       nearbyintf(float);
long double nearbyintl(long double);
double      nextafter(double, double);
float       nextafterf(float, float);
long double nextafterl(long double, long double);
double      nexttoward(double, long double);
float       nexttowardf(float, long double);
long double nexttowardl(long double, long double);
double      pow(double, double);
float       powf(float, float);
long double powl(long double, long double);
double      remainder(double, double);
float       remainderf(float, float);
long double remainderl(long double, long double);
double      remquo(double, double, int *);
float       remquof(float, float, int *);
long double remquol(long double, long double, int *);
double      rint(double);
float       rintf(float);
long double rintl(long double);
double      round(double);
float       roundf(float);
long double roundl(long double);

double      scalb(double, double);

double      scalbln(double, long);
float       scalblnf(float, long);
long double scalblnl(long double, long);
double      scalbn(double, int);
float       scalbnf(float, int);
long double scalbnl(long double, int);
double      sin(double);
float       sinf(float);
double      sinh(double);
float       sinhf(float);
long double sinhl(long double);
long double sinl(long double);
double      sqrt(double);
float       sqrtf(float);
long double sqrtl(long double);
double      tan(double);
float       tanf(float);
double      tanh(double);
float       tanhf(float);
long double tanhl(long double);
long double tanl(long double);
double      tgamma(double);
float       tgammaf(float);
long double tgammal(long double);
double      trunc(double);
float       truncf(float);
long double truncl(long double);

double      y0(double);
double      y1(double);
double      yn(int, double);

The following external variable shall be defined:

extern int signgam;

The behavior of each of the functions defined in <math.h> is specified in the System Interfaces volume of IEEE Std 1003.1-2001 for all representable values of its input arguments, except where stated otherwise. Each function shall execute as if it were a single operation without generating any externally visible exceptional conditions.

The following sections are informative.

APPLICATION USAGE

The FP_CONTRACT pragma can be used to allow (if the state is on) or disallow (if the state is off) the implementation to contract expressions. Each pragma can occur either outside external declarations or preceding all explicit declarations and statements inside a compound statement. When outside external declarations, the pragma takes effect from its occurrence until another FP_CONTRACT pragma is encountered, or until the end of the translation unit. When inside a compound statement, the pragma takes effect from its occurrence until another FP_CONTRACT pragma is encountered (including within a nested compound statement), or until the end of the compound statement; at the end of a compound statement the state for the pragma is restored to its condition just before the compound statement. If this pragma is used in any other context, the behavior is undefined. The default state (on or off) for the pragma is implementation-defined.

RATIONALE

Before the ISO/IEC 9899:1999 standard, the math library was defined only for the floating type double. All the names formed by appending 'f' or 'l' to a name in <math.h> were reserved to allow for the definition of float and long double libraries; and the ISO/IEC 9899:1999 standard provides for all three versions of math functions.

The functions ecvt(), fcvt(), and gcvt() have been dropped from the ISO C standard since their capability is available through sprintf(). These are provided on XSI-conformant systems supporting the Legacy Option Group.

FUTURE DIRECTIONS

None.

SEE ALSO

<stddef.h> , <sys/types.h> , the System
Interfaces volume of IEEE Std 1003.1-2001, acos(), acosh(),
asin(), atan(), atan2(), cbrt(), ceil(),
cos(), cosh(), erf(), exp(), expm1(),
fabs(), floor(), fmod(), frexp(), hypot(),
ilogb(), isnan(), j0(), ldexp(), lgamma(),
log(), log10(), log1p(), logb(), modf(),
nextafter(), pow(), remainder(), rint(), scalb(),
sin(), sinh(), sqrt(), tan(), tanh(),
y0()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stropts.h(0p)

<stropts.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stropts.h - STREAMS interface (STREAMS)

SYNOPSIS

#include <stropts.h>

DESCRIPTION

The <stropts.h> header shall define the bandinfo structure that includes at least the following members:

unsigned char  bi_pri   Priority band.
int            bi_flag  Flushing type.

The <stropts.h> header shall define the strpeek structure that includes at least the following members:

struct strbuf  ctlbuf   The control portion of the message.
struct strbuf  databuf  The data portion of the message.
t_uscalar_t    flags    RS_HIPRI or 0.

The <stropts.h> header shall define the strbuf structure that includes at least the following members:

int    maxlen  Maximum buffer length.
int    len     Length of data.
char  *buf     Pointer to buffer.

The <stropts.h> header shall define the strfdinsert structure that includes at least the following members:

struct strbuf  ctlbuf   The control portion of the message.
struct strbuf  databuf  The data portion of the message.
t_uscalar_t    flags    RS_HIPRI or 0.
int            fildes   File descriptor of the other STREAM.
int            offset   Relative location of the stored value.

The <stropts.h> header shall define the strioctl structure that includes at least the following members:

int    ic_cmd     ioctl() command.
int    ic_timout  Timeout for response.
int    ic_len     Length of data.
char  *ic_dp      Pointer to buffer.

The <stropts.h> header shall define the strrecvfd structure that includes at least the following members:

int    fda  Received file descriptor.
uid_t  uid  UID of sender.
gid_t  gid  GID of sender.

The uid_t and gid_t types shall be defined through typedef as described in <sys/types.h> .

The <stropts.h> header shall define the t_scalar_t and t_uscalar_t types, respectively, as signed and unsigned opaque types of equal length of at least 32 bits.

The <stropts.h> header shall define the str_list structure that includes at least the following members:

int                sl_nmods    Number of STREAMS module names.
struct str_mlist  *sl_modlist  STREAMS module names.

The <stropts.h> header shall define the str_mlist structure that includes at least the following member:

char  l_name[FMNAMESZ+1]  A STREAMS module name.

At least the following macros shall be defined for use as the request argument to ioctl():

I_PUSH
Push a STREAMS module.
I_POP
Pop a STREAMS module.
I_LOOK
Get the top module name.
I_FLUSH
Flush a STREAM.
I_FLUSHBAND
Flush one band of a STREAM.
I_SETSIG
Ask for notification signals.
I_GETSIG
Retrieve current notification signals.
I_FIND
Look for a STREAMS module.
I_PEEK
Peek at the top message on a STREAM.
I_SRDOPT
Set the read mode.
I_GRDOPT
Get the read mode.
I_NREAD
Size the top message.
I_FDINSERT
Send implementation-defined information about another STREAM.
I_STR
Send a STREAMS ioctl().
I_SWROPT
Set the write mode.
I_GWROPT
Get the write mode.
I_SENDFD
Pass a file descriptor through a STREAMS pipe.
I_RECVFD
Get a file descriptor sent via I_SENDFD.
I_LIST
Get all the module names on a STREAM.
I_ATMARK
Is the top message "marked''?
I_CKBAND
See if any messages exist in a band.
I_GETBAND
Get the band of the top message on a STREAM.
I_CANPUT
Is a band writable?
I_SETCLTIME
Set close time delay.
I_GETCLTIME
Get close time delay.
I_LINK
Connect two STREAMs.
I_UNLINK
Disconnect two STREAMs.
I_PLINK
Persistently connect two STREAMs.
I_PUNLINK
Dismantle a persistent STREAMS link.

At least the following macros shall be defined for use with I_LOOK:

FMNAMESZ
The minimum size in bytes of the buffer referred to by the arg argument.

At least the following macros shall be defined for use with I_FLUSH:

FLUSHR
Flush read queues.
FLUSHW
Flush write queues.
FLUSHRW
Flush read and write queues.

At least the following macros shall be defined for use with I_SETSIG:

S_RDNORM
A normal (priority band set to 0) message has arrived at the head of a STREAM head read queue.
S_RDBAND
A message with a non-zero priority band has arrived at the head of a STREAM head read queue.
S_INPUT
A message, other than a high-priority message, has arrived at the head of a STREAM head read queue.
S_HIPRI
A high-priority message is present on a STREAM head read queue.
S_OUTPUT
The write queue for normal data (priority band 0) just below the STREAM head is no longer full. This notifies the process that there is room on the queue for sending (or writing) normal data downstream.
S_WRNORM
Equivalent to S_OUTPUT.
S_WRBAND
The write queue for a non-zero priority band just below the STREAM head is no longer full.
S_MSG
A STREAMS signal message that contains the SIGPOLL signal reaches the front of the STREAM head read queue.
S_ERROR
Notification of an error condition reaches the STREAM head.
S_HANGUP
Notification of a hangup reaches the STREAM head.
S_BANDURG
When used in conjunction with S_RDBAND, SIGURG is generated instead of SIGPOLL when a priority message reaches the front of the STREAM head read queue.

At least the following macros shall be defined for use with I_PEEK:

RS_HIPRI
Only look for high-priority messages.

At least the following macros shall be defined for use with I_SRDOPT:

RNORM
Byte-STREAM mode, the default.
RMSGD
Message-discard mode.
RMSGN
Message-non-discard mode.
RPROTNORM
Fail read() with [EBADMSG] if a message containing a control part is at the front of the STREAM head read queue.
RPROTDAT
Deliver the control part of a message as data when a process issues a read().
RPROTDIS
Discard the control part of a message, delivering any data part, when a process issues a read().

At least the following macros shall be defined for use with I_SWOPT:

SNDZERO
Send a zero-length message downstream when a write() of 0 bytes occurs.

At least the following macros shall be defined for use with I_ATMARK:

ANYMARK
Check if the message is marked.
LASTMARK
Check if the message is the last one marked on the queue.

At least the following macros shall be defined for use with I_UNLINK:

MUXID_ALL
Unlink all STREAMs linked to the STREAM associated with fildes.

The following macros shall be defined for getmsg(), getpmsg(), putmsg(), and putpmsg():

MSG_ANY
Receive any message.
MSG_BAND
Receive message from specified band.
MSG_HIPRI
Send/receive high-priority message.
MORECTL
More control information is left in message.
MOREDATA
More data is left in message.

The <stropts.h> header may make visible all of the symbols from <unistd.h>.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    isastream(int);
int    getmsg(int, struct strbuf *restrict, struct strbuf *restrict,
           int *restrict);
int    getpmsg(int, struct strbuf *restrict, struct strbuf *restrict,
           int *restrict, int *restrict);
int    ioctl(int, int, ... );
int    putmsg(int, const struct strbuf *, const struct strbuf *, int);
int    putpmsg(int, const struct strbuf *, const struct strbuf *, int,
           int);
int    fattach(int, const char *);
int    fdetach(const char *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , <unistd.h> , the System Interfaces volume of IEEE Std 1003.1-2001, close(), fcntl(), getmsg(), ioctl(), open(), pipe(), read(), poll(), putmsg(), signal(), write()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


errno.h(0p)

<errno.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

errno.h - system error numbers

SYNOPSIS

#include <errno.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The ISO C standard only requires the symbols [EDOM], [EILSEQ], and [ERANGE] to be defined.

The <errno.h> header shall provide a declaration for errno and give positive values for the following symbolic constants. Their values shall be unique except as noted below.

E2BIG
Argument list too long.
EACCES
Permission denied.
EADDRINUSE
Address in use.
EADDRNOTAVAIL
Address not available.
EAFNOSUPPORT
Address family not supported.
EAGAIN
Resource unavailable, try again (may be the same value as [EWOULDBLOCK]).
EALREADY
Connection already in progress.
EBADF
Bad file descriptor.
EBADMSG
Bad message.
EBUSY
Device or resource busy.
ECANCELED
Operation canceled.
ECHILD
No child processes.
ECONNABORTED
Connection aborted.
ECONNREFUSED
Connection refused.
ECONNRESET
Connection reset.
EDEADLK
Resource deadlock would occur.
EDESTADDRREQ
Destination address required.
EDOM
Mathematics argument out of domain of function.
EDQUOT
Reserved.
EEXIST
File exists.
EFAULT
Bad address.
EFBIG
File too large.
EHOSTUNREACH
Host is unreachable.
EIDRM
Identifier removed.
EILSEQ
Illegal byte sequence.
EINPROGRESS
Operation in progress.
EINTR
Interrupted function.
EINVAL
Invalid argument.
EIO
I/O error.
EISCONN
Socket is connected.
EISDIR
Is a directory.
ELOOP
Too many levels of symbolic links.
EMFILE
Too many open files.
EMLINK
Too many links.
EMSGSIZE
Message too large.
EMULTIHOP
Reserved.
ENAMETOOLONG
Filename too long.
ENETDOWN
Network is down.
ENETRESET
Connection aborted by network.
ENETUNREACH
Network unreachable.
ENFILE
Too many files open in system.
ENOBUFS
No buffer space available.
ENODATA
No message is available on the STREAM head read queue.
ENODEV
No such device.
ENOENT
No such file or directory.
ENOEXEC
Executable file format error.
ENOLCK
No locks available.
ENOLINK
Reserved.
ENOMEM
Not enough space.
ENOMSG
No message of the desired type.
ENOPROTOOPT
Protocol not available.
ENOSPC
No space left on device.
ENOSR
No STREAM resources.
ENOSTR
Not a STREAM.
ENOSYS
Function not supported.
ENOTCONN
The socket is not connected.
ENOTDIR
Not a directory.
ENOTEMPTY
Directory not empty.
ENOTSOCK
Not a socket.
ENOTSUP
Not supported.
ENOTTY
Inappropriate I/O control operation.
ENXIO
No such device or address.
EOPNOTSUPP
Operation not supported on socket.
EOVERFLOW
Value too large to be stored in data type.
EPERM
Operation not permitted.
EPIPE
Broken pipe.
EPROTO
Protocol error.
EPROTONOSUPPORT

Protocol not supported.

EPROTOTYPE
Protocol wrong type for socket.
ERANGE
Result too large.
EROFS
Read-only file system.
ESPIPE
Invalid seek.
ESRCH
No such process.
ESTALE
Reserved.
ETIME
Stream ioctl() timeout.
ETIMEDOUT
Connection timed out.
ETXTBSY
Text file busy.
EWOULDBLOCK
Operation would block (may be the same value as [EAGAIN]).
EXDEV
Cross-device link.

The following sections are informative.

APPLICATION USAGE

Additional error numbers may be defined on conforming systems; see the System Interfaces volume of IEEE Std 1003.1-2001.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, Section 2.3, Error Numbers

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


locale.h(0p)

<locale.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

locale.h - category macros

SYNOPSIS

#include <locale.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The <locale.h> header shall provide a definition for lconv structure, which shall include at least the following members. (See the definitions of LC_MONETARY in LC_MONETARY and LC_NUMERIC .)

char    *currency_symbol
char    *decimal_point
char     frac_digits
char    *grouping
char    *int_curr_symbol
char     int_frac_digits
char     int_n_cs_precedes
char     int_n_sep_by_space
char     int_n_sign_posn
char     int_p_cs_precedes
char     int_p_sep_by_space
char     int_p_sign_posn
char    *mon_decimal_point
char    *mon_grouping
char    *mon_thousands_sep
char    *negative_sign
char     n_cs_precedes
char     n_sep_by_space
char     n_sign_posn
char    *positive_sign
char     p_cs_precedes
char     p_sep_by_space
char     p_sign_posn
char    *thousands_sep

The <locale.h> header shall define NULL (as defined in <stddef.h> ) and at least the following as macros:

LC_ALL
LC_COLLATE
LC_CTYPE

LC_MESSAGES

LC_MONETARY
LC_NUMERIC
LC_TIME

which shall expand to distinct integer constant expressions, for use as the first argument to the setlocale() function.

Additional macro definitions, beginning with the characters LC_ and an uppercase letter, may also be given here.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

struct  lconv *localeconv (void);
char   *setlocale(int, const char *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, localeconv(), setlocale(), Environment Variables

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uio.h(0p)

Status: 403 Forbidden uio.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/uio.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


stdlib.h(0p)

<stdlib.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stdlib.h - standard library definitions

SYNOPSIS

#include <stdlib.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <stdlib.h> header shall define the following macros:

EXIT_FAILURE
Unsuccessful termination for exit(); evaluates to a non-zero value.
EXIT_SUCCESS
Successful termination for exit(); evaluates to 0.
NULL
Null pointer.
{RAND_MAX}
Maximum value returned by rand(); at least 32767.
{MB_CUR_MAX}
Integer expression whose value is the maximum number of bytes in a character specified by the current locale.

The following data types shall be defined through typedef:

div_t
Structure type returned by the div() function.
ldiv_t
Structure type returned by the ldiv() function.
lldiv_t
Structure type returned by the lldiv() function.
size_t
As described in <stddef.h> .
wchar_t
As described in <stddef.h> .

In addition, the following symbolic names and macros shall be defined as in <sys/wait.h> , for use in decoding the return value from system():

WNOHANG
WUNTRACED
WEXITSTATUS
WIFEXITED
WIFSIGNALED
WIFSTOPPED
WSTOPSIG
WTERMSIG

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void          _Exit(int);

long          a64l(const char *);

void          abort(void);
int           abs(int);
int           atexit(void (*)(void));
double        atof(const char *);
int           atoi(const char *);
long          atol(const char *);
long long     atoll(const char *);
void         *bsearch(const void *, const void *, size_t, size_t,
                  int (*)(const void *, const void *));
void         *calloc(size_t, size_t);
div_t         div(int, int);

double        drand48(void);
char         *ecvt(double, int, int *restrict, int *restrict); (LEGACY )
double        erand48(unsigned short[3]);

void          exit(int);

char         *fcvt(double, int, int *restrict, int *restrict); (LEGACY )

void          free(void *);

char         *gcvt(double, int, char *); (LEGACY )

char         *getenv(const char *);

int           getsubopt(char **, char *const *, char **);
int           grantpt(int);
char         *initstate(unsigned, char *, size_t);
long          jrand48(unsigned short[3]);
char         *l64a(long);

long          labs(long);

void          lcong48(unsigned short[7]);

ldiv_t        ldiv(long, long);
long long     llabs(long long);
lldiv_t       lldiv(long long, long long);

long          lrand48(void);

void         *malloc(size_t);
int           mblen(const char *, size_t);
size_t        mbstowcs(wchar_t *restrict, const char *restrict, size_t);
int           mbtowc(wchar_t *restrict, const char *restrict, size_t);

char         *mktemp(char *); (LEGACY )
int           mkstemp(char *);
long          mrand48(void);
long          nrand48(unsigned short[3]);

int           posix_memalign(void **, size_t, size_t);

int           posix_openpt(int);
char         *ptsname(int);
int           putenv(char *);

void          qsort(void *, size_t, size_t, int (*)(const void *,
                  const void *));
int           rand(void);

int           rand_r(unsigned *);

long          random(void);

void         *realloc(void *, size_t);

char         *realpath(const char *restrict, char *restrict);
unsigned short seed48(unsigned short[3]);

int           setenv(const char *, const char *, int);

void          setkey(const char *);
char         *setstate(const char *);

void          srand(unsigned);

void          srand48(long);
void          srandom(unsigned);

double        strtod(const char *restrict, char **restrict);
float         strtof(const char *restrict, char **restrict);
long          strtol(const char *restrict, char **restrict, int);
long double   strtold(const char *restrict, char **restrict);
long long     strtoll(const char *restrict, char **restrict, int);
unsigned long strtoul(const char *restrict, char **restrict, int);
unsigned long long
              strtoull(const char *restrict, char **restrict, int);
int           system(const char *);

int           unlockpt(int);

int           unsetenv(const char *);

size_t        wcstombs(char *restrict, const wchar_t *restrict, size_t);
int           wctomb(char *, wchar_t);

Inclusion of the <stdlib.h> header may also make visible all symbols from <stddef.h>, <limits.h>, <math.h>, and <sys/wait.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<limits.h> , <math.h> , <stddef.h> , <sys/types.h>
, <sys/wait.h> , the System Interfaces volume of IEEE Std 1003.1-2001,
_Exit(), a64l(), abort(), abs(), atexit(),
atof(), atoi(), atol(), atoll(), bsearch(),
calloc(), div(), drand48(), erand48(), exit(),
free(), getenv(), getsubopt(), grantpt(),
initstate(), jrand48(), l64a(), labs(), lcong48(),
ldiv(), llabs(), lldiv(), lrand48(), malloc(),
mblen(), mbstowcs(), mbtowc(), mkstemp(),
mrand48(), nrand48(), posix_memalign(), ptsname(),
putenv(), qsort(), rand(), realloc(), realpath(),
setstate(), srand(), srand48(), srandom(),
strtod(), strtof(), strtol(), strtold(), strtoll(),
strtoul(), strtoull(), unlockpt(), wcstombs(),
wctomb()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wchar.h(0p)

<wchar.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wchar.h - wide-character handling

SYNOPSIS

#include <wchar.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <wchar.h> header shall define the following types:

wchar_t
As described in <stddef.h> .
wint_t
An integer type capable of storing any valid value of wchar_t or WEOF.
wctype_t
A scalar type of a data object that can hold values which represent locale-specific character classification.
mbstate_t
An object type other than an array type that can hold the conversion state information necessary to convert between sequences of (possibly multi-byte) characters and wide characters. If a codeset is being used such that an mbstate_t needs to preserve more than 2 levels of reserved state, the results are unspecified.
FILE
As described in <stdio.h> .
size_t
As described in <stddef.h> .
va_list
As described in <stdarg.h> .

The implementation shall support one or more programming environments in which the width of wint_t is no greater than the width of type long. The names of these programming environments can be obtained using the confstr() function or the getconf utility.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

wint_t        btowc(int);
wint_t        fgetwc(FILE *);
wchar_t      *fgetws(wchar_t *restrict, int, FILE *restrict);
wint_t        fputwc(wchar_t, FILE *);
int           fputws(const wchar_t *restrict, FILE *restrict);
int           fwide(FILE *, int);
int           fwprintf(FILE *restrict, const wchar_t *restrict, ...);
int           fwscanf(FILE *restrict, const wchar_t *restrict, ...);
wint_t        getwc(FILE *);
wint_t        getwchar(void);

int           iswalnum(wint_t);
int           iswalpha(wint_t);
int           iswcntrl(wint_t);
int           iswctype(wint_t, wctype_t);
int           iswdigit(wint_t);
int           iswgraph(wint_t);
int           iswlower(wint_t);
int           iswprint(wint_t);
int           iswpunct(wint_t);
int           iswspace(wint_t);
int           iswupper(wint_t);
int           iswxdigit(wint_t);

size_t        mbrlen(const char *restrict, size_t, mbstate_t *restrict);
size_t        mbrtowc(wchar_t *restrict, const char *restrict, size_t,
                  mbstate_t *restrict);
int           mbsinit(const mbstate_t *);
size_t        mbsrtowcs(wchar_t *restrict, const char **restrict, size_t,
                  mbstate_t *restrict);
wint_t        putwc(wchar_t, FILE *);
wint_t        putwchar(wchar_t);
int           swprintf(wchar_t *restrict, size_t,
                  const wchar_t *restrict, ...);
int           swscanf(const wchar_t *restrict,
                  const wchar_t *restrict, ...);

wint_t        towlower(wint_t);
wint_t        towupper(wint_t);

wint_t        ungetwc(wint_t, FILE *);
int           vfwprintf(FILE *restrict, const wchar_t *restrict, va_list);
int           vfwscanf(FILE *restrict, const wchar_t *restrict, va_list);
int           vwprintf(const wchar_t *restrict, va_list);
int           vswprintf(wchar_t *restrict, size_t,
                  const wchar_t *restrict, va_list);
int           vswscanf(const wchar_t *restrict, const wchar_t *restrict,
                  va_list);
int           vwscanf(const wchar_t *restrict, va_list);
size_t        wcrtomb(char *restrict, wchar_t, mbstate_t *restrict);
wchar_t      *wcscat(wchar_t *restrict, const wchar_t *restrict);
wchar_t      *wcschr(const wchar_t *, wchar_t);
int           wcscmp(const wchar_t *, const wchar_t *);
int           wcscoll(const wchar_t *, const wchar_t *);
wchar_t      *wcscpy(wchar_t *restrict, const wchar_t *restrict);
size_t        wcscspn(const wchar_t *, const wchar_t *);
size_t        wcsftime(wchar_t *restrict, size_t,
                  const wchar_t *restrict, const struct tm *restrict);
size_t        wcslen(const wchar_t *);
wchar_t      *wcsncat(wchar_t *restrict, const wchar_t *restrict, size_t);
int           wcsncmp(const wchar_t *, const wchar_t *, size_t);
wchar_t      *wcsncpy(wchar_t *restrict, const wchar_t *restrict, size_t);
wchar_t      *wcspbrk(const wchar_t *, const wchar_t *);
wchar_t      *wcsrchr(const wchar_t *, wchar_t);
size_t        wcsrtombs(char *restrict, const wchar_t **restrict,
                  size_t, mbstate_t *restrict);
size_t        wcsspn(const wchar_t *, const wchar_t *);
wchar_t      *wcsstr(const wchar_t *restrict, const wchar_t *restrict);
double        wcstod(const wchar_t *restrict, wchar_t **restrict);
float         wcstof(const wchar_t *restrict, wchar_t **restrict);
wchar_t      *wcstok(wchar_t *restrict, const wchar_t *restrict,
                  wchar_t **restrict);
long          wcstol(const wchar_t *restrict, wchar_t **restrict, int);
long double   wcstold(const wchar_t *restrict, wchar_t **restrict);
long long     wcstoll(const wchar_t *restrict, wchar_t **restrict, int);
unsigned long wcstoul(const wchar_t *restrict, wchar_t **restrict, int);
unsigned long long
              wcstoull(const wchar_t *restrict, wchar_t **restrict, int);

wchar_t      *wcswcs(const wchar_t *, const wchar_t *);
int           wcswidth(const wchar_t *, size_t);

size_t        wcsxfrm(wchar_t *restrict, const wchar_t *restrict, size_t);
int           wctob(wint_t);

wctype_t      wctype(const char *);
int           wcwidth(wchar_t);

wchar_t      *wmemchr(const wchar_t *, wchar_t, size_t);
int           wmemcmp(const wchar_t *, const wchar_t *, size_t);
wchar_t      *wmemcpy(wchar_t *restrict, const wchar_t *restrict, size_t);
wchar_t      *wmemmove(wchar_t *, const wchar_t *, size_t);
wchar_t      *wmemset(wchar_t *, wchar_t, size_t);
int           wprintf(const wchar_t *restrict, ...);
int           wscanf(const wchar_t *restrict, ...);

The <wchar.h> header shall define the following macros:

WCHAR_MAX
The maximum value representable by an object of type wchar_t.
WCHAR_MIN
The minimum value representable by an object of type wchar_t.
WEOF
Constant expression of type wint_t that is returned by several WP functions to indicate end-of-file.
NULL
As described in <stddef.h> .

The tag tm shall be declared as naming an incomplete structure type, the contents of which are described in the header <time.h> .

Inclusion of the <wchar.h> header may make visible all symbols from the headers <ctype.h>, <string.h>, <stdarg.h>, <stddef.h>, <stdio.h>, <stdlib.h>, and <time.h>.

The following sections are informative.

APPLICATION USAGE

The iswblank() function was a late addition to the ISO C standard and was introduced at the same time as the ISO C standard introduced <wctype.h>, which contains all of the isw*() functions. The Open Group Base Specifications had previously aligned with the MSE working draft and had introduced the rest of the isw*() functions into <wchar.h>. For backwards-compatibility, the original set of isw*() functions, without iswblank(), are permitted (as an XSI extension) in <wchar.h>. For maximum portability, applications should include <wctype.h> in order to obtain declarations for the isw*() functions.

RATIONALE

In the ISO C standard, the symbols referenced as XSI extensions are in <wctype.h>. Their presence here is thus an extension.

FUTURE DIRECTIONS

None.

SEE ALSO

<ctype.h> , <stdarg.h> , <stddef.h> , <stdio.h>
, <stdlib.h> , <string.h> , <time.h> , <wctype.h>
, the System Interfaces volume of
IEEE Std 1003.1-2001, btowc(), confstr(), fgetwc(),
fgetws(), fputwc(), fputws(), fwide(), fwprintf(),
fwscanf(), getwc(), getwchar(), iswalnum(),
iswalpha(), iswcntrl(), iswctype(), iswdigit(),
iswgraph(), iswlower(), iswprint(), iswpunct(),
iswspace(), iswupper(), iswxdigit(), iswctype(),
mbsinit(), mbrlen(), mbrtowc(), mbsrtowcs(),
putwc(), putwchar(), swprintf(), swscanf(),
towlower(), towupper(), ungetwc(), vfwprintf(),
vfwscanf(), vswprintf(), vswscanf(), vwscanf(),
wcrtomb(), wcsrtombs(), wcscat(), wcschr(),
wcscmp(), wcscoll(), wcscpy(), wcscspn(),
wcsftime(), wcslen(), wcsncat(), wcsncmp(),
wcsncpy(), wcspbrk(), wcsrchr(), wcsspn(),
wcsstr(), wcstod(), wcstof(), wcstok(), wcstol(),
wcstold(), wcstoll(), wcstoul(), wcstoull(),
wcswcs(), wcswidth(), wcsxfrm(), wctob(),
wctype(), wcwidth(), wmemchr(), wmemcmp(),
wmemcpy(), wmemmove(), wmemset(), wprintf(),
wscanf(), the Shell and Utilities volume of IEEE Std 1003.1-2001,
getconf

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


float.h(0p)

<float.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

float.h - floating types

SYNOPSIS

#include <float.h>

DESCRIPTION

The characteristics of floating types are defined in terms of a model that describes a representation of floating-point numbers and values that provide information about an implementation's floating-point arithmetic.

The following parameters are used to define the model for each floating-point type:

s
Sign (±1).
b
Base or radix of exponent representation (an integer >1).
e
Exponent (an integer between a minimum e_min and a maximum e_max).
p
Precision (the number of base-b digits in the significand).
f_k
Non-negative integers less than b (the significand digits).

A floating-point number x is defined by the following model:

In addition to normalized floating-point numbers (f_1>0 if x!=0), floating types may be able to contain other kinds of floating-point numbers, such as subnormal floating-point numbers ( x!=0, e= e_min, f_1=0) and unnormalized floating-point numbers ( x!=0, e> e_min, f_1=0), and values that are not floating-point numbers, such as infinities and NaNs. A NaN is an encoding signifying Not-a-Number. A quiet NaN propagates through almost every arithmetic operation without raising a floating-point exception; a signaling NaN generally raises a floating-point exception when occurring as an arithmetic operand.

The accuracy of the floating-point operations ( '+' , '-' , '*' , '/' ) and of the library functions in <math.h> and <complex.h> that return floating-point results is implementation-defined. The implementation may state that the accuracy is unknown.

All integer values in the <float.h> header, except FLT_ROUNDS, shall be constant expressions suitable for use in #if preprocessing directives; all floating values shall be constant expressions. All except DECIMAL_DIG, FLT_EVAL_METHOD, FLT_RADIX, and FLT_ROUNDS have separate names for all three floating-point types. The floating-point model representation is provided for all values except FLT_EVAL_METHOD and FLT_ROUNDS.

The rounding mode for floating-point addition is characterized by the implementation-defined value of FLT_ROUNDS:

-1
Indeterminable.
0
Toward zero.
1
To nearest.
2
Toward positive infinity.
3
Toward negative infinity.

All other values for FLT_ROUNDS characterize implementation-defined rounding behavior.

The values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type. The use of evaluation formats is characterized by the implementation-defined value of FLT_EVAL_METHOD:

-1
Indeterminable.
0
Evaluate all operations and constants just to the range and precision of the type.
1
Evaluate operations and constants of type float and double to the range and precision of the double type; evaluate long double operations and constants to the range and precision of the long double type.
2
Evaluate all operations and constants to the range and precision of the long double type.

All other negative values for FLT_EVAL_METHOD characterize implementation-defined behavior.

The values given in the following list shall be defined as constant expressions with implementation-defined values that are greater or equal in magnitude (absolute value) to those shown, with the same sign.

*
Radix of exponent representation, b.
FLT_RADIX
2

*
Number of base-FLT_RADIX digits in the floating-point significand, p.
FLT_MANT_DIG
DBL_MANT_DIG
LDBL_MANT_DIG

*
Number of decimal digits, n, such that any floating-point number in the widest supported floating type with p_max radix b digits can be rounded to a floating-point number with n decimal digits and back again without change to the value.

DECIMAL_DIG
10

*
Number of decimal digits, q, such that any floating-point number with q decimal digits can be rounded into a floating-point number with p radix b digits and back again without change to the q decimal digits.

FLT_DIG
6
DBL_DIG
10
LDBL_DIG
10

*
Minimum negative integer such that FLT_RADIX raised to that power minus 1 is a normalized floating-point number, e_min.
FLT_MIN_EXP
DBL_MIN_EXP
LDBL_MIN_EXP

*
Minimum negative integer such that 10 raised to that power is in the range of normalized floating-point numbers.

FLT_MIN_10_EXP
-37
DBL_MIN_10_EXP
-37
LDBL_MIN_10_EXP
-37

*
Maximum integer such that FLT_RADIX raised to that power minus 1 is a representable finite floating-point number, e_max.
FLT_MAX_EXP
DBL_MAX_EXP
LDBL_MAX_EXP

*
Maximum integer such that 10 raised to that power is in the range of representable finite floating-point numbers.

FLT_MAX_10_EXP
+37
DBL_MAX_10_EXP
+37
LDBL_MAX_10_EXP
+37

The values given in the following list shall be defined as constant expressions with implementation-defined values that are greater than or equal to those shown:

*
Maximum representable finite floating-point number.

FLT_MAX
1E+37
DBL_MAX
1E+37
LDBL_MAX
1E+37

The values given in the following list shall be defined as constant expressions with implementation-defined (positive) values that are less than or equal to those shown:

*
The difference between 1 and the least value greater than 1 that is representable in the given floating-point type, b**1-p.
FLT_EPSILON
1E-5
DBL_EPSILON
1E-9
LDBL_EPSILON
1E-9

*
Minimum normalized positive floating-point number, b**e_min.
FLT_MIN
1E-37
DBL_MIN
1E-37
LDBL_MIN
1E-37

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<complex.h> , <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


termios.h(0p)

<termios.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

termios.h - define values for termios

SYNOPSIS

#include <termios.h>

DESCRIPTION

The <termios.h> header contains the definitions used by the terminal I/O interfaces (see General Terminal Interface for the structures and names defined).

The termios Structure

The following data types shall be defined through typedef:

cc_t
Used for terminal special characters.
speed_t
Used for terminal baud rates.
tcflag_t
Used for terminal modes.

The above types shall be all unsigned integer types.

The implementation shall support one or more programming environments in which the widths of cc_t, speed_t, and tcflag_t are no greater than the width of type long. The names of these programming environments can be obtained using the confstr() function or the getconf utility.

The termios structure shall be defined, and shall include at least the following members:

tcflag_t  c_iflag     Input modes.
tcflag_t  c_oflag     Output modes.
tcflag_t  c_cflag     Control modes.
tcflag_t  c_lflag     Local modes.
cc_t      c_cc[NCCS]  Control characters.

A definition shall be provided for:

NCCS
Size of the array c_cc for control characters.

The following subscript names for the array c_cc shall be defined:
Subscript Usage |  |
Canonical Mode | Non-Canonical Mode | Description
VEOF |  | EOF character.
VEOL |  | EOL character.
VERASE |  | ERASE character.
VINTR | VINTR | INTR character.
VKILL |  | KILL character.
 | VMIN | MIN value.
VQUIT | VQUIT | QUIT character.
VSTART | VSTART | START character.
VSTOP | VSTOP | STOP character.
VSUSP | VSUSP | SUSP character.
 | VTIME | TIME value.

The subscript values shall be unique, except that the VMIN and VTIME subscripts may have the same values as the VEOF and VEOL subscripts, respectively.

The following flags shall be provided.

Input Modes

The c_iflag field describes the basic terminal input control:

BRKINT
Signal interrupt on break.
ICRNL
Map CR to NL on input.
IGNBRK
Ignore break condition.
IGNCR
Ignore CR.
IGNPAR
Ignore characters with parity errors.
INLCR
Map NL to CR on input.
INPCK
Enable input parity check.
ISTRIP
Strip character.
IXANY
Enable any character to restart output.
IXOFF
Enable start/stop input control.
IXON
Enable start/stop output control.
PARMRK
Mark parity errors.

Output Modes

The c_oflag field specifies the system treatment of output:

OPOST
Post-process output.
ONLCR
Map NL to CR-NL on output.
OCRNL
Map CR to NL on output.
ONOCR
No CR output at column 0.
ONLRET
NL performs CR function.
OFILL
Use fill characters for delay.
NLDLY
Select newline delays:
NL0
Newline type 0.
NL1
Newline type 1.

CRDLY
Select carriage-return delays:
CR0
Carriage-return delay type 0.
CR1
Carriage-return delay type 1.
CR2
Carriage-return delay type 2.
CR3
Carriage-return delay type 3.

TABDLY
Select horizontal-tab delays:
TAB0
Horizontal-tab delay type 0.
TAB1
Horizontal-tab delay type 1.
TAB2
Horizontal-tab delay type 2.
TAB3
Expand tabs to spaces.

BSDLY
Select backspace delays:
BS0
Backspace-delay type 0.
BS1
Backspace-delay type 1.

VTDLY
Select vertical-tab delays:
VT0
Vertical-tab delay type 0.
VT1
Vertical-tab delay type 1.

FFDLY
Select form-feed delays:
FF0
Form-feed delay type 0.
FF1
Form-feed delay type 1.

Baud Rate Selection

The input and output baud rates are stored in the termios structure. These are the valid values for objects of type speed_t. The following values shall be defined, but not all baud rates need be supported by the underlying hardware.

B0
Hang up
B50
50 baud
B75
75 baud
B110
110 baud
B134
134.5 baud
B150
150 baud
B200
200 baud
B300
300 baud
B600
600 baud
B1200
1200 baud
B1800
1800 baud
B2400
2400 baud
B4800
4800 baud
B9600
9600 baud
B19200
19200 baud
B38400
38400 baud

Control Modes

The c_cflag field describes the hardware control of the terminal; not all values specified are required to be supported by the underlying hardware:

CSIZE
Character size:
CS5
5 bits
CS6
6 bits
CS7
7 bits
CS8
8 bits

CSTOPB
Send two stop bits, else one.
CREAD
Enable receiver.
PARENB
Parity enable.
PARODD
Odd parity, else even.
HUPCL
Hang up on last close.
CLOCAL
Ignore modem status lines.

The implementation shall support the functionality associated with the symbols CS7, CS8, CSTOPB, PARODD, and PARENB.

Local Modes

The c_lflag field of the argument structure is used to control various terminal functions:

ECHO
Enable echo.
ECHOE
Echo erase character as error-correcting backspace.
ECHOK
Echo KILL.
ECHONL
Echo NL.
ICANON
Canonical input (erase and kill processing).
IEXTEN
Enable extended input character processing.
ISIG
Enable signals.
NOFLSH
Disable flush after interrupt or quit.
TOSTOP
Send SIGTTOU for background output.

Attribute Selection

The following symbolic constants for use with tcsetattr() are defined:

TCSANOW
Change attributes immediately.
TCSADRAIN
Change attributes when output has drained.
TCSAFLUSH
Change attributes when output has drained; also flush pending input.

Line Control

The following symbolic constants for use with tcflush() shall be defined:

TCIFLUSH
Flush pending input.
TCIOFLUSH
Flush both pending input and untransmitted output.
TCOFLUSH
Flush untransmitted output.

The following symbolic constants for use with tcflow() shall be defined:

TCIOFF
Transmit a STOP character, intended to suspend input data.
TCION
Transmit a START character, intended to restart input data.
TCOOFF
Suspend output.
TCOON
Restart output.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

speed_t cfgetispeed(const struct termios *);
speed_t cfgetospeed(const struct termios *);
int     cfsetispeed(struct termios *, speed_t);
int     cfsetospeed(struct termios *, speed_t);
int     tcdrain(int);
int     tcflow(int, int);
int     tcflush(int, int);
int     tcgetattr(int, struct termios *);

pid_t   tcgetsid(int);

int     tcsendbreak(int, int);
int     tcsetattr(int, int, const struct termios *);

The following sections are informative.

APPLICATION USAGE

The following names are reserved for XSI-conformant systems to use as an extension to the above; therefore strictly conforming applications shall not use them:
CBAUD | EXTB | VDSUSP
DEFECHO | FLUSHO | VLNEXT
ECHOCTL | LOBLK | VREPRINT
ECHOKE | PENDIN | VSTATUS
ECHOPRT | SWTCH | VWERASE
EXTA | VDISCARD |

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, cfgetispeed(), cfgetospeed(), cfsetispeed(), cfsetospeed(), confstr(), tcdrain(), tcflow(), tcflush(), tcgetattr(), tcgetsid(), tcsendbreak(), tcsetattr(), the Shell and Utilities volume of IEEE Std 1003.1-2001, getconf, General Terminal Interface

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


timeb.h(0p)

Status: 403 Forbidden timeb.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/timeb.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


poll.h(0p)

<poll.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

poll.h - definitions for the poll() function

SYNOPSIS

#include <poll.h>

DESCRIPTION

The <poll.h> header shall define the pollfd structure that includes at least the following members:

int    fd       The following descriptor being polled.
short  events   The input event flags (see below).
short  revents  The output event flags (see below).

The <poll.h> header shall define the following type through typedef:

nfds_t
An unsigned integer type used for the number of file descriptors.

The implementation shall support one or more programming environments in which the width of nfds_t is no greater than the width of type long. The names of these programming environments can be obtained using the confstr() function or the getconf utility.

The following symbolic constants shall be defined, zero or more of which may be OR'ed together to form the events or revents members in the pollfd structure:

POLLIN
Data other than high-priority data may be read without blocking.
POLLRDNORM
Normal data may be read without blocking.
POLLRDBAND
Priority data may be read without blocking.
POLLPRI
High priority data may be read without blocking.
POLLOUT
Normal data may be written without blocking.
POLLWRNORM
Equivalent to POLLOUT.
POLLWRBAND
Priority data may be written.
POLLERR
An error has occurred ( revents only).
POLLHUP
Device has been disconnected ( revents only).
POLLNVAL
Invalid fd member ( revents only).

The significance and semantics of normal, priority, and high-priority data are file and device-specific.

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

int   poll(struct pollfd[], nfds_t, int);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, confstr(), poll(), the Shell and Utilities volume of IEEE Std 1003.1-2001, getconf

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmtmsg.h(0p)

<fmtmsg.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fmtmsg.h - message display structures

SYNOPSIS

#include <fmtmsg.h>

DESCRIPTION

The <fmtmsg.h> header shall define the following macros, which expand to constant integer expressions:

MM_HARD
Source of the condition is hardware.
MM_SOFT
Source of the condition is software.
MM_FIRM
Source of the condition is firmware.
MM_APPL
Condition detected by application.
MM_UTIL
Condition detected by utility.
MM_OPSYS
Condition detected by operating system.
MM_RECOVER
Recoverable error.
MM_NRECOV
Non-recoverable error.
MM_HALT
Error causing application to halt.
MM_ERROR
Application has encountered a non-fatal fault.
MM_WARNING
Application has detected unusual non-error condition.
MM_INFO
Informative message.
MM_NOSEV
No severity level provided for the message.
MM_PRINT
Display message on standard error.
MM_CONSOLE
Display message on system console.

The table below indicates the null values and identifiers for fmtmsg() arguments. The <fmtmsg.h> header shall define the macros in the Identifier column, which expand to constant expressions that expand to expressions of the type indicated in the Type column:
Argument | Type | Null-Value | Identifier
label | char * | (char*)0 | MM_NULLLBL
severity | int | 0 | MM_NULLSEV
class | long | 0L | MM_NULLMC
text | char * | (char*)0 | MM_NULLTXT
action | char * | (char*)0 | MM_NULLACT
tag | char * | (char*)0 | MM_NULLTAG

The <fmtmsg.h> header shall also define the following macros for use as return values for fmtmsg():

MM_OK
The function succeeded.
MM_NOTOK
The function failed completely.
MM_NOMSG
The function was unable to generate a message on standard error, but otherwise succeeded.
MM_NOCON
The function was unable to generate a console message, but otherwise succeeded.

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

int fmtmsg(long, const char *, int,
    const char *, const char *, const char *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, fmtmsg()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


string.h(0p)

<string.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

string.h - string operations

SYNOPSIS

#include <string.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <string.h> header shall define the following:

NULL
Null pointer constant.
size_t
As described in <stddef.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void    *memccpy(void *restrict, const void *restrict, int, size_t);

void    *memchr(const void *, int, size_t);
int      memcmp(const void *, const void *, size_t);
void    *memcpy(void *restrict, const void *restrict, size_t);
void    *memmove(void *, const void *, size_t);
void    *memset(void *, int, size_t);
char    *strcat(char *restrict, const char *restrict);
char    *strchr(const char *, int);
int      strcmp(const char *, const char *);
int      strcoll(const char *, const char *);
char    *strcpy(char *restrict, const char *restrict);
size_t   strcspn(const char *, const char *);

char    *strdup(const char *);

char    *strerror(int);

int     *strerror_r(int, char *, size_t);

size_t   strlen(const char *);
char    *strncat(char *restrict, const char *restrict, size_t);
int      strncmp(const char *, const char *, size_t);
char    *strncpy(char *restrict, const char *restrict, size_t);
char    *strpbrk(const char *, const char *);
char    *strrchr(const char *, int);
size_t   strspn(const char *, const char *);
char    *strstr(const char *, const char *);
char    *strtok(char *restrict, const char *restrict);

char    *strtok_r(char *, const char *, char **);

size_t   strxfrm(char *restrict, const char *restrict, size_t);

Inclusion of the <string.h> header may also make visible all symbols from <stddef.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<stddef.h> , <sys/types.h> , the System
Interfaces volume of IEEE Std 1003.1-2001, memccpy(), memchr(),
memcmp(), memcpy(), memmove(), memset(), strcat(),
strchr(), strcmp(), strcoll(), strcpy(), strcspn(),
strdup(), strerror(), strlen(), strncat(),
strncmp(), strncpy(), strpbrk(), strrchr(),
strspn(), strstr(), strtok(), strxfrm()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


signal.h(0p)

<signal.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

signal.h - signals

SYNOPSIS

#include <signal.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <signal.h> header shall define the following symbolic constants, each of which expands to a distinct constant expression of the type:

void (*)(int)

whose value matches no declarable function.

SIG_DFL
Request for default signal handling.
SIG_ERR
Return value from signal() in case of error.
SIG_HOLD
Request that signal be held.
SIG_IGN
Request that signal be ignored.

The following data types shall be defined through typedef:

sig_atomic_t
Possibly volatile-qualified integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts.
sigset_t
Integer or structure type of an object used to represent sets of signals.
pid_t
As described in <sys/types.h> .

The <signal.h> header shall define the sigevent structure, which has at least the following members:

int                    sigev_notify            Notification type.
int                    sigev_signo             Signal number.
union sigval           sigev_value             Signal value.
void(*)(union sigval)  sigev_notify_function   Notification function.
(pthread_attr_t *)     sigev_notify_attributes Notification attributes.

The following values of sigev_notify shall be defined:

SIGEV_NONE
No asynchronous notification is delivered when the event of interest occurs.
SIGEV_SIGNAL
A queued signal, with an application-defined value, is generated when the event of interest occurs.
SIGEV_THREAD
A notification function is called to perform notification.

The sigval union shall be defined as:

int    sival_int    Integer signal value.
void  *sival_ptr    Pointer signal value.

This header shall also declare the macros SIGRTMIN and SIGRTMAX, which evaluate to integer expressions, and specify a range of signal numbers that are reserved for application use and for which the realtime signal behavior specified in this volume of IEEE Std 1003.1-2001 is supported. The signal numbers in this range do not overlap any of the signals specified in the following table.

The range SIGRTMIN through SIGRTMAX inclusive shall include at least {RTSIG_MAX} signal numbers.

It is implementation-defined whether realtime signal behavior is supported for other signals.

This header also declares the constants that are used to refer to the signals that occur in the system. Signals defined here begin with the letters SIG. Each of the signals have distinct positive integer values. The value 0 is reserved for use as the null signal (see kill()). Additional implementation-defined signals may occur in the system.

The ISO C standard only requires the signal names SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, and SIGTERM to be defined.

The following signals shall be supported on all implementations (default actions are explained below the table):
Signal | Default Action | Description
SIGABRT | A | Process abort signal.
SIGALRM | T | Alarm clock.
SIGBUS | A | Access to an undefined portion of a memory object.
SIGCHLD | I | Child process terminated, stopped,
 |  | or continued.
SIGCONT | C | Continue executing, if stopped.
SIGFPE | A | Erroneous arithmetic operation.
SIGHUP | T | Hangup.
SIGILL | A | Illegal instruction.
SIGINT | T | Terminal interrupt signal.
SIGKILL | T | Kill (cannot be caught or ignored).
SIGPIPE | T | Write on a pipe with no one to read it.
SIGQUIT | A | Terminal quit signal.
SIGSEGV | A | Invalid memory reference.
SIGSTOP | S | Stop executing (cannot be caught or ignored).
SIGTERM | T | Termination signal.
SIGTSTP | S | Terminal stop signal.
SIGTTIN | S | Background process attempting read.
SIGTTOU | S | Background process attempting write.
SIGUSR1 | T | User-defined signal 1.
SIGUSR2 | T | User-defined signal 2.
SIGPOLL | T | Pollable event.
SIGPROF | T | Profiling timer expired.
SIGSYS | A | Bad system call.
SIGTRAP | A | Trace/breakpoint trap.
SIGURG | I | High bandwidth data is available at a socket.
SIGVTALRM | T | Virtual timer expired.
SIGXCPU | A | CPU time limit exceeded.
SIGXFSZ | A | File size limit exceeded.

The default actions are as follows:

T
Abnormal termination of the process. The process is terminated with all the consequences of _exit() except that the status made available to wait() and waitpid() indicates abnormal termination by the specified signal.
A
Abnormal termination of the process.
Additionally, implementation-defined abnormal termination actions, such as creation of a core file, may occur.
I
Ignore the signal.
S
Stop the process.
C
Continue the process, if it is stopped; otherwise, ignore the signal.

The header shall provide a declaration of struct sigaction, including at least the following members:

void (*sa_handler)(int)  Pointer to a signal-catching function or one of the macros
                         SIG_IGN or SIG_DFL.
sigset_t sa_mask         Set of signals to be blocked during execution of the signal
                         handling function.
int      sa_flags        Special flags.
void (*sa_sigaction)(int, siginfo_t *, void *)
                         Pointer to a signal-catching function.

The storage occupied by sa_handler and sa_sigaction may overlap, and a conforming application shall not use both simultaneously.

The following shall be declared as constants:

SA_NOCLDSTOP
Do not generate SIGCHLD when children stop
or stopped children continue.
SIG_BLOCK
The resulting set is the union of the current set and the signal set pointed to by the argument set.
SIG_UNBLOCK
The resulting set is the intersection of the current set and the complement of the signal set pointed to by the argument set.
SIG_SETMASK
The resulting set is the signal set pointed to by the argument set.
SA_ONSTACK
Causes signal delivery to occur on an alternate stack.
SA_RESETHAND
Causes signal dispositions to be set to SIG_DFL on entry to signal handlers.
SA_RESTART
Causes certain functions to become restartable.
SA_SIGINFO
Causes extra information to be passed to signal handlers at the time of receipt of a signal.
SA_NOCLDWAIT
Causes implementations not to create zombie processes on child death.
SA_NODEFER
Causes signal not to be automatically blocked on entry to signal handler.
SS_ONSTACK
Process is executing on an alternate signal stack.
SS_DISABLE
Alternate signal stack is disabled.
MINSIGSTKSZ
Minimum stack size for a signal handler.
SIGSTKSZ
Default size in bytes for the alternate signal stack.

The ucontext_t structure shall be defined through typedef as described in <ucontext.h>.

The mcontext_t type shall be defined through typedef as described in <ucontext.h>.

The <signal.h> header shall define the stack_t type as a structure that includes at least the following members:

void     *ss_sp       Stack base or pointer.
size_t    ss_size     Stack size.
int       ss_flags    Flags.

The <signal.h> header shall define the sigstack structure that includes at least the following members:

int       ss_onstack  Non-zero when signal stack is in use.
void     *ss_sp       Signal stack pointer.

The <signal.h> header shall define the siginfo_t type as a structure that includes at least the following members:

int           si_signo  Signal number.

int           si_errno  If non-zero, an errno value associated with
                        this signal, as defined in <errno.h>.

int           si_code   Signal code.

pid_t         si_pid    Sending process ID.
uid_t         si_uid    Real user ID of sending process.
void         *si_addr   Address of faulting instruction.
int           si_status Exit value or signal.
long          si_band   Band event for SIGPOLL.

union sigval  si_value  Signal value.

The macros specified in the Code column of the following table are defined for use as values of si_code that are signal-specific or non-signal-specific reasons why the signal was generated.
Signal | Code | Reason
SIGILL | ILL_ILLOPC | Illegal opcode.
 | ILL_ILLOPN | Illegal operand.
 | ILL_ILLADR | Illegal addressing mode.
 | ILL_ILLTRP | Illegal trap.
 | ILL_PRVOPC | Privileged opcode.
 | ILL_PRVREG | Privileged register.
 | ILL_COPROC | Coprocessor error.
 | ILL_BADSTK | Internal stack error.
SIGFPE | FPE_INTDIV | Integer divide by zero.
 | FPE_INTOVF | Integer overflow.
 | FPE_FLTDIV | Floating-point divide by zero.
 | FPE_FLTOVF | Floating-point overflow.
 | FPE_FLTUND | Floating-point underflow.
 | FPE_FLTRES | Floating-point inexact result.
 | FPE_FLTINV | Invalid floating-point operation.
 | FPE_FLTSUB | Subscript out of range.
SIGSEGV | SEGV_MAPERR | Address not mapped to object.
 | SEGV_ACCERR | Invalid permissions for mapped object.
SIGBUS | BUS_ADRALN | Invalid address alignment.
 | BUS_ADRERR | Nonexistent physical address.
 | BUS_OBJERR | Object-specific hardware error.
SIGTRAP | TRAP_BRKPT | Process breakpoint.
 | TRAP_TRACE | Process trace trap.
SIGCHLD | CLD_EXITED | Child has exited.
 | CLD_KILLED | Child has terminated abnormally and did not create a core file.
 | CLD_DUMPED | Child has terminated abnormally and created a core file.
 | CLD_TRAPPED | Traced child has trapped.
 | CLD_STOPPED | Child has stopped.
 | CLD_CONTINUED | Stopped child has continued.
SIGPOLL | POLL_IN | Data input available.
 | POLL_OUT | Output buffers available.
 | POLL_MSG | Input message available.
 | POLL_ERR | I/O error.
 | POLL_PRI | High priority input available.
 | POLL_HUP | Device disconnected.
Any | SI_USER | Signal sent by kill().
 | SI_QUEUE | Signal sent by the sigqueue().
 | SI_TIMER | Signal generated by expiration of a timer set by timer_settime().
 | SI_ASYNCIO | Signal generated by completion of an asynchronous I/O request.
 | SI_MESGQ | Signal generated by arrival of a message on an empty message queue.

Implementations may support additional si_code values not included in this list, may generate values included in this list under circumstances other than those described in this list, and may contain extensions or limitations that prevent some values from being generated. Implementations do not generate a different value from the ones described in this list for circumstances described in this list.

In addition, the following signal-specific information shall be available:
Signal | Member | Value
SIGILL | void * si_addr | Address of faulting instruction.
SIGFPE |  |
SIGSEGV | void * si_addr | Address of faulting memory reference.
SIGBUS |  |
SIGCHLD | pid_t si_pid | Child process ID.
 | int si_status | Exit value or signal.
 | uid_t si_uid | Real user ID of the process that sent the signal.
SIGPOLL | long si_band | Band event for POLL_IN, POLL_OUT, or POLL_MSG.

For some implementations, the value of si_addr may be inaccurate.

The following shall be declared as functions and may also be defined as macros:

void (*bsd_signal(int, void (*)(int)))(int);

int    kill(pid_t, int);

int    killpg(pid_t, int);

int    pthread_kill(pthread_t, int);
int    pthread_sigmask(int, const sigset_t *, sigset_t *);

int    raise(int);

int    sigaction(int, const struct sigaction *restrict,
           struct sigaction *restrict);
int    sigaddset(sigset_t *, int);

int    sigaltstack(const stack_t *restrict, stack_t *restrict);

int    sigdelset(sigset_t *, int);
int    sigemptyset(sigset_t *);
int    sigfillset(sigset_t *);

int    sighold(int);
int    sigignore(int);
int    siginterrupt(int, int);

int    sigismember(const sigset_t *, int);

void (*signal(int, void (*)(int)))(int);

int    sigpause(int);

int    sigpending(sigset_t *);
int    sigprocmask(int, const sigset_t *restrict, sigset_t *restrict);

int    sigqueue(pid_t, int, const union sigval);

int    sigrelse(int);
void (*sigset(int, void (*)(int)))(int);

int    sigsuspend(const sigset_t *);

int    sigtimedwait(const sigset_t *restrict, siginfo_t *restrict,
           const struct timespec *restrict);

int    sigwait(const sigset_t *restrict, int *restrict);

int    sigwaitinfo(const sigset_t *restrict, siginfo_t *restrict);

Inclusion of the <signal.h> header may make visible all symbols from the <time.h> header.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<errno.h> , <stropts.h> , <sys/types.h> , <time.h>
, <ucontext.h> , the System Interfaces volume of IEEE Std 1003.1-2001,
alarm(), bsd_signal(), ioctl(), kill(), killpg(),
raise(), sigaction(), sigaddset(), sigaltstack(),
sigdelset(), sigemptyset(), sigfillset(), siginterrupt(),
sigismember(), signal(), sigpending(), sigprocmask(),
sigqueue(), sigsuspend(), sigwaitinfo(), wait(),
waitid()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_uio.h(0p)

<sys/uio.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/uio.h - definitions for vector I/O operations

SYNOPSIS

#include <sys/uio.h>

DESCRIPTION

The <sys/uio.h> header shall define the iovec structure that includes at least the following members:

void   *iov_base  Base address of a memory region for input or output.
size_t  iov_len   The size of the memory pointed to by iov_base.

The <sys/uio.h> header uses the iovec structure for scatter/gather I/O.

The ssize_t and size_t types shall be defined as described in <sys/types.h>.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

ssize_t readv(int, const struct iovec *, int);
ssize_t writev(int, const struct iovec *, int);

The following sections are informative.

APPLICATION USAGE

The implementation can put a limit on the number of scatter/gather elements which can be processed in one call. The symbol {IOV_MAX} defined in <limits.h> should always be used to learn about the limits instead of assuming a fixed value.

RATIONALE

Traditionally, the maximum number of scatter/gather elements the system can process in one call were described by the symbolic value {UIO_MAXIOV}. In IEEE Std 1003.1-2001 this value is replaced by the constant {IOV_MAX} which can be found in <limits.h>.

FUTURE DIRECTIONS

None.

SEE ALSO

<limits.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, read(), write()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_times.h(0p)

<sys/times.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/times.h - file access and modification times structure

SYNOPSIS

#include <sys/times.h>

DESCRIPTION

The <sys/times.h> header shall define the structure tms, which is returned by times() and includes at least the following members:

clock_t  tms_utime  User CPU time.
clock_t  tms_stime  System CPU time.
clock_t  tms_cutime User CPU time of terminated child processes.
clock_t  tms_cstime System CPU time of terminated child processes.

The clock_t type shall be defined as described in <sys/types.h> .

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

clock_t times(struct tms *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, times()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


resource.h(0p)

Status: 403 Forbidden resource.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/resource.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


sys_mman.h(0p)

<sys/mman.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/mman.h - memory management declarations

SYNOPSIS

#include <sys/mman.h>

DESCRIPTION

The <sys/mman.h> header shall be supported if the implementation supports at least one of the following options:

*
The Memory Mapped Files option

*
The Shared Memory Objects option

*
The Process Memory Locking option

*
The Memory Protection option

*
The Typed Memory Objects option

*
The Synchronized Input and Output option

*
The Advisory Information option

*
The Typed Memory Objects option

If one or more of the Advisory Information, Memory Mapped Files, or Shared Memory Objects options are supported, the following protection options shall be defined:

PROT_READ
Page can be read.
PROT_WRITE
Page can be written.
PROT_EXEC
Page can be executed.
PROT_NONE
Page cannot be accessed.

The following flag options shall be defined:

MAP_SHARED
Share changes.
MAP_PRIVATE
Changes are private.
MAP_FIXED
Interpret addr exactly.

The following flags shall be defined for msync():

MS_ASYNC
Perform asynchronous writes.
MS_SYNC
Perform synchronous writes.
MS_INVALIDATE
Invalidate mappings.

The following symbolic constants shall be defined for the mlockall() function:

MCL_CURRENT
Lock currently mapped pages.
MCL_FUTURE
Lock pages that become mapped.

The symbolic constant MAP_FAILED shall be defined to indicate a failure from the mmap() function.

If the Advisory Information and either the Memory Mapped Files or Shared Memory Objects options are supported, values for advice used by posix_madvise() shall be defined as follows:

POSIX_MADV_NORMAL

The application has no advice to give on its behavior with respect to the specified range. It is the default characteristic if no advice is given for a range of memory.

POSIX_MADV_SEQUENTIAL

The application expects to access the specified range sequentially from lower addresses to higher addresses.

POSIX_MADV_RANDOM

The application expects to access the specified range in a random order.

POSIX_MADV_WILLNEED

The application expects to access the specified range in the near future.

POSIX_MADV_DONTNEED

The application expects that it will not access the specified range in the near future.

The following flags shall be defined for posix_typed_mem_open():

POSIX_TYPED_MEM_ALLOCATE

Allocate on mmap().

POSIX_TYPED_MEM_ALLOCATE_CONTIG

Allocate contiguously on mmap().

POSIX_TYPED_MEM_MAP_ALLOCATABLE

Map on mmap(), without affecting allocatability.

The mode_t, off_t, and size_t types shall be defined as described in <sys/types.h> .

The <sys/mman.h> header shall define the structure posix_typed_mem_info, which includes at least the following member:

size_t  posix_tmi_length  Maximum length which may be allocated
                          from a typed memory object.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    mlock(const void *, size_t);

int    mlockall(int);

void  *mmap(void *, size_t, int, int, int, off_t);

int    mprotect(void *, size_t, int);

int    msync(void *, size_t, int);

int    munlock(const void *, size_t);

int    munlockall(void);

int    munmap(void *, size_t);

int    posix_madvise(void *, size_t, int);

int    posix_mem_offset(const void *restrict, size_t, off_t *restrict,
           size_t *restrict, int *restrict);
int    posix_typed_mem_get_info(int, struct posix_typed_mem_info *);
int    posix_typed_mem_open(const char *, int, int);

int    shm_open(const char *, int, mode_t);
int    shm_unlink(const char *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of
IEEE Std 1003.1-2001, mlock(), mlockall(), mmap(),
mprotect(), msync(), munlock(), munlockall(),
munmap(), posix_mem_offset(),
posix_typed_mem_get_info(), posix_typed_mem_open(), shm_open(),
shm_unlink()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ulimit.h(0p)

<ulimit.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ulimit.h - ulimit commands

SYNOPSIS

#include <ulimit.h>

DESCRIPTION

The <ulimit.h> header shall define the symbolic constants used by the ulimit() function.

Symbolic constants:

UL_GETFSIZE
Get maximum file size.
UL_SETFSIZE
Set maximum file size.

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

long ulimit(int, ...);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, ulimit()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_socket.h(0p)

<sys/socket.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/socket.h - main sockets header

SYNOPSIS

#include <sys/socket.h>

DESCRIPTION

The <sys/socket.h> header shall define the type socklen_t, which is an integer type of width of at least 32 bits; see APPLICATION USAGE.

The <sys/socket.h> header shall define the unsigned integer type sa_family_t.

The <sys/socket.h> header shall define the sockaddr structure that includes at least the following members:

sa_family_t  sa_family  Address family.
char         sa_data[]  Socket address (variable-length data).

The sockaddr structure is used to define a socket address which is used in the bind(), connect(), getpeername(), getsockname(), recvfrom(), and sendto() functions.

The <sys/socket.h> header shall define the sockaddr_storage structure. This structure shall be:

*
Large enough to accommodate all supported protocol-specific address structures

*
Aligned at an appropriate boundary so that pointers to it can be cast as pointers to protocol-specific address structures and used to access the fields of those structures without alignment problems

The sockaddr_storage structure shall contain at least the following members:

sa_family_t   ss_family

When a sockaddr_storage structure is cast as a sockaddr structure, the ss_family field of the sockaddr_storage structure shall map onto the sa_family field of the sockaddr structure. When a sockaddr_storage structure is cast as a protocol-specific address structure, the ss_family field shall map onto a field of that structure that is of type sa_family_t and that identifies the protocol's address family.

The <sys/socket.h> header shall define the msghdr structure that includes at least the following members:

void          *msg_name        Optional address.
socklen_t      msg_namelen     Size of address.
struct iovec  *msg_iov         Scatter/gather array.
int            msg_iovlen      Members in msg_iov.
void          *msg_control     Ancillary data; see below.
socklen_t      msg_controllen  Ancillary data buffer len.
int            msg_flags       Flags on received message.

The msghdr structure is used to minimize the number of directly supplied parameters to the recvmsg() and sendmsg() functions. This structure is used as a value- result parameter in the recvmsg() function and value only for the sendmsg() function.

The iovec structure shall be defined as described in <sys/uio.h> .

The <sys/socket.h> header shall define the cmsghdr structure that includes at least the following members:

socklen_t  cmsg_len    Data byte count, including the cmsghdr.
int        cmsg_level  Originating protocol.
int        cmsg_type   Protocol-specific type.

The cmsghdr structure is used for storage of ancillary data object information.

Ancillary data consists of a sequence of pairs, each consisting of a cmsghdr structure followed by a data array. The data array contains the ancillary data message, and the cmsghdr structure contains descriptive information that allows an application to correctly parse the data.

The values for cmsg_level shall be legal values for the level argument to the getsockopt() and setsockopt() functions. The system documentation shall specify the cmsg_type definitions for the supported protocols.

Ancillary data is also possible at the socket level. The <sys/socket.h> header defines the following macro for use as the cmsg_type value when cmsg_level is SOL_SOCKET:

SCM_RIGHTS
Indicates that the data array contains the access rights to be sent or received.

The <sys/socket.h> header defines the following macros to gain access to the data arrays in the ancillary data associated with a message header:

CMSG_DATA(cmsg)

If the argument is a pointer to a cmsghdr structure, this macro shall return an unsigned character pointer to the data array associated with the cmsghdr structure.

CMSG_NXTHDR(mhdr,cmsg)

If the first argument is a pointer to a msghdr structure and the second argument is a pointer to a cmsghdr structure in the ancillary data pointed to by the msg_control field of that msghdr structure, this macro shall return a pointer to the next cmsghdr structure, or a null pointer if this structure is the last cmsghdr in the ancillary data.

CMSG_FIRSTHDR(mhdr)

If the argument is a pointer to a msghdr structure, this macro shall return a pointer to the first cmsghdr structure in the ancillary data associated with this msghdr structure, or a null pointer if there is no ancillary data associated with the msghdr structure.

The <sys/socket.h> header shall define the linger structure that includes at least the following members:

int  l_onoff   Indicates whether linger option is enabled.
int  l_linger  Linger time, in seconds.

The <sys/socket.h> header shall define the following macros, with distinct integer values:

SOCK_DGRAM
Datagram socket.
SOCK_RAW
Raw Protocol Interface.
SOCK_SEQPACKET
Sequenced-packet socket.
SOCK_STREAM
Byte-stream socket.

The <sys/socket.h> header shall define the following macro for use as the level argument of setsockopt() and getsockopt().

SOL_SOCKET
Options to be accessed at socket level, not protocol level.

The <sys/socket.h> header shall define the following macros, with distinct integer values, for use as the option_name argument in getsockopt() or setsockopt() calls:

SO_ACCEPTCONN
Socket is accepting connections.
SO_BROADCAST
Transmission of broadcast messages is supported.
SO_DEBUG
Debugging information is being recorded.
SO_DONTROUTE
Bypass normal routing.
SO_ERROR
Socket error status.
SO_KEEPALIVE
Connections are kept alive with periodic messages.
SO_LINGER
Socket lingers on close.
SO_OOBINLINE
Out-of-band data is transmitted in line.
SO_RCVBUF
Receive buffer size.
SO_RCVLOWAT
Receive ``low water mark''.
SO_RCVTIMEO
Receive timeout.
SO_REUSEADDR
Reuse of local addresses is supported.
SO_SNDBUF
Send buffer size.
SO_SNDLOWAT
Send ``low water mark''.
SO_SNDTIMEO
Send timeout.
SO_TYPE
Socket type.

The <sys/socket.h> header shall define the following macro as the maximum backlog queue length which may be specified by the backlog field of the listen() function:

SOMAXCONN
The maximum backlog queue length.

The <sys/socket.h> header shall define the following macros, with distinct integer values, for use as the valid values for the msg_flags field in the msghdr structure, or the flags parameter in recvfrom(), recvmsg(), sendmsg(), or sendto() calls:

MSG_CTRUNC
Control data truncated.
MSG_DONTROUTE
Send without using routing tables.
MSG_EOR
Terminates a record (if supported by the protocol).
MSG_OOB
Out-of-band data.
MSG_PEEK
Leave received data in queue.
MSG_TRUNC
Normal data truncated.
MSG_WAITALL
Attempt to fill the read buffer.

The <sys/socket.h> header shall define the following macros, with distinct integer values:

AF_INET
Internet domain sockets for use with IPv4 addresses.
AF_INET6
Internet domain sockets for use with IPv6 addresses.
AF_UNIX
UNIX domain sockets.
AF_UNSPEC
Unspecified.

The <sys/socket.h> header shall define the following macros, with distinct integer values:

SHUT_RD
Disables further receive operations.
SHUT_RDWR
Disables further send and receive operations.
SHUT_WR
Disables further send operations.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int     accept(int, struct sockaddr *restrict, socklen_t *restrict);
int     bind(int, const struct sockaddr *, socklen_t);
int     connect(int, const struct sockaddr *, socklen_t);
int     getpeername(int, struct sockaddr *restrict, socklen_t *restrict);
int     getsockname(int, struct sockaddr *restrict, socklen_t *restrict);
int     getsockopt(int, int, int, void *restrict, socklen_t *restrict);
int     listen(int, int);
ssize_t recv(int, void *, size_t, int);
ssize_t recvfrom(int, void *restrict, size_t, int,
        struct sockaddr *restrict, socklen_t *restrict);
ssize_t recvmsg(int, struct msghdr *, int);
ssize_t send(int, const void *, size_t, int);
ssize_t sendmsg(int, const struct msghdr *, int);
ssize_t sendto(int, const void *, size_t, int, const struct sockaddr *,
        socklen_t);
int     setsockopt(int, int, int, const void *, socklen_t);
int     shutdown(int, int);
int     socket(int, int, int);
int     sockatmark(int);
int     socketpair(int, int, int, int[2]);

Inclusion of <sys/socket.h> may also make visible all symbols from <sys/uio.h>.

The following sections are informative.

APPLICATION USAGE

To forestall portability problems, it is recommended that applications not use values larger than 2**31 -1 for the socklen_t type.

The sockaddr_storage structure solves the problem of declaring storage for automatic variables which is both large enough and aligned enough for storing the socket address data structure of any family. For example, code with a file descriptor and without the context of the address family can pass a pointer to a variable of this type, where a pointer to a socket address structure is expected in calls such as getpeername(), and determine the address family by accessing the received content after the call.

The example below illustrates a data structure which aligns on a 64-bit boundary. An implementation-defined field _ss_align following _ss_pad1 is used to force a 64-bit alignment which covers proper alignment good enough for needs of at least sockaddr_in6 (IPv6) and sockaddr_in (IPv4) address data structures. The size of padding field _ss_pad1 depends on the chosen alignment boundary. The size of padding field _ss_pad2 depends on the value of overall size chosen for the total size of the structure. This size and alignment are represented in the above example by implementation-defined (not required) constants _SS_MAXSIZE (chosen value 128) and _SS_ALIGNMENT (with chosen value 8). Constants _SS_PAD1SIZE (derived value 6) and _SS_PAD2SIZE (derived value 112) are also for illustration and not required. The implementation-defined definitions and structure field names above start with an underscore to denote implementation private name space. Portable code is not expected to access or reference those fields or constants.

/*
 *  Desired design of maximum size and alignment.
 */
#define _SS_MAXSIZE 128
    /* Implementation-defined maximum size. */
#define _SS_ALIGNSIZE (sizeof(int64_t))
    /* Implementation-defined desired alignment. */

/*
 *  Definitions used for sockaddr_storage structure paddings design.
 */
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(sa_family_t))
#define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof(sa_family_t)+ \
                      _SS_PAD1SIZE + _SS_ALIGNSIZE))
struct sockaddr_storage {
    sa_family_t  ss_family;  /* Address family. */
/*
 *  Following fields are implementation-defined.
 */
    char _ss_pad1[_SS_PAD1SIZE];
        /* 6-byte pad; this is to make implementation-defined
           pad up to alignment field that follows explicit in
           the data structure. */
    int64_t _ss_align;  /* Field to force desired structure
                           storage alignment. */
    char _ss_pad2[_SS_PAD2SIZE];
        /* 112-byte pad to achieve desired size,
           _SS_MAXSIZE value minus size of ss_family
           __ss_pad1, __ss_align fields is 112. */
};

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/uio.h> , the System Interfaces volume of
IEEE Std 1003.1-2001, accept(), bind(), connect(),
getpeername(), getsockname(),
getsockopt(), listen(), recv(), recvfrom(),
recvmsg(), send(), sendmsg(), sendto(), setsockopt(),
shutdown(), socket(), socketpair()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dirent.h(0p)

<dirent.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dirent.h - format of directory entries

SYNOPSIS

#include <dirent.h>

DESCRIPTION

The internal format of directories is unspecified.

The <dirent.h> header shall define the following type:

DIR
A type representing a directory stream.

It shall also define the structure dirent which shall include the following members:

ino_t  d_ino       File serial number.

char   d_name[]    Name of entry.

The type ino_t shall be defined as described in <sys/types.h> .

The character array d_name is of unspecified size, but the number of bytes preceding the terminating null byte shall not exceed {NAME_MAX}.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int            closedir(DIR *);
DIR           *opendir(const char *);
struct dirent *readdir(DIR *);

int            readdir_r(DIR *restrict, struct dirent *restrict,
                   struct dirent **restrict);

void           rewinddir(DIR *);

void           seekdir(DIR *, long);
long           telldir(DIR *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

Information similar to that in the <dirent.h> header is contained in a file <sys/dir.h> in 4.2 BSD and 4.3 BSD. The equivalent in these implementations of struct dirent from this volume of IEEE Std 1003.1-2001 is struct direct. The filename was changed because the name <sys/dir.h> was also used in earlier implementations to refer to definitions related to the older access method; this produced name conflicts. The name of the structure was changed because this volume of IEEE Std 1003.1-2001 does not completely define what is in the structure, so it could be different on some implementations from struct direct.

The name of an array of char of an unspecified size should not be used as an lvalue. Use of:

sizeof(d_name)

is incorrect; use:

strlen(d_name)

instead.

The array of char d_name is not a fixed size. Implementations may need to declare struct dirent with an array size for d_name of 1, but the actual number of characters provided matches (or only slightly exceeds) the length of the filename.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, closedir(), opendir(), readdir(), readdir_r(), rewinddir(), seekdir(), telldir()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_types.h(0p)

<sys/types.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/types.h - data types

SYNOPSIS

#include <sys/types.h>

DESCRIPTION

The <sys/types.h> header shall include definitions for at least the following types:

blkcnt_t
Used for file block counts.
blksize_t
Used for block sizes.
clock_t
Used for system times in clock ticks or CLOCKS_PER_SEC; see <time.h> .
clockid_t
Used for clock ID type in the clock and timer functions.
dev_t
Used for device IDs.
fsblkcnt_t
Used for file system block counts.
fsfilcnt_t
Used for file system file counts.
gid_t
Used for group IDs.
id_t
Used as a general identifier; can be used to contain at least a pid_t, uid_t, or gid_t.
ino_t
Used for file serial numbers.
key_t
Used for XSI interprocess communication.
mode_t
Used for some file attributes.
nlink_t
Used for link counts.
off_t
Used for file sizes.
pid_t
Used for process IDs and process group IDs.
pthread_attr_t
Used to identify a thread attribute object.
pthread_barrier_t
Used to identify a barrier.
pthread_barrierattr_t
Used to define a barrier attributes object.
pthread_cond_t
Used for condition variables.
pthread_condattr_t
Used to identify a condition attribute object.
pthread_key_t
Used for thread-specific data keys.
pthread_mutex_t
Used for mutexes.
pthread_mutexattr_t
Used to identify a mutex attribute object.
pthread_once_t
Used for dynamic package initialization.
pthread_rwlock_t
Used for read-write locks.
pthread_rwlockattr_t
Used for read-write lock attributes.
pthread_spinlock_t
Used to identify a spin lock.
pthread_t
Used to identify a thread.
size_t
Used for sizes of objects.
ssize_t
Used for a count of bytes or an error indication.
suseconds_t
Used for time in microseconds.
time_t
Used for time in seconds.
timer_t
Used for timer ID returned by timer_create().
trace_attr_t
Used to identify a trace stream attributes object.
trace_event_id_t
Used to identify a trace event type.
trace_event_set_t
Used to identify a trace event type set.
trace_id_t
Used to identify a trace stream.
uid_t
Used for user IDs.
useconds_t
Used for time in microseconds.

All of the types shall be defined as arithmetic types of an appropriate length, with the following exceptions:

key_t

pthread_attr_t

pthread_barrier_t
pthread_barrierattr_t

pthread_cond_t
pthread_condattr_t
pthread_key_t
pthread_mutex_t
pthread_mutexattr_t
pthread_once_t
pthread_rwlock_t
pthread_rwlockattr_t

pthread_spinlock_t

trace_attr_t
trace_event_id_t

trace_event_set_t

trace_id_t

Additionally:

*
mode_t shall be an integer type.

*
nlink_t, uid_t, gid_t, and id_t shall be integer types.

*
blkcnt_t and off_t shall be signed integer types.

*
fsblkcnt_t, fsfilcnt_t, and ino_t shall be defined as unsigned integer types.

*
size_t shall be an unsigned integer type.

*
blksize_t, pid_t, and ssize_t shall be signed integer types.

*
time_t and clock_t shall be integer or real-floating types.

The type ssize_t shall be capable of storing values at least in the range [-1, {SSIZE_MAX}]. The type useconds_t shall be an unsigned integer type capable of storing values at least in the range [0, 1000000]. The type suseconds_t shall be a signed integer type capable of storing values at least in the range [-1, 1000000].

The implementation shall support one or more programming environments in which the widths of blksize_t, pid_t, size_t, ssize_t, suseconds_t, and useconds_t are no greater than the width of type long. The names of these programming environments can be obtained using the confstr() function or the getconf utility.

There are no defined comparison or assignment operators for the following types:

pthread_attr_t

pthread_barrier_t
pthread_barrierattr_t

pthread_cond_t
pthread_condattr_t
pthread_mutex_t
pthread_mutexattr_t
pthread_rwlock_t
pthread_rwlockattr_t

pthread_spinlock_t

trace_attr_t

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<time.h> , the System Interfaces volume of IEEE Std 1003.1-2001, confstr(), the Shell and Utilities volume of IEEE Std 1003.1-2001, getconf

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


statvfs.h(0p)

Status: 403 Forbidden statvfs.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/statvfs.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


socket.h(0p)

Status: 403 Forbidden socket.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/socket.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


stdint.h(0p)

<stdint.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stdint.h - integer types

SYNOPSIS

#include <stdint.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <stdint.h> header shall declare sets of integer types having specified widths, and shall define corresponding sets of macros. It shall also define macros that specify limits of integer types corresponding to types defined in other standard headers.

Note:
The "width" of an integer type is the number of bits used to store its value in a pure binary system; the actual type may use more bits than that (for example, a 28-bit type could be stored in 32 bits of actual storage). An N-bit signed type has values in the range -2**N-1 or 1-2**N-1 to 2**N-1-1, while an N-bit unsigned type has values in the range 0 to 2**N-1.

Types are defined in the following categories:

*
Integer types having certain exact widths

*
Integer types having at least certain specified widths

*
Fastest integer types having at least certain specified widths

*
Integer types wide enough to hold pointers to objects

*
Integer types having greatest width

(Some of these types may denote the same type.)

Corresponding macros specify limits of the declared types and construct suitable constants.

For each type described herein that the implementation provides, the <stdint.h> header shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, the <stdint.h> header shall not declare that typedef name, nor shall it define the associated macros. An implementation shall provide those types described as required, but need not provide any of the others (described as optional).

Integer Types

When typedef names differing only in the absence or presence of the initial u are defined, they shall denote corresponding signed and unsigned types as described in the ISO/IEC 9899:1999 standard, Section 6.2.5; an implementation providing one of these corresponding types shall also provide the other.

In the following descriptions, the symbol N represents an unsigned decimal integer with no leading zeros (for example, 8 or 24, but not 04 or 048).

*
Exact-width integer types

The typedef name int N _t designates a signed integer type with width N, no padding bits, and a two's-complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.

The typedef name uint N _t designates an unsigned integer type with width N. Thus, uint24_t denotes an unsigned integer type with a width of exactly 24 bits.

The following types are required:

int8_t
int16_t
int32_t
uint8_t
uint16_t
uint32_t

If an implementation provides integer types with width 64 that meet these requirements, then the following types are required: int64_t uint64_t

In particular, this will be the case if any of the following are true:

*
The implementation supports the _POSIX_V6_ILP32_OFFBIG programming environment and the application is being built in the _POSIX_V6_ILP32_OFFBIG programming environment (see the Shell and Utilities volume of IEEE Std 1003.1-2001, c99, Programming Environments).

*
The implementation supports the _POSIX_V6_LP64_OFF64 programming environment and the application is being built in the _POSIX_V6_LP64_OFF64 programming environment.

*
The implementation supports the _POSIX_V6_LPBIG_OFFBIG programming environment and the application is being built in the _POSIX_V6_LPBIG_OFFBIG programming environment.

All other types of this form are optional.

*
Minimum-width integer types

The typedef name int_least N _t designates a signed integer type with a width of at least N, such that no signed integer type with lesser size has at least the specified width. Thus, int_least32_t denotes a signed integer type with a width of at least 32 bits.

The typedef name uint_least N _t designates an unsigned integer type with a width of at least N, such that no unsigned integer type with lesser size has at least the specified width. Thus, uint_least16_t denotes an unsigned integer type with a width of at least 16 bits.

The following types are required: int_least8_t int_least16_t int_least32_t int_least64_t uint_least8_t uint_least16_t uint_least32_t uint_least64_t

All other types of this form are optional.

*
Fastest minimum-width integer types

Each of the following types designates an integer type that is usually fastest to operate with among all integer types that have at least the specified width.

The designated type is not guaranteed to be fastest for all purposes; if the implementation has no clear grounds for choosing one type over another, it will simply pick some integer type satisfying the signedness and width requirements.

The typedef name int_fast N _t designates the fastest signed integer type with a width of at least N. The typedef name uint_fast N _t designates the fastest unsigned integer type with a width of at least N.

The following types are required: int_fast8_t int_fast16_t int_fast32_t int_fast64_t uint_fast8_t uint_fast16_t uint_fast32_t uint_fast64_t

All other types of this form are optional.

*
Integer types capable of holding object pointers

The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to a pointer to void, and the result will compare equal to the original pointer: intptr_t

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to a pointer to void, and the result will compare equal to the original pointer: uintptr_t

On XSI-conformant systems, the intptr_t and uintptr_t types are required; otherwise, they are optional.

*
Greatest-width integer types

The following type designates a signed integer type capable of representing any value of any signed integer type: intmax_t

The following type designates an unsigned integer type capable of representing any value of any unsigned integer type: uintmax_t

These types are required.

Note:
Applications can test for optional types by using the corresponding limit macro from Limits of Specified-Width Integer Types .

Limits of Specified-Width Integer Types

The following macros specify the minimum and maximum limits of the types declared in the <stdint.h> header. Each macro name corresponds to a similar type name in Integer Types .

Each instance of any defined macro shall be replaced by a constant expression suitable for use in #if preprocessing directives, and this expression shall have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Its implementation-defined value shall be equal to or greater in magnitude (absolute value) than the corresponding value given below, with the same sign, except where stated to be exactly the given value.

*
Limits of exact-width integer types
*
Minimum values of exact-width signed integer types:
{INTN_MIN}
Exactly -(2 **N-1)

*
Maximum values of exact-width signed integer types:
{INTN_MAX}
Exactly 2**N-1 -1

*
Maximum values of exact-width unsigned integer types:
{UINTN_MAX}
Exactly 2 **N -1

*
Limits of minimum-width integer types
*
Minimum values of minimum-width signed integer types:
{INT_LEASTN_MIN}
-(2 ** N-1 -1)

*
Maximum values of minimum-width signed integer types:
{INT_LEASTN_MAX}
2 ** N-1 -1

*
Maximum values of minimum-width unsigned integer types:
{UINT_LEASTN_MAX}
2 ** N -1

*
Limits of fastest minimum-width integer types
*
Minimum values of fastest minimum-width signed integer types:
{INT_FASTN_MIN}
-(2 ** N-1 -1)

*
Maximum values of fastest minimum-width signed integer types:
{INT_FASTN_MAX}
2 ** N-1 -1

*
Maximum values of fastest minimum-width unsigned integer types:
{UINT_FASTN_MAX}
2 ** N -1

*
Limits of integer types capable of holding object pointers
*
Minimum value of pointer-holding signed integer type:
{INTPTR_MIN}
-(2 ** 15 -1)

*
Maximum value of pointer-holding signed integer type:
{INTPTR_MAX}
2 ** 15 -1

*
Maximum value of pointer-holding unsigned integer type:
{UINTPTR_MAX}
2 ** 16 -1

*
Limits of greatest-width integer types
*
Minimum value of greatest-width signed integer type:
{INTMAX_MIN}
-(2 ** 63 -1)

*
Maximum value of greatest-width signed integer type:
{INTMAX_MAX}
2 ** 63 -1

*
Maximum value of greatest-width unsigned integer type:
{UINTMAX_MAX}
2 ** 64 -1

Limits of Other Integer Types

The following macros specify the minimum and maximum limits of integer types corresponding to types defined in other standard headers.

Each instance of these macros shall be replaced by a constant expression suitable for use in #if preprocessing directives, and this expression shall have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Its implementation-defined value shall be equal to or greater in magnitude (absolute value) than the corresponding value given below, with the same sign.

*
Limits of ptrdiff_t:
{PTRDIFF_MIN}
-65535
{PTRDIFF_MAX}
+65535

*
Limits of sig_atomic_t:
{SIG_ATOMIC_MIN}
See below.
{SIG_ATOMIC_MAX}
See below.

*
Limit of size_t:
{SIZE_MAX}
65535

*
Limits of wchar_t:
{WCHAR_MIN}
See below.
{WCHAR_MAX}
See below.

*
Limits of wint_t:
{WINT_MIN}
See below.
{WINT_MAX}
See below.

If sig_atomic_t (see the <signal.h> header) is defined as a signed integer type, the value of {SIG_ATOMIC_MIN} shall be no greater than -127 and the value of {SIG_ATOMIC_MAX} shall be no less than 127; otherwise, sig_atomic_t shall be defined as an unsigned integer type, and the value of {SIG_ATOMIC_MIN} shall be 0 and the value of {SIG_ATOMIC_MAX} shall be no less than 255.

If wchar_t (see the <stddef.h> header) is defined as a signed integer type, the value of {WCHAR_MIN} shall be no greater than -127 and the value of {WCHAR_MAX} shall be no less than 127; otherwise, wchar_t shall be defined as an unsigned integer type, and the value of {WCHAR_MIN} shall be 0 and the value of {WCHAR_MAX} shall be no less than 255.

If wint_t (see the <wchar.h> header) is defined as a signed integer type, the value of {WINT_MIN} shall be no greater than -32767 and the value of {WINT_MAX} shall be no less than 32767; otherwise, wint_t shall be defined as an unsigned integer type, and the value of {WINT_MIN} shall be 0 and the value of {WINT_MAX} shall be no less than 65535.

Macros for Integer Constant Expressions

The following macros expand to integer constant expressions suitable for initializing objects that have integer types corresponding to types defined in the <stdint.h> header. Each macro name corresponds to a similar type name listed under Minimum-width integer types and Greatest-width integer types.

Each invocation of one of these macros shall expand to an integer constant expression suitable for use in #if preprocessing directives. The type of the expression shall have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. The value of the expression shall be that of the argument.

The argument in any instance of these macros shall be a decimal, octal, or hexadecimal constant with a value that does not exceed the limits for the corresponding type.

*
Macros for minimum-width integer constant expressions

The macro INTN_C( value) shall expand to an integer constant expression corresponding to the type int_least N _t. The macro UINTN_C( value) shall expand to an integer constant expression corresponding to the type uint_least N _t. For example, if uint_least64_t is a name for the type unsigned long long, then UINT64_C(0x123) might expand to the integer constant 0x123ULL.

*
Macros for greatest-width integer constant expressions

The following macro expands to an integer constant expression having the value specified by its argument and the type intmax_t: INTMAX_C(value)

The following macro expands to an integer constant expression having the value specified by its argument and the type uintmax_t: UINTMAX_C(value)

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

The <stdint.h> header is a subset of the <inttypes.h> header more suitable for use in freestanding environments, which might not support the formatted I/O functions. In some environments, if the formatted conversion support is not wanted, using this header instead of the <inttypes.h> header avoids defining such a large number of macros.

As a consequence of adding int8_t, the following are true:

*
A byte is exactly 8 bits.

*
{CHAR_BIT} has the value 8, {SCHAR_MAX} has the value 127, {SCHAR_MIN} has the value -127 or -128, and {UCHAR_MAX} has the value 255.

FUTURE DIRECTIONS

typedef names beginning with int or uint and ending with _t may be added to the types defined in the <stdint.h> header. Macro names beginning with INT or UINT and ending with _MAX, _MIN, or _C may be added to the macros defined in the <stdint.h> header.

SEE ALSO

<inttypes.h> , <signal.h> , <stddef.h> , <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


un.h(0p)

Status: 403 Forbidden un.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/un.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


sys_statvfs.h(0p)

<sys/statvfs.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/statvfs.h - VFS File System information structure

SYNOPSIS

#include <sys/statvfs.h>

DESCRIPTION

The <sys/statvfs.h> header shall define the statvfs structure that includes at least the following members:

unsigned long f_bsize    File system block size.
unsigned long f_frsize   Fundamental file system block size.
fsblkcnt_t    f_blocks   Total number of blocks on file system in units of f_frsize.
fsblkcnt_t    f_bfree    Total number of free blocks.
fsblkcnt_t    f_bavail   Number of free blocks available to
                         non-privileged process.
fsfilcnt_t    f_files    Total number of file serial numbers.
fsfilcnt_t    f_ffree    Total number of free file serial numbers.
fsfilcnt_t    f_favail   Number of file serial numbers available to
                         non-privileged process.
unsigned long f_fsid     File system ID.
unsigned long f_flag     Bit mask of f_flag values.
unsigned long f_namemax  Maximum filename length.

The fsblkcnt_t and fsfilcnt_t types shall be defined as described in <sys/types.h> .

The following flags for the f_flag member shall be defined:

ST_RDONLY
Read-only file system.
ST_NOSUID
Does not support the semantics of the ST_ISUID and ST_ISGID file mode bits.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int statvfs(const char *restrict, struct statvfs *restrict);
int fstatvfs(int, struct statvfs *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, fstatvfs(), statvfs()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sem.h(0p)

Status: 403 Forbidden sem.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/sem.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


pthread.h(0p)

<pthread.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread.h - threads

SYNOPSIS

#include <pthread.h>

DESCRIPTION

The <pthread.h> header shall define the following symbols:

PTHREAD_BARRIER_SERIAL_THREAD

PTHREAD_CANCEL_ASYNCHRONOUS
PTHREAD_CANCEL_ENABLE
PTHREAD_CANCEL_DEFERRED
PTHREAD_CANCEL_DISABLE
PTHREAD_CANCELED
PTHREAD_COND_INITIALIZER
PTHREAD_CREATE_DETACHED
PTHREAD_CREATE_JOINABLE
PTHREAD_EXPLICIT_SCHED
PTHREAD_INHERIT_SCHED

PTHREAD_MUTEX_DEFAULT
PTHREAD_MUTEX_ERRORCHECK

PTHREAD_MUTEX_INITIALIZER

PTHREAD_MUTEX_NORMAL
PTHREAD_MUTEX_RECURSIVE

PTHREAD_ONCE_INIT

PTHREAD_PRIO_INHERIT

PTHREAD_PRIO_NONE

PTHREAD_PRIO_PROTECT

PTHREAD_PROCESS_SHARED
PTHREAD_PROCESS_PRIVATE

PTHREAD_SCOPE_PROCESS
PTHREAD_SCOPE_SYSTEM

The following types shall be defined as described in <sys/types.h> :

pthread_attr_t

pthread_barrier_t
pthread_barrierattr_t

pthread_cond_t
pthread_condattr_t
pthread_key_t
pthread_mutex_t
pthread_mutexattr_t
pthread_once_t
pthread_rwlock_t
pthread_rwlockattr_t

pthread_spinlock_t

pthread_t

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int   pthread_atfork(void (*)(void), void (*)(void),
          void(*)(void));
int   pthread_attr_destroy(pthread_attr_t *);
int   pthread_attr_getdetachstate(const pthread_attr_t *, int *);

int   pthread_attr_getguardsize(const pthread_attr_t *restrict,
          size_t *restrict);

int   pthread_attr_getinheritsched(const pthread_attr_t *restrict,
          int *restrict);

int   pthread_attr_getschedparam(const pthread_attr_t *restrict,
          struct sched_param *restrict);

int   pthread_attr_getschedpolicy(const pthread_attr_t *restrict,
          int *restrict);

int   pthread_attr_getscope(const pthread_attr_t *restrict,
          int *restrict);

int   pthread_attr_getstack(const pthread_attr_t *restrict,
          void **restrict, size_t *restrict);

int   pthread_attr_getstackaddr(const pthread_attr_t *restrict,
          void **restrict);

int   pthread_attr_getstacksize(const pthread_attr_t *restrict,
          size_t *restrict);

int   pthread_attr_init(pthread_attr_t *);
int   pthread_attr_setdetachstate(pthread_attr_t *, int);

int   pthread_attr_setguardsize(pthread_attr_t *, size_t);

int   pthread_attr_setinheritsched(pthread_attr_t *, int);

int   pthread_attr_setschedparam(pthread_attr_t *restrict,
          const struct sched_param *restrict);

int   pthread_attr_setschedpolicy(pthread_attr_t *, int);
int   pthread_attr_setscope(pthread_attr_t *, int);

int   pthread_attr_setstack(pthread_attr_t *, void *, size_t);

int   pthread_attr_setstackaddr(pthread_attr_t *, void *);

int   pthread_attr_setstacksize(pthread_attr_t *, size_t);

int   pthread_barrier_destroy(pthread_barrier_t *);
int   pthread_barrier_init(pthread_barrier_t *restrict,
          const pthread_barrierattr_t *restrict, unsigned);
int   pthread_barrier_wait(pthread_barrier_t *);
int   pthread_barrierattr_destroy(pthread_barrierattr_t *);

int   pthread_barrierattr_getpshared(
          const pthread_barrierattr_t *restrict, int *restrict);

int   pthread_barrierattr_init(pthread_barrierattr_t *);

int   pthread_barrierattr_setpshared(pthread_barrierattr_t *, int);

int   pthread_cancel(pthread_t);
void  pthread_cleanup_push(void (*)(void *), void *);
void  pthread_cleanup_pop(int);
int   pthread_cond_broadcast(pthread_cond_t *);
int   pthread_cond_destroy(pthread_cond_t *);
int   pthread_cond_init(pthread_cond_t *restrict,
          const pthread_condattr_t *restrict);
int   pthread_cond_signal(pthread_cond_t *);
int   pthread_cond_timedwait(pthread_cond_t *restrict,
          pthread_mutex_t *restrict, const struct timespec *restrict);
int   pthread_cond_wait(pthread_cond_t *restrict,
          pthread_mutex_t *restrict);
int   pthread_condattr_destroy(pthread_condattr_t *);

int   pthread_condattr_getclock(const pthread_condattr_t *restrict,
          clockid_t *restrict);

int   pthread_condattr_getpshared(const pthread_condattr_t *restrict,
          int *restrict);

int   pthread_condattr_init(pthread_condattr_t *);

int   pthread_condattr_setclock(pthread_condattr_t *, clockid_t);

int   pthread_condattr_setpshared(pthread_condattr_t *, int);

int   pthread_create(pthread_t *restrict, const pthread_attr_t *restrict,
          void *(*)(void *), void *restrict);
int   pthread_detach(pthread_t);
int   pthread_equal(pthread_t, pthread_t);
void  pthread_exit(void *);

int   pthread_getconcurrency(void);

int   pthread_getcpuclockid(pthread_t, clockid_t *);

int   pthread_getschedparam(pthread_t, int *restrict,
          struct sched_param *restrict);

void *pthread_getspecific(pthread_key_t);
int   pthread_join(pthread_t, void **);
int   pthread_key_create(pthread_key_t *, void (*)(void *));
int   pthread_key_delete(pthread_key_t);
int   pthread_mutex_destroy(pthread_mutex_t *);

int   pthread_mutex_getprioceiling(const pthread_mutex_t *restrict,
          int *restrict);

int   pthread_mutex_init(pthread_mutex_t *restrict,
          const pthread_mutexattr_t *restrict);
int   pthread_mutex_lock(pthread_mutex_t *);

int   pthread_mutex_setprioceiling(pthread_mutex_t *restrict, int,
          int *restrict);

int   pthread_mutex_timedlock(pthread_mutex_t *,
          const struct timespec *);

int   pthread_mutex_trylock(pthread_mutex_t *);
int   pthread_mutex_unlock(pthread_mutex_t *);
int   pthread_mutexattr_destroy(pthread_mutexattr_t *);

int   pthread_mutexattr_getprioceiling(
          const pthread_mutexattr_t *restrict, int *restrict);

int   pthread_mutexattr_getprotocol(const pthread_mutexattr_t *restrict,
          int *restrict);

int   pthread_mutexattr_getpshared(const pthread_mutexattr_t *restrict,
          int *restrict);

int   pthread_mutexattr_gettype(const pthread_mutexattr_t *restrict,
          int *restrict);

int   pthread_mutexattr_init(pthread_mutexattr_t *);

int   pthread_mutexattr_setprioceiling(pthread_mutexattr_t *, int);

int   pthread_mutexattr_setprotocol(pthread_mutexattr_t *, int);

int   pthread_mutexattr_setpshared(pthread_mutexattr_t *, int);

int   pthread_mutexattr_settype(pthread_mutexattr_t *, int);

int   pthread_once(pthread_once_t *, void (*)(void));
int   pthread_rwlock_destroy(pthread_rwlock_t *);
int   pthread_rwlock_init(pthread_rwlock_t *restrict,
          const pthread_rwlockattr_t *restrict);
int   pthread_rwlock_rdlock(pthread_rwlock_t *);

int   pthread_rwlock_timedrdlock(pthread_rwlock_t *restrict,
          const struct timespec *restrict);
int   pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict,
          const struct timespec *restrict);

int   pthread_rwlock_tryrdlock(pthread_rwlock_t *);
int   pthread_rwlock_trywrlock(pthread_rwlock_t *);
int   pthread_rwlock_unlock(pthread_rwlock_t *);
int   pthread_rwlock_wrlock(pthread_rwlock_t *);
int   pthread_rwlockattr_destroy(pthread_rwlockattr_t *);

int   pthread_rwlockattr_getpshared(
          const pthread_rwlockattr_t *restrict, int *restrict);

int   pthread_rwlockattr_init(pthread_rwlockattr_t *);

int   pthread_rwlockattr_setpshared(pthread_rwlockattr_t *, int);

pthread_t
      pthread_self(void);
int   pthread_setcancelstate(int, int *);
int   pthread_setcanceltype(int, int *);

int   pthread_setconcurrency(int);

int   pthread_setschedparam(pthread_t, int,
          const struct sched_param *);

int   pthread_setschedprio(pthread_t, int);

int   pthread_setspecific(pthread_key_t, const void *);

int   pthread_spin_destroy(pthread_spinlock_t *);
int   pthread_spin_init(pthread_spinlock_t *, int);
int   pthread_spin_lock(pthread_spinlock_t *);
int   pthread_spin_trylock(pthread_spinlock_t *);
int   pthread_spin_unlock(pthread_spinlock_t *);

void  pthread_testcancel(void);

Inclusion of the <pthread.h> header shall make symbols defined in the headers <sched.h> and <time.h> visible.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sched.h> , <sys/types.h> , <time.h> , the System
Interfaces volume of IEEE Std 1003.1-2001, pthread_attr_getguardsize(),
pthread_attr_init(), pthread_attr_setscope(), pthread_barrier_destroy(),
pthread_barrier_init(), pthread_barrier_wait(), pthread_barrierattr_destroy(),
pthread_barrierattr_getpshared(), pthread_barrierattr_init(),
pthread_barrierattr_setpshared(), pthread_cancel(), pthread_cleanup_pop(),
pthread_cond_init(), pthread_cond_signal(), pthread_cond_wait(),
pthread_condattr_getclock(), pthread_condattr_init(),
pthread_condattr_setclock(), pthread_create(), pthread_detach(),
pthread_equal(), pthread_exit(),
pthread_getconcurrency(), pthread_getcpuclockid(), pthread_getschedparam(),
pthread_join(), pthread_key_create(), pthread_key_delete(),
pthread_mutex_init(), pthread_mutex_lock(), pthread_mutex_setprioceiling(),
pthread_mutex_timedlock(), pthread_mutexattr_init(), pthread_mutexattr_gettype(),
pthread_mutexattr_setprotocol(), pthread_once(), pthread_rwlock_destroy(),
pthread_rwlock_init(), pthread_rwlock_rdlock(), pthread_rwlock_timedrdlock(),
pthread_rwlock_timedwrlock(), pthread_rwlock_tryrdlock(),
pthread_rwlock_trywrlock(), pthread_rwlock_unlock(), pthread_rwlock_wrlock(),
pthread_rwlockattr_destroy(), pthread_rwlockattr_getpshared(),
pthread_rwlockattr_init(), pthread_rwlockattr_setpshared(),
pthread_self(), pthread_setcancelstate(), pthread_setspecific(),
pthread_spin_destroy(), pthread_spin_init(), pthread_spin_lock(),
pthread_spin_trylock(), pthread_spin_unlock()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


times.h(0p)

Status: 403 Forbidden times.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/times.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


sys_sem.h(0p)

<sys/sem.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/sem.h - XSI semaphore facility

SYNOPSIS

#include <sys/sem.h>

DESCRIPTION

The <sys/sem.h> header shall define the following constants and structures.

Semaphore operation flags:

SEM_UNDO
Set up adjust on exit entry.

Command definitions for the semctl() function shall be provided as follows:

GETNCNT
Get semncnt.
GETPID
Get sempid.
GETVAL
Get semval.
GETALL
Get all cases of semval.
GETZCNT
Get semzcnt.
SETVAL
Set semval.
SETALL
Set all cases of semval.

The semid_ds structure shall contain the following members:

struct ipc_perm  sem_perm  Operation permission structure.
unsigned short   sem_nsems Number of semaphores in set.
time_t           sem_otime Last semop
 () time.
time_t           sem_ctime Last time changed by semctl
 ().

The pid_t, time_t, key_t, and size_t types shall be defined as described in <sys/types.h> .

A semaphore shall be represented by an anonymous structure containing the following members:

unsigned short  semval   Semaphore value.
pid_t           sempid   Process ID of last operation.
unsigned short  semncnt  Number of processes waiting for semval
                         to become greater than current value.
unsigned short  semzcnt  Number of processes waiting for semval
                         to become 0.

The sembuf structure shall contain the following members:

unsigned short  sem_num   Semaphore number.
short           sem_op    Semaphore operation.
short           sem_flg   Operation flags.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int   semctl(int, int, int, ...);
int   semget(key_t, int, int);
int   semop(int, struct sembuf *, size_t);

In addition, all of the symbols from <sys/ipc.h> shall be defined when this header is included.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/ipc.h> , <sys/types.h> , semctl(), semget(), semop()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fnmatch.h(0p)

<fnmatch.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fnmatch.h - filename-matching types

SYNOPSIS

#include <fnmatch.h>

DESCRIPTION

The <fnmatch.h> header shall define the following constants:

FNM_NOMATCH
The string does not match the specified pattern.
FNM_PATHNAME
Slash in string only matches slash in pattern.
FNM_PERIOD
Leading period in string must be exactly matched by period in pattern.
FNM_NOESCAPE
Disable backslash escaping.
FNM_NOSYS
Reserved.

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

int fnmatch(const char *, const char *, int);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, fnmatch(), the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tar.h(0p)

<tar.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tar.h - extended tar definitions

SYNOPSIS

#include <tar.h>

DESCRIPTION

The <tar.h> header shall define header block definitions as follows.

General definitions:
Name | Description | Value
TMAGIC | "ustar" | ustar plus null byte.
TMAGLEN | 6 | Length of the above.
TVERSION | "00" | 00 without a null byte.
TVERSLEN | 2 | Length of the above.

Typeflag field definitions:
Name | Description | Value
REGTYPE | '0' | Regular file.
AREGTYPE | '\0' | Regular file.
LNKTYPE | '1' | Link.
SYMTYPE | '2' | Symbolic link.
CHRTYPE | '3' | Character special.
BLKTYPE | '4' | Block special.
DIRTYPE | '5' | Directory.
FIFOTYPE | '6' | FIFO special.
CONTTYPE | '7' | Reserved.

Mode field bit definitions (octal):
Name | Description | Value
TSUID | 04000 | Set UID on execution.
TSGID | 02000 | Set GID on execution.
TSVTX | 01000 | On directories, restricted deletion flag.
TUREAD | 00400 | Read by owner.
TUWRITE | 00200 | Write by owner special.
TUEXEC | 00100 | Execute/search by owner.
TGREAD | 00040 | Read by group.
TGWRITE | 00020 | Write by group.
TGEXEC | 00010 | Execute/search by group.
TOREAD | 00004 | Read by other.
TOWRITE | 00002 | Write by other.
TOEXEC | 00001 | Execute/search by other.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Shell and Utilities volume of IEEE Std 1003.1-2001, pax

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wait.h(0p)

Status: 403 Forbidden wait.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/wait.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


netdb.h(0p)

<netdb.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

netdb.h - definitions for network database operations

SYNOPSIS

#include <netdb.h>

DESCRIPTION

The <netdb.h> header may define the in_port_t type and the in_addr_t type as described in <netinet/in.h> .

The <netdb.h> header shall define the hostent structure that includes at least the following members:

char   *h_name       Official name of the host.
char  **h_aliases    A pointer to an array of pointers to
                     alternative host names, terminated by a
                     null pointer.
int     h_addrtype   Address type.
int     h_length     The length, in bytes, of the address.
char  **h_addr_list  A pointer to an array of pointers to network
                     addresses (in network byte order) for the host,
                     terminated by a null pointer.

The <netdb.h> header shall define the netent structure that includes at least the following members:

char     *n_name      Official, fully-qualified (including the
                      domain) name of the host.
char    **n_aliases   A pointer to an array of pointers to
                      alternative network names, terminated by a
                      null pointer.
int       n_addrtype  The address type of the network.
uint32_t  n_net       The network number, in host byte order.

The uint32_t type shall be defined as described in <inttypes.h> .

The <netdb.h> header shall define the protoent structure that includes at least the following members:

char   *p_name     Official name of the protocol.
char  **p_aliases  A pointer to an array of pointers to
                   alternative protocol names, terminated by
                   a null pointer.
int     p_proto    The protocol number.

The <netdb.h> header shall define the servent structure that includes at least the following members:

char   *s_name     Official name of the service.
char  **s_aliases  A pointer to an array of pointers to
                   alternative service names, terminated by
                   a null pointer.
int     s_port     The port number at which the service
                   resides, in network byte order.
char   *s_proto    The name of the protocol to use when
                   contacting the service.

The <netdb.h> header shall define the IPPORT_RESERVED macro with the value of the highest reserved Internet port number.

When the <netdb.h> header is included, h_errno shall be available as a modifiable lvalue of type int. It is unspecified whether h_errno is a macro or an identifier declared with external linkage.

The <netdb.h> header shall define the following macros for use as error values for gethostbyaddr() and gethostbyname():

HOST_NOT_FOUND
NO_DATA
NO_RECOVERY
TRY_AGAIN

Address Information Structure

The <netdb.h> header shall define the addrinfo structure that includes at least the following members:

int               ai_flags      Input flags.
int               ai_family     Address family of socket.
int               ai_socktype   Socket type.
int               ai_protocol   Protocol of socket.
socklen_t         ai_addrlen    Length of socket address.
struct sockaddr  *ai_addr       Socket address of socket.
char             *ai_canonname  Canonical name of service location.
struct addrinfo  *ai_next       Pointer to next in list.

The <netdb.h> header shall define the following macros that evaluate to bitwise-distinct integer constants for use in the flags field of the addrinfo structure:

AI_PASSIVE
Socket address is intended for bind().
AI_CANONNAME

Request for canonical name.

AI_NUMERICHOST

Return numeric host address as name.

AI_NUMERICSERV

Inhibit service name resolution.

AI_V4MAPPED
If no IPv6 addresses are found, query for IPv4 addresses and return them to the caller as IPv4-mapped IPv6 addresses.
AI_ALL
Query for both IPv4 and IPv6 addresses.
AI_ADDRCONFIG

Query for IPv4 addresses only when an IPv4 address is configured; query for IPv6 addresses only when an IPv6 address is configured.

The <netdb.h> header shall define the following macros that evaluate to bitwise-distinct integer constants for use in the flags argument to getnameinfo():

NI_NOFQDN
Only the nodename portion of the FQDN is returned for local hosts.
NI_NUMERICHOST

The numeric form of the node's address is returned instead of its name.

NI_NAMEREQD
Return an error if the node's name cannot be located in the database.
NI_NUMERICSERV

The numeric form of the service address is returned instead of its name.

NI_NUMERICSCOPE

For IPv6 addresses, the numeric form of the scope identifier is returned instead of its name.

NI_DGRAM
Indicates that the service is a datagram service (SOCK_DGRAM).

Address Information Errors

The <netdb.h> header shall define the following macros for use as error values for getaddrinfo() and getnameinfo():

EAI_AGAIN
The name could not be resolved at this time. Future attempts may succeed.
EAI_BADFLAGS
The flags had an invalid value.
EAI_FAIL
A non-recoverable error occurred.
EAI_FAMILY
The address family was not recognized or the address length was invalid for the specified family.
EAI_MEMORY
There was a memory allocation failure.
EAI_NONAME
The name does not resolve for the supplied parameters.

NI_NAMEREQD is set and the host's name cannot be located, or both nodename and servname were null.

EAI_SERVICE
The service passed was not recognized for the specified socket type.
EAI_SOCKTYPE
The intended socket type was not recognized.
EAI_SYSTEM
A system error occurred. The error code can be found in errno.
EAI_OVERFLOW

An argument buffer overflowed.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void              endhostent(void);
void              endnetent(void);
void              endprotoent(void);
void              endservent(void);
void              freeaddrinfo(struct addrinfo *);
const char       *gai_strerror(int);
int               getaddrinfo(const char *restrict, const char *restrict,
                      const struct addrinfo *restrict,
                      struct addrinfo **restrict);
struct hostent   *gethostbyaddr(const void *, socklen_t, int);
struct hostent   *gethostbyname(const char *);
struct hostent   *gethostent(void);
int               getnameinfo(const struct sockaddr *restrict, socklen_t,
                      char *restrict, socklen_t, char *restrict,
                      socklen_t, int);
struct netent    *getnetbyaddr(uint32_t, int);
struct netent    *getnetbyname(const char *);
struct netent    *getnetent(void);
struct protoent  *getprotobyname(const char *);
struct protoent  *getprotobynumber(int);
struct protoent  *getprotoent(void);
struct servent   *getservbyname(const char *, const char *);
struct servent   *getservbyport(int, const char *);
struct servent   *getservent(void);
void              sethostent(int);
void              setnetent(int);
void              setprotoent(int);
void              setservent(int);

The type socklen_t shall be defined through typedef as described in <sys/socket.h>.

Inclusion of the <netdb.h> header may also make visible all symbols from <netinet/in.h>, <sys/socket.h>, and <inttypes.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<netinet/in.h> , <inttypes.h> , <sys/socket.h> , the System Interfaces volume of IEEE Std 1003.1-2001, bind(), endhostent(), endnetent(), endprotoent(), endservent(), getaddrinfo(), getnameinfo()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


limits.h(0p)

<limits.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

limits.h - implementation-defined constants

SYNOPSIS

#include <limits.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

Many of the symbols listed here are not defined by the ISO/IEC 9899:1999 standard. Such symbols are not shown as CX shaded.

The <limits.h> header shall define various symbolic names. Different categories of names are described below.

The names represent various limits on resources that the implementation imposes on applications.

Implementations may choose any appropriate value for each limit, provided it is not more restrictive than the Minimum Acceptable Values listed below. Symbolic constant names beginning with _POSIX may be found in <unistd.h> .

Applications should not assume any particular value for a limit. To achieve maximum portability, an application should not require more resource than the Minimum Acceptable Value quantity. However, an application wishing to avail itself of the full amount of a resource available on an implementation may make use of the value given in <limits.h> on that particular implementation, by using the symbolic names listed below. It should be noted, however, that many of the listed limits are not invariant, and at runtime, the value of the limit may differ from those given in this header, for the following reasons:

*
The limit is pathname-dependent.

*
The limit differs between the compile and runtime machines.

For these reasons, an application may use the fpathconf(), pathconf(), and sysconf() functions to determine the actual value of a limit at runtime.

The items in the list ending in _MIN give the most negative values that the mathematical types are guaranteed to be capable of representing. Numbers of a more negative value may be supported on some implementations, as indicated by the <limits.h> header on the implementation, but applications requiring such numbers are not guaranteed to be portable to all implementations. For positive constants ending in _MIN, this indicates the minimum acceptable value.

Runtime Invariant Values (Possibly Indeterminate)

A definition of one of the symbolic names in the following list shall be omitted from <limits.h> on specific implementations where the corresponding value is equal to or greater than the stated minimum, but is unspecified.

This indetermination might depend on the amount of available memory space on a specific instance of a specific implementation. The actual value supported by a specific instance shall be provided by the sysconf() function.

{AIO_LISTIO_MAX}

Maximum number of I/O operations in a single list I/O call supported by the implementation.
Minimum Acceptable Value: {_POSIX_AIO_LISTIO_MAX}

{AIO_MAX}

Maximum number of outstanding asynchronous I/O operations supported by the implementation.
Minimum Acceptable Value: {_POSIX_AIO_MAX}

{AIO_PRIO_DELTA_MAX}

The maximum amount by which a process can decrease its asynchronous I/O priority level from its own scheduling priority.
Minimum Acceptable Value: 0

{ARG_MAX}
Maximum length of argument to the exec functions including environment data.
Minimum Acceptable Value: {_POSIX_ARG_MAX}
{ATEXIT_MAX}

Maximum number of functions that may be registered with atexit().
Minimum Acceptable Value: 32

{CHILD_MAX}
Maximum number of simultaneous processes per real user ID.
Minimum Acceptable Value: {_POSIX_CHILD_MAX}
{DELAYTIMER_MAX}

Maximum number of timer expiration overruns.
Minimum Acceptable Value: {_POSIX_DELAYTIMER_MAX}

{HOST_NAME_MAX}
Maximum length of a host name (not including the terminating null) as returned from the gethostname() function.
Minimum Acceptable Value: {_POSIX_HOST_NAME_MAX}
{IOV_MAX}

Maximum number of iovec structures that one process has available for use with readv() or writev().
Minimum Acceptable Value: {_XOPEN_IOV_MAX}

{LOGIN_NAME_MAX}
Maximum length of a login name.
Minimum Acceptable Value: {_POSIX_LOGIN_NAME_MAX}
{MQ_OPEN_MAX}

The maximum number of open message queue descriptors a process may hold.
Minimum Acceptable Value: {_POSIX_MQ_OPEN_MAX}

{MQ_PRIO_MAX}

The maximum number of message priorities supported by the implementation.
Minimum Acceptable Value: {_POSIX_MQ_PRIO_MAX}

{OPEN_MAX}
Maximum number of files that one process can have open at any one time.
Minimum Acceptable Value: {_POSIX_OPEN_MAX}
{PAGESIZE}
Size in bytes of a page.
Minimum Acceptable Value: 1
{PAGE_SIZE}

Equivalent to {PAGESIZE}. If either {PAGESIZE} or {PAGE_SIZE} is defined, the other is defined with the same value.

{PTHREAD_DESTRUCTOR_ITERATIONS}

Maximum number of attempts made to destroy a thread's thread-specific data values on thread exit.
Minimum Acceptable Value: {_POSIX_THREAD_DESTRUCTOR_ITERATIONS}

{PTHREAD_KEYS_MAX}

Maximum number of data keys that can be created by a process.
Minimum Acceptable Value: {_POSIX_THREAD_KEYS_MAX}

{PTHREAD_STACK_MIN}

Minimum size in bytes of thread stack storage.
Minimum Acceptable Value: 0

{PTHREAD_THREADS_MAX}

Maximum number of threads that can be created per process.
Minimum Acceptable Value: {_POSIX_THREAD_THREADS_MAX}

{RE_DUP_MAX}
The number of repeated occurrences of a BRE permitted by the regexec() and regcomp() functions when using the interval notation {\(m,n\}; see BREs Matching Multiple Characters .
Minimum Acceptable Value: {_POSIX2_RE_DUP_MAX}
{RTSIG_MAX}

Maximum number of realtime signals reserved for application use in this implementation.
Minimum Acceptable Value: {_POSIX_RTSIG_MAX}

{SEM_NSEMS_MAX}

Maximum number of semaphores that a process may have.
Minimum Acceptable Value: {_POSIX_SEM_NSEMS_MAX}

{SEM_VALUE_MAX}

The maximum value a semaphore may have.
Minimum Acceptable Value: {_POSIX_SEM_VALUE_MAX}

{SIGQUEUE_MAX}

Maximum number of queued signals that a process may send and have pending at the receiver(s) at any time.
Minimum Acceptable Value: {_POSIX_SIGQUEUE_MAX}

{SS_REPL_MAX}

The maximum number of replenishment operations that may be simultaneously pending for a particular sporadic server scheduler.
Minimum Acceptable Value: {_POSIX_SS_REPL_MAX}

{STREAM_MAX}
The number of streams that one process can have open at one time. If defined, it has the same value as {FOPEN_MAX} (see <stdio.h> ).
Minimum Acceptable Value: {_POSIX_STREAM_MAX}
{SYMLOOP_MAX}
Maximum number of symbolic links that can be reliably traversed in the resolution of a pathname in the absence of a loop.
Minimum Acceptable Value: {_POSIX_SYMLOOP_MAX}
{TIMER_MAX}

Maximum number of timers per process supported by the implementation.
Minimum Acceptable Value: {_POSIX_TIMER_MAX}

{TRACE_EVENT_NAME_MAX}

Maximum length of the trace event name.
Minimum Acceptable Value: {_POSIX_TRACE_EVENT_NAME_MAX}

{TRACE_NAME_MAX}

Maximum length of the trace generation version string or of the trace stream name.
Minimum Acceptable Value: {_POSIX_TRACE_NAME_MAX}

{TRACE_SYS_MAX}

Maximum number of trace streams that may simultaneously exist in the system.
Minimum Acceptable Value: {_POSIX_TRACE_SYS_MAX}

{TRACE_USER_EVENT_MAX}

Maximum number of user trace event type identifiers that may simultaneously exist in a traced process, including the predefined user trace event POSIX_TRACE_UNNAMED_USER_EVENT.
Minimum Acceptable Value: {_POSIX_TRACE_USER_EVENT_MAX}

{TTY_NAME_MAX}
Maximum length of terminal device name.
Minimum Acceptable Value: {_POSIX_TTY_NAME_MAX}
{TZNAME_MAX}
Maximum number of bytes supported for the name of a timezone (not of the TZ variable).
Minimum Acceptable Value: {_POSIX_TZNAME_MAX}

Note:
The length given by {TZNAME_MAX} does not include the quoting characters mentioned in Other Environment Variables .

Pathname Variable Values

The values in the following list may be constants within an implementation or may vary from one pathname to another. For example, file systems or directories may have different characteristics.

A definition of one of the values shall be omitted from the <limits.h> header on specific implementations where the corresponding value is equal to or greater than the stated minimum, but where the value can vary depending on the file to which it is applied. The actual value supported for a specific pathname shall be provided by the pathconf() function.

{FILESIZEBITS}
Minimum number of bits needed to represent, as a signed integer value, the maximum size of a regular file allowed in the specified directory.
Minimum Acceptable Value: 32
{LINK_MAX}
Maximum number of links to a single file.
Minimum Acceptable Value: {_POSIX_LINK_MAX}
{MAX_CANON}
Maximum number of bytes in a terminal canonical input line.
Minimum Acceptable Value: {_POSIX_MAX_CANON}
{MAX_INPUT}
Minimum number of bytes for which space is available in a terminal input queue; therefore, the maximum number of bytes a conforming application may require to be typed as input before reading them.
Minimum Acceptable Value: {_POSIX_MAX_INPUT}
{NAME_MAX}
Maximum number of bytes in a filename (not including terminating null).
Minimum Acceptable Value: {_POSIX_NAME_MAX}
Minimum Acceptable Value: {_XOPEN_NAME_MAX}
{PATH_MAX}
Maximum number of bytes in a pathname, including the terminating null character.
Minimum Acceptable Value: {_POSIX_PATH_MAX}
Minimum Acceptable Value: {_XOPEN_PATH_MAX}
{PIPE_BUF}
Maximum number of bytes that is guaranteed to be atomic when writing to a pipe.
Minimum Acceptable Value: {_POSIX_PIPE_BUF}
{POSIX_ALLOC_SIZE_MIN}

Minimum number of bytes of storage actually allocated for any portion of a file.
Minimum Acceptable Value: Not specified.

{POSIX_REC_INCR_XFER_SIZE}

Recommended increment for file transfer sizes between the {POSIX_REC_MIN_XFER_SIZE} and {POSIX_REC_MAX_XFER_SIZE} values.
Minimum Acceptable Value: Not specified.

{POSIX_REC_MAX_XFER_SIZE}

Maximum recommended file transfer size.
Minimum Acceptable Value: Not specified.

{POSIX_REC_MIN_XFER_SIZE}

Minimum recommended file transfer size.
Minimum Acceptable Value: Not specified.

{POSIX_REC_XFER_ALIGN}

Recommended file transfer buffer alignment.
Minimum Acceptable Value: Not specified.

{SYMLINK_MAX}
Maximum number of bytes in a symbolic link.
Minimum Acceptable Value: {_POSIX_SYMLINK_MAX}

Runtime Increasable Values

The magnitude limitations in the following list shall be fixed by specific implementations. An application should assume that the value supplied by <limits.h> in a specific implementation is the minimum that pertains whenever the application is run under that implementation. A specific instance of a specific implementation may increase the value relative to that supplied by <limits.h> for that implementation. The actual value supported by a specific instance shall be provided by the sysconf() function.

{BC_BASE_MAX}
Maximum obase values allowed by the bc utility.
Minimum Acceptable Value: {_POSIX2_BC_BASE_MAX}
{BC_DIM_MAX}
Maximum number of elements permitted in an array by the bc utility.
Minimum Acceptable Value: {_POSIX2_BC_DIM_MAX}
{BC_SCALE_MAX}
Maximum scale value allowed by the bc utility.
Minimum Acceptable Value: {_POSIX2_BC_SCALE_MAX}
{BC_STRING_MAX}
Maximum length of a string constant accepted by the bc utility.
Minimum Acceptable Value: {_POSIX2_BC_STRING_MAX}
{CHARCLASS_NAME_MAX}
Maximum number of bytes in a character class name.
Minimum Acceptable Value: {_POSIX2_CHARCLASS_NAME_MAX}
{COLL_WEIGHTS_MAX}
Maximum number of weights that can be assigned to an entry of the LC_COLLATE order keyword in the locale definition file; see Locale .
Minimum Acceptable Value: {_POSIX2_COLL_WEIGHTS_MAX}
{EXPR_NEST_MAX}
Maximum number of expressions that can be nested within parentheses by the expr utility.
Minimum Acceptable Value: {_POSIX2_EXPR_NEST_MAX}
{LINE_MAX}
Unless otherwise noted, the maximum length, in bytes, of a utility's input line (either standard input or another file), when the utility is described as processing text files. The length includes room for the trailing <newline>.
Minimum Acceptable Value: {_POSIX2_LINE_MAX}
{NGROUPS_MAX}
Maximum number of simultaneous supplementary group IDs per process.
Minimum Acceptable Value: {_POSIX_NGROUPS_MAX}
{RE_DUP_MAX}
Maximum number of repeated occurrences of a regular expression permitted when using the interval notation \{m,n\}; see Regular Expressions .
Minimum Acceptable Value: {_POSIX2_RE_DUP_MAX}

Maximum Values

The symbolic constants in the following list shall be defined in <limits.h> with the values shown. These are symbolic names for the most restrictive value for certain features on an implementation supporting the Timers option. A conforming implementation shall provide values no larger than these values. A conforming application must not require a smaller value for correct operation.

{_POSIX_CLOCKRES_MIN}

The resolution of the CLOCK_REALTIME clock, in nanoseconds.
Value: 20 000 000

If the Monotonic Clock option is supported, the resolution of the CLOCK_MONOTONIC clock, in nanoseconds, is represented by {_POSIX_CLOCKRES_MIN}.

Minimum Values

The symbolic constants in the following list shall be defined in <limits.h> with the values shown. These are symbolic names for the most restrictive value for certain features on an implementation conforming to this volume of IEEE Std 1003.1-2001. Related symbolic constants are defined elsewhere in this volume of IEEE Std 1003.1-2001 which reflect the actual implementation and which need not be as restrictive. A conforming implementation shall provide values at least this large. A strictly conforming application must not require a larger value for correct operation.

{_POSIX_AIO_LISTIO_MAX}

The number of I/O operations that can be specified in a list I/O call.
Value: 2

{_POSIX_AIO_MAX}

The number of outstanding asynchronous I/O operations.
Value: 1

{_POSIX_ARG_MAX}
Maximum length of argument to the exec functions including environment data.
Value: 4 096
{_POSIX_CHILD_MAX}
Maximum number of simultaneous processes per real user ID.
Value: 25
{_POSIX_DELAYTIMER_MAX}

The number of timer expiration overruns.
Value: 32

{_POSIX_HOST_NAME_MAX}
Maximum length of a host name (not including the terminating null) as returned from the gethostname() function.
Value: 255
{_POSIX_LINK_MAX}
Maximum number of links to a single file.
Value: 8
{_POSIX_LOGIN_NAME_MAX}
The size of the storage required for a login name, in bytes, including the terminating null.
Value: 9
{_POSIX_MAX_CANON}
Maximum number of bytes in a terminal canonical input queue.
Value: 255
{_POSIX_MAX_INPUT}
Maximum number of bytes allowed in a terminal input queue.
Value: 255
{_POSIX_MQ_OPEN_MAX}

The number of message queues that can be open for a single process.
Value: 8

{_POSIX_MQ_PRIO_MAX}

The maximum number of message priorities supported by the implementation.
Value: 32

{_POSIX_NAME_MAX}
Maximum number of bytes in a filename (not including terminating null).
Value: 14
{_POSIX_NGROUPS_MAX}
Maximum number of simultaneous supplementary group IDs per process.
Value: 8
{_POSIX_OPEN_MAX}
Maximum number of files that one process can have open at any one time.
Value: 20
{_POSIX_PATH_MAX}
Maximum number of bytes in a pathname.
Value: 256
{_POSIX_PIPE_BUF}
Maximum number of bytes that is guaranteed to be atomic when writing to a pipe.
Value: 512
{_POSIX_RE_DUP_MAX}
The number of repeated occurrences of a BRE permitted by the regexec() and regcomp() functions when using the interval notation {\(m,n\}; see BREs Matching Multiple Characters .
Value: 255
{_POSIX_RTSIG_MAX}

The number of realtime signal numbers reserved for application use.
Value: 8

{_POSIX_SEM_NSEMS_MAX}

The number of semaphores that a process may have.
Value: 256

{_POSIX_SEM_VALUE_MAX}

The maximum value a semaphore may have.
Value: 32 767

{_POSIX_SIGQUEUE_MAX}

The number of queued signals that a process may send and have pending at the receiver(s) at any time.
Value: 32

{_POSIX_SSIZE_MAX}
The value that can be stored in an object of type ssize_t.
Value: 32 767
{_POSIX_STREAM_MAX}
The number of streams that one process can have open at one time.
Value: 8
{_POSIX_SS_REPL_MAX}

The number of replenishment operations that may be simultaneously pending for a particular sporadic server scheduler.
Value: 4

{_POSIX_SYMLINK_MAX}
The number of bytes in a symbolic link.
Value: 255
{_POSIX_SYMLOOP_MAX}
The number of symbolic links that can be traversed in the resolution of a pathname in the absence of a loop.
Value: 8
{_POSIX_THREAD_DESTRUCTOR_ITERATIONS}

The number of attempts made to destroy a thread's thread-specific data values on thread exit.
Value: 4

{_POSIX_THREAD_KEYS_MAX}

The number of data keys per process.
Value: 128

{_POSIX_THREAD_THREADS_MAX}

The number of threads per process.
Value: 64

{_POSIX_TIMER_MAX}

The per-process number of timers.
Value: 32

{_POSIX_TRACE_EVENT_NAME_MAX}

The length in bytes of a trace event name.
Value: 30

{_POSIX_TRACE_NAME_MAX}

The length in bytes of a trace generation version string or a trace stream name.
Value: 8

{_POSIX_TRACE_SYS_MAX}

The number of trace streams that may simultaneously exist in the system.
Value: 8

{_POSIX_TRACE_USER_EVENT_MAX}

The number of user trace event type identifiers that may simultaneously exist in a traced process, including the predefined user trace event POSIX_TRACE_UNNAMED_USER_EVENT.
Value: 32

{_POSIX_TTY_NAME_MAX}
The size of the storage required for a terminal device name, in bytes, including the terminating null.
Value: 9
{_POSIX_TZNAME_MAX}
Maximum number of bytes supported for the name of a timezone (not of the TZ variable).
Value: 6
Note:
The length given by {_POSIX_TZNAME_MAX} does not include the quoting characters mentioned in Other Environment Variables .

{_POSIX2_BC_BASE_MAX}
Maximum obase values allowed by the bc utility.
Value: 99
{_POSIX2_BC_DIM_MAX}
Maximum number of elements permitted in an array by the bc utility.
Value: 2 048
{_POSIX2_BC_SCALE_MAX}
Maximum scale value allowed by the bc utility.
Value: 99
{_POSIX2_BC_STRING_MAX}
Maximum length of a string constant accepted by the bc utility.
Value: 1 000
{_POSIX2_CHARCLASS_NAME_MAX}
Maximum number of bytes in a character class name.
Value: 14
{_POSIX2_COLL_WEIGHTS_MAX}
Maximum number of weights that can be assigned to an entry of the LC_COLLATE order keyword in the locale definition file; see Locale .
Value: 2
{_POSIX2_EXPR_NEST_MAX}
Maximum number of expressions that can be nested within parentheses by the expr utility.
Value: 32
{_POSIX2_LINE_MAX}
Unless otherwise noted, the maximum length, in bytes, of a utility's input line (either standard input or another file), when the utility is described as processing text files. The length includes room for the trailing <newline>.
Value: 2 048
{_POSIX2_RE_DUP_MAX
Maximum number of repeated occurrences of a regular expression permitted when using the interval notation \{m,n\}; see Regular Expressions .
Value: 255
{_XOPEN_IOV_MAX}

Maximum number of iovec structures that one process has available for use with readv() or writev().
Value: 16

{_XOPEN_NAME_MAX}

Maximum number of bytes in a filename (not including the terminating null).
Value: 255

{_XOPEN_PATH_MAX}

Maximum number of bytes in a pathname.
Value: 1024

Numerical Limits

The values in the following lists shall be defined in <limits.h> and are constant expressions suitable for use in #if preprocessing directives. Moreover, except for {CHAR_BIT}, {DBL_DIG}, {DBL_MAX}, {FLT_DIG}, {FLT_MAX}, {LONG_BIT}, {WORD_BIT}, and {MB_LEN_MAX}, the symbolic names are defined as expressions of the correct type.

If the value of an object of type char is treated as a signed integer when used in an expression, the value of {CHAR_MIN} is the same as that of {SCHAR_MIN} and the value of {CHAR_MAX} is the same as that of {SCHAR_MAX}. Otherwise, the value of {CHAR_MIN} is 0 and the value of {CHAR_MAX} is the same as that of {UCHAR_MAX}.

{CHAR_BIT}
Number of bits in a type char.
Value: 8
{CHAR_MAX}
Maximum value of type char.
Value: {UCHAR_MAX} or {SCHAR_MAX}
{CHAR_MIN}
Minimum value of type char.
Value: {SCHAR_MIN} or 0
{INT_MAX}
Maximum value of an int.
Minimum Acceptable Value: 2 147 483 647
{LONG_BIT}

Number of bits in a long.
Minimum Acceptable Value: 32

{LONG_MAX}
Maximum value of a long.
Minimum Acceptable Value: +2 147 483 647
{MB_LEN_MAX}
Maximum number of bytes in a character, for any supported locale.
Minimum Acceptable Value: 1
{SCHAR_MAX}
Maximum value of type signed char.
Value: +127
{SHRT_MAX}
Maximum value of type short.
Minimum Acceptable Value: +32 767
{SSIZE_MAX}
Maximum value of an object of type ssize_t.
Minimum Acceptable Value: {_POSIX_SSIZE_MAX}
{UCHAR_MAX}
Maximum value of type unsigned char.
Value: 255
{UINT_MAX}
Maximum value of type unsigned.
Minimum Acceptable Value: 4 294 967 295
{ULONG_MAX}
Maximum value of type unsigned long.
Minimum Acceptable Value: 4 294 967 295
{USHRT_MAX}
Maximum value for a type unsigned short.
Minimum Acceptable Value: 65 535
{WORD_BIT}

Number of bits in a word or type int.
Minimum Acceptable Value: 16

{INT_MIN}
Minimum value of type int.
Maximum Acceptable Value: -2 147 483 647
{LONG_MIN}
Minimum value of type long.
Maximum Acceptable Value: -2 147 483 647
{SCHAR_MIN}
Minimum value of type signed char.
Value: -128
{SHRT_MIN}
Minimum value of type short.
Maximum Acceptable Value: -32 767
{LLONG_MIN}
Minimum value of type long long.
Maximum Acceptable Value: -9223372036854775807
{LLONG_MAX}
Maximum value of type long long.
Minimum Acceptable Value: +9223372036854775807
{ULLONG_MAX}
Maximum value of type unsigned long long.
Minimum Acceptable Value: 18446744073709551615

Other Invariant Values

The following constants shall be defined on all implementations in <limits.h>:

{CHARCLASS_NAME_MAX}

Maximum number of bytes in a character class name.
Minimum Acceptable Value: 14

{NL_ARGMAX}

Maximum value of digit in calls to the printf() and scanf() functions.
Minimum Acceptable Value: 9

{NL_LANGMAX}

Maximum number of bytes in a LANG name.
Minimum Acceptable Value: 14

{NL_MSGMAX}

Maximum message number.
Minimum Acceptable Value: 32 767

{NL_NMAX}

Maximum number of bytes in an N-to-1 collation mapping.
Minimum Acceptable Value: No guaranteed value across all conforming implementations.

{NL_SETMAX}

Maximum set number.
Minimum Acceptable Value: 255

{NL_TEXTMAX}

Maximum number of bytes in a message string.
Minimum Acceptable Value: {_POSIX2_LINE_MAX}

{NZERO}

Default process priority.
Minimum Acceptable Value: 20

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

A request was made to reduce the value of {_POSIX_LINK_MAX} from the value of 8 specified for it in the POSIX.1-1990 standard to 2. The standard developers decided to deny this request for several reasons:

*
They wanted to avoid making any changes to the standard that could break conforming applications, and the requested change could have that effect.

*
The use of multiple hard links to a file cannot always be replaced with use of symbolic links. Symbolic links are semantically different from hard links in that they associate a pathname with another pathname rather than a pathname with a file. This has implications for access control, file permanence, and transparency.

*
The original standard developers had considered the issue of allowing for implementations that did not in general support hard links, and decided that this would reduce consensus on the standard.

Systems that support historical versions of the development option of the ISO POSIX-2 standard retain the name {_POSIX2_RE_DUP_MAX} as an alias for {_POSIX_RE_DUP_MAX}.

{PATH_MAX}
IEEE PASC Interpretation 1003.1 #15 addressed the inconsistency in the standard with the definition of pathname and the description of {PATH_MAX}, allowing application writers to allocate either {PATH_MAX} or {PATH_MAX}+1 bytes. The inconsistency has been removed by correction to the {PATH_MAX} definition to include the null character. With this change, applications that previously allocated {PATH_MAX} bytes will continue to succeed.
{SYMLINK_MAX}
This symbol refers to space for data that is stored in the file system, as opposed to {PATH_MAX} which is the length of a name that can be passed to a function. In some existing implementations, the filenames pointed to by symbolic links are stored in the inodes of the links, so it is important that {SYMLINK_MAX} not be constrained to be as large as {PATH_MAX}.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, fpathconf(), pathconf(), sysconf()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


if.h(0p)

<net/if.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

net/if.h - sockets local interfaces

SYNOPSIS

#include <net/if.h>

DESCRIPTION

The <net/if.h> header shall define the if_nameindex structure that includes at least the following members:

unsigned  if_index  Numeric index of the interface.
char     *if_name   Null-terminated name of the interface.

The <net/if.h> header shall define the following macro for the length of a buffer containing an interface name (including the terminating NULL character):

IF_NAMESIZE
Interface name length.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

unsigned              if_nametoindex(const char *);
char                 *if_indextoname(unsigned, char *);
struct if_nameindex  *if_nameindex(void);
void                  if_freenameindex(struct if_nameindex *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, if_freenameindex(), if_indextoname(), if_nameindex(), if_nametoindex()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stat.h(0p)

Status: 403 Forbidden stat.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/stat.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


glob.h(0p)

<glob.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

glob.h - pathname pattern-matching types

SYNOPSIS

#include <glob.h>

DESCRIPTION

The <glob.h> header shall define the structures and symbolic constants used by the glob() function.

The structure type glob_t shall contain at least the following members:

size_t   gl_pathc Count of paths matched by pattern.
char   **gl_pathv Pointer to a list of matched pathnames.
size_t   gl_offs  Slots to reserve at the beginning of gl_pathv.

The following constants shall be provided as values for the flags argument:

GLOB_APPEND
Append generated pathnames to those previously obtained.
GLOB_DOOFFS
Specify how many null pointers to add to the beginning of gl_pathv.
GLOB_ERR
Cause glob() to return on error.
GLOB_MARK
Each pathname that is a directory that matches pattern has a slash appended.
GLOB_NOCHECK
If pattern does not match any pathname, then return a list consisting of only pattern.
GLOB_NOESCAPE
Disable backslash escaping.
GLOB_NOSORT
Do not sort the pathnames returned.

The following constants shall be defined as error return values:

GLOB_ABORTED
The scan was stopped because GLOB_ERR was set or (*errfunc)() returned non-zero.
GLOB_NOMATCH
The pattern does not match any existing pathname, and GLOB_NOCHECK was not set in flags.
GLOB_NOSPACE
An attempt to allocate memory failed.
GLOB_NOSYS
Reserved.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int  glob(const char *restrict, int, int (*)(const char *, int),
         glob_t *restrict);
void globfree (glob_t *);

The implementation may define additional macros or constants using names beginning with GLOB_.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, glob(), the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


types.h(0p)

Status: 403 Forbidden types.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/types.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


mqueue.h(0p)

<mqueue.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mqueue.h - message queues (REALTIME)

SYNOPSIS

#include <mqueue.h>

DESCRIPTION

The <mqueue.h> header shall define the mqd_t type, which is used for message queue descriptors. This is not an array type.

The <mqueue.h> header shall define the sigevent structure (as described in <signal.h> ) and the mq_attr structure, which is used in getting and setting the attributes of a message queue. Attributes are initially set when the message queue is created. An mq_attr structure shall have at least the following fields:

long    mq_flags    Message queue flags.
long    mq_maxmsg   Maximum number of messages.
long    mq_msgsize  Maximum message size.
long    mq_curmsgs  Number of messages currently queued.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int      mq_close(mqd_t);
int      mq_getattr(mqd_t, struct mq_attr *);
int      mq_notify(mqd_t, const struct sigevent *);
mqd_t    mq_open(const char *, int, ...);
ssize_t  mq_receive(mqd_t, char *, size_t, unsigned *);
int      mq_send(mqd_t, const char *, size_t, unsigned );
int      mq_setattr(mqd_t, const struct mq_attr *restrict,
             struct mq_attr *restrict);

ssize_t  mq_timedreceive(mqd_t, char *restrict, size_t,
             unsigned *restrict, const struct timespec *restrict);
int      mq_timedsend(mqd_t, const char *, size_t, unsigned ,
             const struct timespec *);

int      mq_unlink(const char *);

Inclusion of the <mqueue.h> header may make visible symbols defined in the headers <fcntl.h>, <signal.h>, <sys/types.h>, and <time.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<fcntl.h> , <signal.h> , <sys/types.h> , <time.h> , the System Interfaces volume of IEEE Std 1003.1-2001, mq_close(), mq_getattr(), mq_notify(), mq_open(), mq_receive(), mq_send(), mq_setattr(), mq_timedreceive(), mq_timedsend(), mq_unlink()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dlfcn.h(0p)

<dlfcn.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dlfcn.h - dynamic linking

SYNOPSIS

#include <dlfcn.h>

DESCRIPTION

The <dlfcn.h> header shall define at least the following macros for use in the construction of a dlopen() mode argument:

RTLD_LAZY
Relocations are performed at an implementation-defined time.
RTLD_NOW
Relocations are performed when the object is loaded.
RTLD_GLOBAL
All symbols are available for relocation processing of other modules.
RTLD_LOCAL
All symbols are not made available for relocation processing by other modules.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    dlclose(void *);
char  *dlerror(void);
void  *dlopen(const char *, int);
void  *dlsym(void *restrict, const char *restrict);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, dlopen(), dlclose(), dlsym(), dlerror()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ucontext.h(0p)

<ucontext.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ucontext.h - user context

SYNOPSIS

#include <ucontext.h>

DESCRIPTION

The <ucontext.h> header shall define the mcontext_t type through typedef.

The <ucontext.h> header shall define the ucontext_t type as a structure that shall include at least the following members:

ucontext_t *uc_link     Pointer to the context that is resumed
                        when this context returns.
sigset_t    uc_sigmask  The set of signals that are blocked when this
                        context is active.
stack_t     uc_stack    The stack used by this context.
mcontext_t  uc_mcontext A machine-specific representation of the saved
                        context.

The types sigset_t and stack_t shall be defined as in <signal.h> .

The following shall be declared as functions and may also be defined as macros, Function prototypes shall be provided.

int  getcontext(ucontext_t *);
int  setcontext(const ucontext_t *);
void makecontext(ucontext_t *, void (*)(void), int, ...);
int  swapcontext(ucontext_t *restrict, const ucontext_t *restrict);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<signal.h> , the System Interfaces volume of IEEE Std 1003.1-2001, getcontext(), makecontext(), sigaction(), sigprocmask(), sigaltstack()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


search.h(0p)

<search.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

search.h - search tables

SYNOPSIS

#include <search.h>

DESCRIPTION

The <search.h> header shall define the ENTRY type for structure entry which shall include the following members:

char    *key
void    *data

and shall define ACTION and VISIT as enumeration data types through type definitions as follows:

enum { FIND, ENTER } ACTION;
enum { preorder, postorder, endorder, leaf } VISIT;

The size_t type shall be defined as described in <sys/types.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    hcreate(size_t);
void   hdestroy(void);
ENTRY *hsearch(ENTRY, ACTION);
void   insque(void *, void *);
void  *lfind(const void *, const void *, size_t *,
          size_t, int (*)(const void *, const void *));
void  *lsearch(const void *, void *, size_t *,
          size_t, int (*)(const void *, const void *));
void   remque(void *);
void  *tdelete(const void *restrict, void **restrict,
          int(*)(const void *, const void *));
void  *tfind(const void *, void *const *,
          int(*)(const void *, const void *));
void  *tsearch(const void *, void **,
          int(*)(const void *, const void *));
void   twalk(const void *,
          void (*)(const void *, VISIT, int ));

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, hcreate(), insque(), lsearch(), remque(), tsearch()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strings.h(0p)

<strings.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strings.h - string operations

SYNOPSIS

#include <strings.h>

DESCRIPTION

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    bcmp(const void *, const void *, size_t); (LEGACY )
void   bcopy(const void *, void *, size_t); (LEGACY )
void   bzero(void *, size_t); (LEGACY )
int    ffs(int);
char  *index(const char *, int); (LEGACY )
char  *rindex(const char *, int); (LEGACY )
int    strcasecmp(const char *, const char *);
int    strncasecmp(const char *, const char *, size_t);

The size_t type shall be defined through typedef as described in <stddef.h> .

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<stddef.h> , the System Interfaces volume of IEEE Std 1003.1-2001, ffs(), strcasecmp(), strncasecmp()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nl_types.h(0p)

<nl_types.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nl_types.h - data types

SYNOPSIS

#include <nl_types.h>

DESCRIPTION

The <nl_types.h> header shall contain definitions of at least the following types:

nl_catd
Used by the message catalog functions catopen(), catgets(), and catclose() to identify a catalog descriptor.
nl_item
Used by nl_langinfo() to identify items of langinfo data. Values of objects of type nl_item are defined in <langinfo.h> .

The <nl_types.h> header shall contain definitions of at least the following constants:

NL_SETD
Used by gencat when no $set directive is specified in a message text source file; see the Internationalization Guide. This constant can be passed as the value of set_id on subsequent calls to catgets() (that is, to retrieve messages from the default message set). The value of NL_SETD is implementation-defined.
NL_CAT_LOCALE
Value that must be passed as the oflag argument to catopen() to ensure that message catalog selection depends on the LC_MESSAGES locale category, rather than directly on the LANG environment variable.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int       catclose(nl_catd);
char     *catgets(nl_catd, int, int, const char *);
nl_catd   catopen(const char *, int);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<langinfo.h> , the System Interfaces volume of IEEE Std 1003.1-2001, catclose(), catgets(), catopen(), nl_langinfo(), the Shell and Utilities volume of IEEE Std 1003.1-2001, gencat

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_time.h(0p)

<sys/time.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/time.h - time types

SYNOPSIS

#include <sys/time.h>

DESCRIPTION

The <sys/time.h> header shall define the timeval structure that includes at least the following members:

time_t         tv_sec      Seconds.
suseconds_t    tv_usec     Microseconds.

The <sys/time.h> header shall define the itimerval structure that includes at least the following members:

struct timeval it_interval Timer interval.
struct timeval it_value    Current value.

The time_t and suseconds_t types shall be defined as described in <sys/types.h> .

The fd_set type shall be defined as described in <sys/select.h> .

The <sys/time.h> header shall define the following values for the which argument of getitimer() and setitimer():

ITIMER_REAL
Decrements in real time.
ITIMER_VIRTUAL
Decrements in process virtual time.
ITIMER_PROF
Decrements both in process virtual time and when the system is running on behalf of the process.

The following shall be defined as described in <sys/select.h> : FD_CLR() FD_ISSET() FD_SET() FD_ZERO() FD_SETSIZE

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int   getitimer(int, struct itimerval *);
int   gettimeofday(struct timeval *restrict, void *restrict);
int   select(int, fd_set *restrict, fd_set *restrict, fd_set *restrict,
          struct timeval *restrict);
int   setitimer(int, const struct itimerval *restrict,
          struct itimerval *restrict);
int   utimes(const char *, const struct timeval [2]); (LEGACY )

Inclusion of the <sys/time.h> header may make visible all symbols from the <sys/select.h> header.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/select.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, getitimer(), gettimeofday(), select(), setitimer()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sched.h(0p)

<sched.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched.h - execution scheduling (REALTIME)

SYNOPSIS

#include <sched.h>

DESCRIPTION

The <sched.h> header shall define the sched_param structure, which contains the scheduling parameters required for implementation of each supported scheduling policy. This structure shall contain at least the following member:

int       sched_priority        Process execution scheduling priority.

In addition, if _POSIX_SPORADIC_SERVER or _POSIX_THREAD_SPORADIC_SERVER is defined, the sched_param structure defined in <sched.h> shall contain the following members in addition to those specified above:

int             sched_ss_low_priority Low scheduling priority for
                                      sporadic server.
struct timespec sched_ss_repl_period  Replenishment period for
                                      sporadic server.
struct timespec sched_ss_init_budget  Initial budget for sporadic server.
int             sched_ss_max_repl     Maximum pending replenishments for
                                      sporadic server.

Each process is controlled by an associated scheduling policy and priority. Associated with each policy is a priority range. Each policy definition specifies the minimum priority range for that policy. The priority ranges for each policy may overlap the priority ranges of other policies.

Four scheduling policies are defined; others may be defined by the implementation. The four standard policies are indicated by the values of the following symbolic constants:

SCHED_FIFO
First in-first out (FIFO) scheduling policy.
SCHED_RR
Round robin scheduling policy.
SCHED_SPORADIC
Sporadic server scheduling policy.
SCHED_OTHER
Another scheduling policy.

The values of these constants are distinct.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int    sched_get_priority_max(int);
int    sched_get_priority_min(int);

int    sched_getparam(pid_t, struct sched_param *);
int    sched_getscheduler(pid_t);

int    sched_rr_get_interval(pid_t, struct timespec *);

int    sched_setparam(pid_t, const struct sched_param *);
int    sched_setscheduler(pid_t, int, const struct sched_param *);

int    sched_yield(void);

Inclusion of the <sched.h> header may make visible all symbols from the <time.h> header.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_resource.h(0p)

<sys/resource.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/resource.h - definitions for XSI resource operations

SYNOPSIS

#include <sys/resource.h>

DESCRIPTION

The <sys/resource.h> header shall define the following symbolic constants as possible values of the which argument of getpriority() and setpriority():

PRIO_PROCESS
Identifies the who argument as a process ID.
PRIO_PGRP
Identifies the who argument as a process group ID.
PRIO_USER
Identifies the who argument as a user ID.

The following type shall be defined through typedef:

rlim_t
Unsigned integer type used for limit values.

The following symbolic constants shall be defined:

RLIM_INFINITY
A value of rlim_t indicating no limit.
RLIM_SAVED_MAX
A value of type rlim_t indicating an unrepresentable saved hard limit.
RLIM_SAVED_CUR
A value of type rlim_t indicating an unrepresentable saved soft limit.

On implementations where all resource limits are representable in an object of type rlim_t, RLIM_SAVED_MAX and RLIM_SAVED_CUR need not be distinct from RLIM_INFINITY.

The following symbolic constants shall be defined as possible values of the who parameter of getrusage():

RUSAGE_SELF
Returns information about the current process.
RUSAGE_CHILDREN
Returns information about children of the current process.

The <sys/resource.h> header shall define the rlimit structure that includes at least the following members:

rlim_t rlim_cur  The current (soft) limit.
rlim_t rlim_max  The hard limit.

The <sys/resource.h> header shall define the rusage structure that includes at least the following members:

struct timeval ru_utime  User time used.
struct timeval ru_stime  System time used.

The timeval structure shall be defined as described in <sys/time.h> .

The following symbolic constants shall be defined as possible values for the resource argument of getrlimit() and setrlimit():

RLIMIT_CORE
Limit on size of core file.
RLIMIT_CPU
Limit on CPU time per process.
RLIMIT_DATA
Limit on data segment size.
RLIMIT_FSIZE
Limit on file size.
RLIMIT_NOFILE
Limit on number of open files.
RLIMIT_STACK
Limit on stack size.
RLIMIT_AS
Limit on address space size.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int  getpriority(int, id_t);
int  getrlimit(int, struct rlimit *);
int  getrusage(int, struct rusage *);
int  setpriority(int, id_t, int);
int  setrlimit(int, const struct rlimit *);

The id_t type shall be defined through typedef as described in <sys/types.h> .

Inclusion of the <sys/resource.h> header may also make visible all symbols from <sys/time.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/time.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, getpriority(), getrusage(), getrlimit()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


in.h(0p)

<netinet/in.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

netinet/in.h - Internet address family

SYNOPSIS

#include <netinet/in.h>

DESCRIPTION

The <netinet/in.h> header shall define the following types:

in_port_t
Equivalent to the type uint16_t as defined in <inttypes.h> .
in_addr_t
Equivalent to the type uint32_t as defined in <inttypes.h> .

The sa_family_t type shall be defined as described in <sys/socket.h> .

The uint8_t and uint32_t type shall be defined as described in <inttypes.h>. Inclusion of the <netinet/in.h> header may also make visible all symbols from <inttypes.h> and <sys/socket.h>.

The <netinet/in.h> header shall define the in_addr structure that includes at least the following member:

in_addr_t  s_addr

The <netinet/in.h> header shall define the sockaddr_in structure that includes at least the following members (all in network byte order):

sa_family_t     sin_family   AF_INET.
in_port_t       sin_port     Port number.
struct in_addr  sin_addr     IP address.

The sockaddr_in structure is used to store addresses for the Internet address family. Values of this type shall be cast by applications to struct sockaddr for use with socket functions.

The <netinet/in.h> header shall define the in6_addr structure that contains at least the following member:

uint8_t s6_addr[16]

This array is used to contain a 128-bit IPv6 address, stored in network byte order.

The <netinet/in.h> header shall define the sockaddr_in6 structure that includes at least the following members (all in network byte order):

sa_family_t      sin6_family    AF_INET6.
in_port_t        sin6_port      Port number.
uint32_t         sin6_flowinfo  IPv6 traffic class and flow information.
struct in6_addr  sin6_addr      IPv6 address.
uint32_t         sin6_scope_id  Set of interfaces for a scope.

The sockaddr_in6 structure shall be set to zero by an application prior to using it, since implementations are free to have additional, implementation-defined fields in sockaddr_in6.

The sin6_scope_id field is a 32-bit integer that identifies a set of interfaces as appropriate for the scope of the address carried in the sin6_addr field. For a link scope sin6_addr, the application shall ensure that sin6_scope_id is a link index. For a site scope sin6_addr, the application shall ensure that sin6_scope_id is a site index. The mapping of sin6_scope_id to an interface or set of interfaces is implementation-defined.

The <netinet/in.h> header shall declare the following external variable:

const struct in6_addr in6addr_any

This variable is initialized by the system to contain the wildcard IPv6 address. The <netinet/in.h> header also defines the IN6ADDR_ANY_INIT macro. This macro must be constant at compile time and can be used to initialize a variable of type struct in6_addr to the IPv6 wildcard address.

The <netinet/in.h> header shall declare the following external variable:

const struct in6_addr in6addr_loopback

This variable is initialized by the system to contain the loopback IPv6 address. The <netinet/in.h> header also defines the IN6ADDR_LOOPBACK_INIT macro. This macro must be constant at compile time and can be used to initialize a variable of type struct in6_addr to the IPv6 loopback address.

The <netinet/in.h> header shall define the ipv6_mreq structure that includes at least the following members:

struct in6_addr  ipv6mr_multiaddr  IPv6 multicast address.
unsigned         ipv6mr_interface  Interface index.

The <netinet/in.h> header shall define the following macros for use as values of the level argument of getsockopt() and setsockopt():

IPPROTO_IP
Internet protocol.
IPPROTO_IPV6
Internet Protocol Version 6.
IPPROTO_ICMP
Control message protocol.
IPPROTO_RAW
Raw IP Packets Protocol.
IPPROTO_TCP
Transmission control protocol.
IPPROTO_UDP
User datagram protocol.

The <netinet/in.h> header shall define the following macros for use as destination addresses for connect(), sendmsg(), and sendto():

INADDR_ANY
IPv4 local host address.
INADDR_BROADCAST
IPv4 broadcast address.

The <netinet/in.h> header shall define the following macro to help applications declare buffers of the proper size to store IPv4 addresses in string form:

INET_ADDRSTRLEN
16. Length of the string form for IP.

The htonl(), htons(), ntohl(), and ntohs() functions shall be available as defined in <arpa/inet.h> . Inclusion of the <netinet/in.h> header may also make visible all symbols from <arpa/inet.h> .

The <netinet/in.h> header shall define the following macro to help applications declare buffers of the proper size to store IPv6 addresses in string form:

INET6_ADDRSTRLEN
46. Length of the string form for IPv6.

The <netinet/in.h> header shall define the following macros, with distinct integer values, for use in the option_name argument in the getsockopt() or setsockopt() functions at protocol level IPPROTO_IPV6:

IPV6_JOIN_GROUP
Join a multicast group.
IPV6_LEAVE_GROUP
Quit a multicast group.
IPV6_MULTICAST_HOPS

Multicast hop limit.

IPV6_MULTICAST_IF
Interface to use for outgoing multicast packets.
IPV6_MULTICAST_LOOP

Multicast packets are delivered back to the local application.

IPV6_UNICAST_HOPS
Unicast hop limit.
IPV6_V6ONLY
Restrict AF_INET6 socket to IPv6 communications only.

The <netinet/in.h> header shall define the following macros that test for special IPv6 addresses. Each macro is of type int and takes a single argument of type const struct in6_addr *:

IN6_IS_ADDR_UNSPECIFIED

Unspecified address.

IN6_IS_ADDR_LOOPBACK

Loopback address.

IN6_IS_ADDR_MULTICAST

Multicast address.

IN6_IS_ADDR_LINKLOCAL

Unicast link-local address.

IN6_IS_ADDR_SITELOCAL

Unicast site-local address.

IN6_IS_ADDR_V4MAPPED

IPv4 mapped address.

IN6_IS_ADDR_V4COMPAT

IPv4-compatible address.

IN6_IS_ADDR_MC_NODELOCAL

Multicast node-local address.

IN6_IS_ADDR_MC_LINKLOCAL

Multicast link-local address.

IN6_IS_ADDR_MC_SITELOCAL

Multicast site-local address.

IN6_IS_ADDR_MC_ORGLOCAL

Multicast organization-local address.

IN6_IS_ADDR_MC_GLOBAL

Multicast global address.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Host and Network Byte Orders , <arpa/inet.h> , <inttypes.h> , <sys/socket.h> , the System Interfaces volume of IEEE Std 1003.1-2001, connect(), getsockopt(), htonl(), htons(), ntohl(), ntohs(), sendmsg(), sendto(), setsockopt()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


utime.h(0p)

<utime.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

utime.h - access and modification times structure

SYNOPSIS

#include <utime.h>

DESCRIPTION

The <utime.h> header shall declare the structure utimbuf, which shall include the following members:

time_t    actime    Access time.
time_t    modtime   Modification time.

The times shall be measured in seconds since the Epoch.

The type time_t shall be defined as described in <sys/types.h> .

The following shall be declared as a function and may also be defined as a macro. A function prototype shall be provided.

int utime(const char *, const struct utimbuf *);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, utime()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


inet.h(0p)

<arpa/inet.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

arpa/inet.h - definitions for internet operations

SYNOPSIS

#include <arpa/inet.h>

DESCRIPTION

The in_port_t and in_addr_t types shall be defined as described in <netinet/in.h> .

The in_addr structure shall be defined as described in <netinet/in.h> .

The INET_ADDRSTRLEN and INET6_ADDRSTRLEN macros shall be defined as described in <netinet/in.h> .

The following shall either be declared as functions, defined as macros, or both. If functions are declared, function prototypes shall be provided.

uint32_t htonl(uint32_t);
uint16_t htons(uint16_t);
uint32_t ntohl(uint32_t);
uint16_t ntohs(uint16_t);

The uint32_t and uint16_t types shall be defined as described in <inttypes.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

in_addr_t    inet_addr(const char *);
char        *inet_ntoa(struct in_addr);
const char  *inet_ntop(int, const void *restrict, char *restrict,
                 socklen_t);
int          inet_pton(int, const char *restrict, void *restrict);

Inclusion of the <arpa/inet.h> header may also make visible all symbols from <netinet/in.h> and <inttypes.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<netinet/in.h> , <inttypes.h> , the System Interfaces volume of IEEE Std 1003.1-2001, htonl(), inet_addr()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mman.h(0p)

Status: 403 Forbidden mman.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/mman.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


spawn.h(0p)

<spawn.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

spawn.h - spawn (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

DESCRIPTION

The <spawn.h> header shall define the posix_spawnattr_t and posix_spawn_file_actions_t types used in performing spawn operations.

The <spawn.h> header shall define the flags that may be set in a posix_spawnattr_t object using the posix_spawnattr_setflags() function:

POSIX_SPAWN_RESETIDS
POSIX_SPAWN_SETPGROUP

POSIX_SPAWN_SETSCHEDPARAM
POSIX_SPAWN_SETSCHEDULER

POSIX_SPAWN_SETSIGDEF
POSIX_SPAWN_SETSIGMASK

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int   posix_spawn(pid_t *restrict, const char *restrict,
          const posix_spawn_file_actions_t *,
          const posix_spawnattr_t *restrict, char *const [restrict],
          char *const [restrict]);
int   posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *,
          int);
int   posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *,
          int, int);
int   posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *restrict,
          int, const char *restrict, int, mode_t);
int   posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *);
int   posix_spawn_file_actions_init(posix_spawn_file_actions_t *);
int   posix_spawnattr_destroy(posix_spawnattr_t *);
int   posix_spawnattr_getsigdefault(const posix_spawnattr_t *restrict,
          sigset_t *restrict);
int   posix_spawnattr_getflags(const posix_spawnattr_t *restrict,
          short *restrict);
int   posix_spawnattr_getpgroup(const posix_spawnattr_t *restrict,
          pid_t *restrict);

int   posix_spawnattr_getschedparam(const posix_spawnattr_t *restrict,
          struct sched_param *restrict);
int   posix_spawnattr_getschedpolicy(const posix_spawnattr_t *restrict,
          int *restrict);

int   posix_spawnattr_getsigmask(const posix_spawnattr_t *restrict,
          sigset_t *restrict);
int   posix_spawnattr_init(posix_spawnattr_t *);
int   posix_spawnattr_setsigdefault(posix_spawnattr_t *restrict,
          const sigset_t *restrict);
int   posix_spawnattr_setflags(posix_spawnattr_t *, short);
int   posix_spawnattr_setpgroup(posix_spawnattr_t *, pid_t);

int   posix_spawnattr_setschedparam(posix_spawnattr_t *restrict,
          const struct sched_param *restrict);
int   posix_spawnattr_setschedpolicy(posix_spawnattr_t *, int);

int   posix_spawnattr_setsigmask(posix_spawnattr_t *restrict,
          const sigset_t *restrict);
int   posix_spawnp(pid_t *restrict, const char *restrict,
          const posix_spawn_file_actions_t *,
          const posix_spawnattr_t *restrict,
          char *const [restrict], char *const [restrict]);

Inclusion of the <spawn.h> header may make visible symbols defined in the <sched.h>, <signal.h>, and <sys/types.h> headers.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sched.h> , <semaphore.h> , <signal.h> , <sys/types.h>
, the System Interfaces
volume of IEEE Std 1003.1-2001, posix_spawnattr_destroy(),
posix_spawnattr_getsigdefault(), posix_spawnattr_getflags(),
posix_spawnattr_getpgroup(), posix_spawnattr_getschedparam(),
posix_spawnattr_getschedpolicy(), posix_spawnattr_getsigmask(),
posix_spawnattr_init(), posix_spawnattr_setsigdefault(),
posix_spawnattr_setflags(), posix_spawnattr_setpgroup(),
posix_spawnattr_setschedparam(), posix_spawnattr_setschedpolicy(),
posix_spawnattr_setsigmask(), posix_spawn(), posix_spawn_file_actions_addclose(),
posix_spawn_file_actions_adddup2(), posix_spawn_file_actions_addopen(),
posix_spawn_file_actions_destroy(), posix_spawn_file_actions_init(),
posix_spawnp()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


msg.h(0p)

Status: 403 Forbidden msg.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/msg.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


stdio.h(0p)

<stdio.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stdio.h - standard buffered input/output

SYNOPSIS

#include <stdio.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <stdio.h> header shall define the following macros as positive integer constant expressions:

BUFSIZ
Size of <stdio.h> buffers.
_IOFBF
Input/output fully buffered.
_IOLBF
Input/output line buffered.
_IONBF
Input/output unbuffered.
L_ctermid
Maximum size of character array to hold ctermid() output.
L_tmpnam
Maximum size of character array to hold tmpnam() output.
SEEK_CUR
Seek relative to current position.
SEEK_END
Seek relative to end-of-file.
SEEK_SET
Seek relative to start-of-file.

The following macros shall be defined as positive integer constant expressions which denote implementation limits:

{FILENAME_MAX}
Maximum size in bytes of the longest filename string that the implementation guarantees can be opened.
{FOPEN_MAX}
Number of streams which the implementation guarantees can be open simultaneously. The value is at least eight.
{TMP_MAX}
Minimum number of unique filenames generated by tmpnam(). Maximum number of times an application can call tmpnam() reliably. The value of {TMP_MAX} is at least 25. On XSI-conformant systems, the value of {TMP_MAX} is at least 10000.

The following macro name shall be defined as a negative integer constant expression:

EOF
End-of-file return value.

The following macro name shall be defined as a null pointer constant:

NULL
Null pointer.

The following macro name shall be defined as a string constant:

P_tmpdir
Default directory prefix for tempnam().

The following shall be defined as expressions of type "pointer to FILE" that point to the FILE objects associated, respectively, with the standard error, input, and output streams:

stderr
Standard error output stream.
stdin
Standard input stream.
stdout
Standard output stream.

The following data types shall be defined through typedef:

FILE
A structure containing information about a file.
fpos_t
A non-array type containing all information needed to specify uniquely every position within a file.
va_list
As described in <stdarg.h> .
size_t
As described in <stddef.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void     clearerr(FILE *);

char    *ctermid(char *);

int      fclose(FILE *);

FILE    *fdopen(int, const char *);

int      feof(FILE *);
int      ferror(FILE *);
int      fflush(FILE *);
int      fgetc(FILE *);
int      fgetpos(FILE *restrict, fpos_t *restrict);
char    *fgets(char *restrict, int, FILE *restrict);

int      fileno(FILE *);

void     flockfile(FILE *);

FILE    *fopen(const char *restrict, const char *restrict);
int      fprintf(FILE *restrict, const char *restrict, ...);
int      fputc(int, FILE *);
int      fputs(const char *restrict, FILE *restrict);
size_t   fread(void *restrict, size_t, size_t, FILE *restrict);
FILE    *freopen(const char *restrict, const char *restrict,
             FILE *restrict);
int      fscanf(FILE *restrict, const char *restrict, ...);
int      fseek(FILE *, long, int);

int      fseeko(FILE *, off_t, int);

int      fsetpos(FILE *, const fpos_t *);
long     ftell(FILE *);

off_t    ftello(FILE *);

int      ftrylockfile(FILE *);
void     funlockfile(FILE *);

size_t   fwrite(const void *restrict, size_t, size_t, FILE *restrict);
int      getc(FILE *);
int      getchar(void);

int      getc_unlocked(FILE *);
int      getchar_unlocked(void);

char    *gets(char *);

int      pclose(FILE *);

void     perror(const char *);

FILE    *popen(const char *, const char *);

int      printf(const char *restrict, ...);
int      putc(int, FILE *);
int      putchar(int);

int      putc_unlocked(int, FILE *);
int      putchar_unlocked(int);

int      puts(const char *);
int      remove(const char *);
int      rename(const char *, const char *);
void     rewind(FILE *);
int      scanf(const char *restrict, ...);
void     setbuf(FILE *restrict, char *restrict);
int      setvbuf(FILE *restrict, char *restrict, int, size_t);
int      snprintf(char *restrict, size_t, const char *restrict, ...);
int      sprintf(char *restrict, const char *restrict, ...);
int      sscanf(const char *restrict, const char *restrict, int ...);

char    *tempnam(const char *, const char *);

FILE    *tmpfile(void);
char    *tmpnam(char *);
int      ungetc(int, FILE *);
int      vfprintf(FILE *restrict, const char *restrict, va_list);
int      vfscanf(FILE *restrict, const char *restrict, va_list);
int      vprintf(const char *restrict, va_list);
int      vscanf(const char *restrict, va_list);
int      vsnprintf(char *restrict, size_t, const char *restrict, va_list;
int      vsprintf(char *restrict, const char *restrict, va_list);
int      vsscanf(const char *restrict, const char *restrict, va_list arg);

Inclusion of the <stdio.h> header may also make visible all symbols from <stddef.h>.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<stdarg.h> , <stddef.h> , <sys/types.h> , the System
Interfaces volume of IEEE Std 1003.1-2001, clearerr(), ctermid(),
fclose(), fdopen(), fgetc(), fgetpos(), ferror(),
feof(), fflush(), fgets(), fileno(), flockfile(),
fopen(), fputc(), fputs(), fread(), freopen(),
fseek(), fsetpos(), ftell(), fwrite(), getc(),
getc_unlocked(), getwchar(), getchar(), getopt(),
gets(), pclose(), perror(), popen(), printf(),
putc(), putchar(), puts(), putwchar(), remove(),
rename(), rewind(), scanf(), setbuf(), setvbuf(),
sscanf(), stdin, system(), tempnam(), tmpfile(),
tmpnam(), ungetc(), vfscanf(), vscanf(), vprintf(),
vsscanf()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stdbool.h(0p)

<stdbool.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stdbool.h - boolean type and values

SYNOPSIS

#include <stdbool.h>

DESCRIPTION

The <stdbool.h> header shall define the following macros:

bool
Expands to _Bool.
true
Expands to the integer constant 1.
false
Expands to the integer constant 0.
__bool_true_false_are_defined

Expands to the integer constant 1.

An application may undefine and then possibly redefine the macros bool, true, and false.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

The ability to undefine and redefine the macros bool, true, and false is an obsolescent feature and may be withdrawn in a future version.

SEE ALSO

None.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wordexp.h(0p)

<wordexp.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wordexp.h - word-expansion types

SYNOPSIS

#include <wordexp.h>

DESCRIPTION

The <wordexp.h> header shall define the structures and symbolic constants used by the wordexp() and wordfree() functions.

The structure type wordexp_t shall contain at least the following members:

size_t   we_wordc  Count of words matched by words.
char   **we_wordv  Pointer to list of expanded words.
size_t   we_offs   Slots to reserve at the beginning of we_wordv.

The flags argument to the wordexp() function shall be the bitwise-inclusive OR of the following flags:

WRDE_APPEND
Append words to those previously generated.
WRDE_DOOFFS
Number of null pointers to prepend to we_wordv.
WRDE_NOCMD
Fail if command substitution is requested.
WRDE_REUSE
The pwordexp argument was passed to a previous successful call to wordexp(), and has not been passed to wordfree(). The result is the same as if the application had called wordfree() and then called wordexp() without WRDE_REUSE.
WRDE_SHOWERR
Do not redirect stderr to /dev/null.
WRDE_UNDEF
Report error on an attempt to expand an undefined shell variable.

The following constants shall be defined as error return values:

WRDE_BADCHAR
One of the unquoted characters- <newline>, '|' , '&' , ';' , '<' , '>' , '(' , ')' , '{' , '}' - appears in words in an inappropriate context.
WRDE_BADVAL
Reference to undefined shell variable when WRDE_UNDEF is set in flags.
WRDE_CMDSUB
Command substitution requested when WRDE_NOCMD was set in flags.
WRDE_NOSPACE
Attempt to allocate memory failed.
WRDE_NOSYS
Reserved.
WRDE_SYNTAX
Shell syntax error, such as unbalanced parentheses or unterminated string.

The <wordexp.h> header shall define the following type:

size_t
As described in <stddef.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int  wordexp(const char *restrict, wordexp_t *restrict, int);
void wordfree(wordexp_t *);

The implementation may define additional macros or constants using names beginning with WRDE_.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<stddef.h> , the System Interfaces volume of IEEE Std 1003.1-2001, wordexp(), the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


utmpx.h(0p)

<utmpx.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

utmpx.h - user accounting database definitions

SYNOPSIS

#include <utmpx.h>

DESCRIPTION

The <utmpx.h> header shall define the utmpx structure that shall include at least the following members:

char            ut_user[]  User login name.
char            ut_id[]    Unspecified initialization process identifier.
char            ut_line[]  Device name.
pid_t           ut_pid     Process ID.
short           ut_type    Type of entry.
struct timeval  ut_tv      Time entry was made.

The pid_t type shall be defined through typedef as described in <sys/types.h> .

The timeval structure shall be defined as described in <sys/time.h> .

Inclusion of the <utmpx.h> header may also make visible all symbols from <sys/time.h>.

The following symbolic constants shall be defined as possible values for the ut_type member of the utmpx structure:

EMPTY
No valid user accounting information.
BOOT_TIME
Identifies time of system boot.
OLD_TIME
Identifies time when system clock changed.
NEW_TIME
Identifies time after system clock changed.
USER_PROCESS
Identifies a process.
INIT_PROCESS
Identifies a process spawned by the init process.
LOGIN_PROCESS
Identifies the session leader of a logged-in user.
DEAD_PROCESS
Identifies a session leader who has exited.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

void          endutxent(void);
struct utmpx *getutxent(void);
struct utmpx *getutxid(const struct utmpx *);
struct utmpx *getutxline(const struct utmpx *);
struct utmpx *pututxline(const struct utmpx *);
void          setutxent(void);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/time.h> , <sys/types.h> , the System Interfaces volume of IEEE Std 1003.1-2001, endutxent()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sys_msg.h(0p)

<sys/msg.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sys/msg.h - XSI message queue structures

SYNOPSIS

#include <sys/msg.h>

DESCRIPTION

The <sys/msg.h> header shall define the following data types through typedef:

msgqnum_t
Used for the number of messages in the message queue.
msglen_t
Used for the number of bytes allowed in a message queue.

These types shall be unsigned integer types that are able to store values at least as large as a type unsigned short.

The <sys/msg.h> header shall define the following constant as a message operation flag:

MSG_NOERROR
No error if big message.

The msqid_ds structure shall contain the following members:

struct ipc_perm msg_perm   Operation permission structure.
msgqnum_t       msg_qnum   Number of messages currently on queue.
msglen_t        msg_qbytes Maximum number of bytes allowed on queue.
pid_t           msg_lspid  Process ID of last msgsnd
 ().
pid_t           msg_lrpid  Process ID of last msgrcv
 ().
time_t          msg_stime  Time of last msgsnd
 ().
time_t          msg_rtime  Time of last msgrcv
 ().
time_t          msg_ctime  Time of last change.

The pid_t, time_t, key_t, size_t, and ssize_t types shall be defined as described in <sys/types.h> .

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int       msgctl(int, int, struct msqid_ds *);
int       msgget(key_t, int);
ssize_t   msgrcv(int, void *, size_t, long, int);
int       msgsnd(int, const void *, size_t, int);

In addition, all of the symbols from <sys/ipc.h> shall be defined when this header is included.

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/ipc.h> , <sys/types.h> , msgctl(), msgget(), msgrcv(), msgsnd()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tcp.h(0p)

<netinet/tcp.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

netinet/tcp.h - definitions for the Internet Transmission Control Protocol (TCP)

SYNOPSIS

#include <netinet/tcp.h>

DESCRIPTION

The <netinet/tcp.h> header shall define the following macro for use as a socket option at the IPPROTO_TCP level:

TCP_NODELAY
Avoid coalescing of small segments.

The macro shall be defined in the header. The implementation need not allow the value of the option to be set via setsockopt() or retrieved via getsockopt().

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

<sys/socket.h> , the System Interfaces volume of IEEE Std 1003.1-2001, getsockopt(), setsockopt()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iconv.h(0p)

<iconv.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iconv.h - codeset conversion facility

SYNOPSIS

#include <iconv.h>

DESCRIPTION

The <iconv.h> header shall define the following type:

iconv_t
Identifies the conversion from one codeset to another.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

iconv_t iconv_open(const char *, const char *);
size_t  iconv(iconv_t, char **restrict, size_t *restrict,
            char **restrict, size_t *restrict);
int     iconv_close(iconv_t);

The following sections are informative.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, iconv(), iconv_close(), iconv_open()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


inttypes.h(0p)

<inttypes.h>

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

inttypes.h - fixed size integer types

SYNOPSIS

#include <inttypes.h>

DESCRIPTION

Some of the functionality described on this reference page extends the ISO C standard. Applications shall define the appropriate feature test macro (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.2, The Compilation Environment) to enable the visibility of these symbols in this header.

The <inttypes.h> header shall include the <stdint.h> header.

The <inttypes.h> header shall include a definition of at least the following type:

imaxdiv_t
Structure type that is the type of the value returned by the imaxdiv() function.

The following macros shall be defined. Each expands to a character string literal containing a conversion specifier, possibly modified by a length modifier, suitable for use within the format argument of a formatted input/output function when converting the corresponding integer type. These macros have the general form of PRI (character string literals for the fprintf() and fwprintf() family of functions) or SCN (character string literals for the fscanf() and fwscanf() family of functions), followed by the conversion specifier, followed by a name corresponding to a similar type name in <stdint.h>. In these names, N represents the width of the type as described in <stdint.h>. For example, PRIdFAST32 can be used in a format string to print the value of an integer of type int_fast32_t.

The fprintf() macros for signed integers are:
PRIdN | PRIdLEASTN | PRIdFASTN | PRIdMAX | PRIdPTR
PRIiN | PRIiLEASTN | PRIiFASTN | PRIiMAX | PRIiPTR

The fprintf() macros for unsigned integers are:
PRIoN | PRIoLEASTN | PRIoFASTN | PRIoMAX | PRIoPTR
PRIuN | PRIuLEASTN | PRIuFASTN | PRIuMAX | PRIuPTR
PRIxN | PRIxLEASTN | PRIxFASTN | PRIxMAX | PRIxPTR
PRIXN | PRIXLEASTN | PRIXFASTN | PRIXMAX | PRIXPTR

The fscanf() macros for signed integers are:
SCNdN | SCNdLEASTN | SCNdFASTN | SCNdMAX | SCNdPTR
SCNiN | SCNiLEASTN | SCNiFASTN | SCNiMAX | SCNiPTR

The fscanf() macros for unsigned integers are:
SCNoN | SCNoLEASTN | SCNoFASTN | SCNoMAX | SCNoPTR
SCNuN | SCNuLEASTN | SCNuFASTN | SCNuMAX | SCNuPTR
SCNxN | SCNxLEASTN | SCNxFASTN | SCNxMAX | SCNxPTR

For each type that the implementation provides in <stdint.h>, the corresponding fprintf() and fwprintf() macros shall be defined and the corresponding fscanf() and fwscanf() macros shall be defined unless the implementation does not have a suitable modifier for the type.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

intmax_t  imaxabs(intmax_t);
imaxdiv_t imaxdiv(intmax_t, intmax_t);
intmax_t  strtoimax(const char *restrict, char **restrict, int);
uintmax_t strtoumax(const char *restrict, char **restrict, int);
intmax_t  wcstoimax(const wchar_t *restrict, wchar_t **restrict, int);
uintmax_t wcstoumax(const wchar_t *restrict, wchar_t **restrict, int);

EXAMPLES

#include <inttypes.h>
#include <wchar.h>
int main(void)
{
    uintmax_t i = UINTMAX_MAX; // This type always exists.
    wprintf(L"The largest integer value is %020"
        PRIxMAX "\n", i);
    return 0;
}

The following sections are informative.

APPLICATION USAGE

The purpose of <inttypes.h> is to provide a set of integer types whose definitions are consistent across machines and independent of operating systems and other implementation idiosyncrasies. It defines, via typedef, integer types of various sizes. Implementations are free to typedef them as ISO C standard integer types or extensions that they support. Consistent use of this header will greatly increase the portability of applications across platforms.

RATIONALE

The ISO/IEC 9899:1990 standard specified that the language should support four signed and unsigned integer data types- char, short, int, and long- but placed very little requirement on their size other than that int and short be at least 16 bits and long be at least as long as int and not smaller than 32 bits. For 16-bit systems, most implementations assigned 8, 16, 16, and 32 bits to char, short, int, and long, respectively. For 32-bit systems, the common practice has been to assign 8, 16, 32, and 32 bits to these types. This difference in int size can create some problems for users who migrate from one system to another which assigns different sizes to integer types, because the ISO C standard integer promotion rule can produce silent changes unexpectedly. The need for defining an extended integer type increased with the introduction of 64-bit systems.

FUTURE DIRECTIONS

Macro names beginning with PRI or SCN followed by any lowercase letter or 'X' may be added to the macros defined in the <inttypes.h> header.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, imaxdiv()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ipc.h(0p)

Status: 403 Forbidden ipc.h(0p)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man0p/ipc.h.0p is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


dd(1)

DD

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

dd - convert and copy a file

SYNOPSIS

dd [--help] [--version] [if=file] [of=file] [ibs=bytes] [obs=bytes] [bs=bytes] [cbs=bytes] [skip=blocks] [seek=blocks] [count=blocks] [conv={ascii, ebcdic, ibm, block, unblock, lcase, ucase, swab, noerror, notrunc, sync}]

DESCRIPTION

dd copies a file (from standard input to standard output, by default) using specific input and output blocksizes, while optionally performing conversions on it.

It reads the input one block at a time, using the specified input block size (the default is 512 bytes). If the bs=bytes option was given, and no conversion other than sync, noerror, or notrunc was specified, it writes the amount of data read (which could be smaller than what was requested) in a separate output block. This output block has precisely the same length as was read unless the sync conversion was specified, in which case the data is padded with NULs (or spaces, see below).

Otherwise, the input, read one block at a time, is processed and the resulting output is collected and written in blocks of the specified output block size. The final output block may be shorter.

The numeric-valued options below (bytes and blocks) can be followed by a multiplier: `k'=1024, `b'=512, `w'=2, `c'=1 (`w' and `c' are GNU extensions; `w' should never be used - it means 2 in System V and 4 in 4.2BSD). Two or more of such numeric expressions can be multiplied by putting `x' in between. The GNU fileutils-4.0 version also allows the following multiplicative suffixes in the specification of blocksizes (in bs=, cbs=, ibs=, obs=): M=1048576, G=1073741824, and so on for T, P, E, Z, Y. A `D' suffix makes them decimal: kD=1000, MD=1000000, GD=1000000000, etc. (Note that for ls, df, du the size of M etc. is determined by environment variables, but for dd it is fixed.)

OPTIONS

if=file
Read from file instead of standard input.
of=file
Write to file instead of standard output. Unless conv=notrunc is given, dd truncates file to zero bytes (or the size specified with seek=).
ibs=bytes
Read bytes bytes at a time. The default is 512.
obs=bytes
Write bytes bytes at a time. The default is 512.
bs=bytes
Both read and write bytes bytes at a time. This overrides ibs and obs. (And setting bs is not equivalent with setting both ibs and obs to this same value, at least when no conversion other than sync, noerror and notrunc is specified, since it stipulates that each input block shall be copied to the output as a single block without aggregating short blocks.)
cbs=bytes
Specify the conversion block size for block and unblock.
skip=blocks
Skip blocks ibs-byte blocks in the input file before copying.
seek=blocks
Skip blocks obs-byte blocks in the output file before copying.
count=blocks
Copy blocks ibs-byte blocks from the input file, instead of everything until the end of the file.
conv=CONVERSION[,CONVERSION]...
Convert the file as specified by the CONVERSION argument(s). (No spaces around any comma(s).)

Conversions:

ascii
Convert EBCDIC to ASCII.
ebcdic
Convert ASCII to EBCDIC.
ibm
Convert ASCII to alternate EBCDIC.
block
For each line in the input, output cbs bytes, replacing the input newline with a space and padding with spaces as necessary.
unblock
Replace trailing spaces in each cbs-sized input block with a newline.
lcase
Change uppercase letters to lowercase.
ucase
Change lowercase letters to uppercase.
swab
Swap every pair of input bytes. If an odd number of bytes are read the last byte is simply copied (since there is nothing to swap it with). [POSIX 1003.2b, PASC interpretations 1003.2 #3 and #4]
noerror
Continue after read errors.
notrunc
Do not truncate the output file.
sync
Pad every input block to size of ibs with trailing zero bytes.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2

EXAMPLE

Often a tape drive will not accept arbitrarily sized blocks, and dd would get an I/O error for the last fragment of data that does not fill an entire block. Use `dd if=myfile of=/dev/mytape conv=sync' to get everything on tape. Of course, reading it back will now produce a slightly larger file, with nulls added at the end.

BUGS

Commands like `dd if=myfile of=/dev/fd0 bs=1k seek=172' fail on some systems because dd tries to truncate the output file, but truncation of a block device is not possible. In such cases, add the `conv=notrunc' option.

NOTES

This page describes dd as found in the fileutils-4.0 package; other versions may differ slightly.


ls(1)

LS

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

ls, dir, vdir - list directory contents

SYNOPSIS

ls [options] [file...]
dir [file...]
vdir [file...]

POSIX options: [-CFRacdilqrtu1] [--]

GNU options (shortest form):
[-1abcdfghiklmnopqrstuvwxABCDFGHLNQRSUX]

[-w cols]

[-T cols]

[-I pattern]

[--full-time]

[--show-control-chars]

[--block-size=size]

[--format={long,verbose,commas,across,vertical,single-column}]

[--sort={none,time,size,extension}]

[--time={atime,access,use,ctime,status}]

[--color[={none,auto,always}]]

[--help] [--version] [--]

DESCRIPTION

The program ls lists first its non-directory file arguments, and then for each directory argument all listable files contained within that directory. If no non-option arguments are present, a default argument `.' (the current directory) is assumed. The -d option causes directories to be treated as non-directory arguments. A file is listable when either its name does not start with `.', or the -a option is given.

Each of the lists of files (that of non-directory files, and for each directory the list of files inside) is sorted separately according to the collating sequence in the current locale. When the -l option is given, each list is preceded by a summary line giving the total size of all files in the list, measured in 512-byte or 1024-byte blocks.

The output is to stdout, one entry per line, unless multicolumn output is requested by the -C option. However, for output to a terminal, it is undefined whether the output will be single-column or multi-column. The options -1 and -C can be used to force single-column and multi-column output, respectively.

POSIX OPTIONS

-C
List files in columns, sorted vertically.
-F
Suffix each directory name with `/', each FIFO name with `|', and each name of an executable with `*'.
-R
Recursively list subdirectories encountered.
-a
Include files with a name starting with `.' in the listing.
-c
Use the status change time instead of the modification time for sorting (with -t) or listing (with -l).
-d
List names of directories like other files, rather than listing their contents.
-i
Precede the output for the file by the file serial number (i-node number).
-l
Write (in single-column format) the file mode, the number of links to the file, the owner name, the group name, the size of the file (in bytes), the timestamp, and the filename. The summary line uses 512-byte units.

The file types are as follows: - for an ordinary file, d for a directory, b for a block special device, c for a character special device, l for a symbolic link, p for a fifo, s for a socket.

By default, the timestamp shown is that of the last modification; the options -c and -u select the other two timestamps. For device special files the size field is commonly replaced by the major and minor device numbers.

-q
Output nonprintable characters in a filename as question marks. (This is permitted to be the default for output to a terminal.)
-r
Reverse the order of the sort.
-t
Sort by the timestamp shown.
-u
Use the time of last access instead of the modification time for sorting (with -t) or listing (with -l).
-1
For single-column output.
--
Terminate option list.

GNU DETAILS

If standard output is a terminal, the output is in columns (sorted vertically).

dir (also installed as d) is equivalent to `ls -C -b'; that is, files are by default listed in columns, sorted vertically. vdir (also installed as v) is equivalent to `ls -l -b'; that is, files are by default listed in long format.

GNU OPTIONS

-1, --format=single-column
List one file per line. This is the default for when standard output is not a terminal.
-a, --all
List all files in directories, including all files that start with `.'.
-b, --escape, --quoting-style=escape
Quote nongraphic characters in file names using alphabetic and octal backslash sequences like those used in C. This option is the same as -Q except that filenames are not surrounded by double-quotes.
-c, --time=ctime, --time=status
Sort directory contents according to the files' status change time (the `ctime' in the inode). If the long listing format is being used (-l) print the status change time instead of the modification time.
-d, --directory
List names of directories like other files, rather than listing their contents.
-f
Do not sort directory contents; list them in whatever order they are stored on the disk. Also enables -a and -U and disables -l, --color, -s, and -t if they were specified before the -f.
-g
Ignored; for Unix compatibility.
-h, --human-readable
Append a size letter, such as M for binary megabytes (`mebibytes'), to each size. (New in fileutils-4.0.)
-i, --inode
Print the inode number (also called the file serial number and index number) of each file to the left of the file name. (This number uniquely identifies each file within a particular filesystem)
-k, --kilobytes
If file sizes are being listed, print them in kilobytes.
-l, --format=long, --format=verbose
In addition to the name of each file, print the file type, permissions, number of hard links, owner name, group name, size in bytes, and timestamp (the modification time unless other times are selected). For files with a time that is more than 6 months old or more than 1 hour into the future, the timestamp contains the year instead of the time of day.

For each directory that is listed, preface the files with a line `total blocks', where blocks is the total disk space used by all files in that directory. By default, 1024-byte blocks are used; if the environment variable POSIXLY_CORRECT is set, 512-byte blocks are used (unless the -k option is given). The blocks computed counts each hard link separately; this is arguably a deficiency.

The permissions listed are similar to symbolic mode specifications but ls combines multiple bits into the third character of each set of permissions

s
If the setuid or setgid bit and the corresponding executable bit are both set.
S
If the setuid or setgid bit is set but the corresponding executable bit is not set.
t
If the sticky bit and the other-executable bit are both set.
T
If the sticky bit is set but the other-executable bit is not set.
x
If the executable bit is set and none of the above apply.
-
Otherwise.
-m, --format=commas
List files horizontally, with as many as will fit on each line, each separated by a comma and a space.
-n, --numeric-uid-gid
List the numeric UID and GID instead of the names.
-o
Produce long format directory listings, but don't display group information. It is equivalent to using --format=long --no-group. This option is provided for compatibility with other versions of ls.
-p, --file-type, --indicator-style=file-type
Append a character to each file name indicating the file type. This is like -F except that executables aren't marked. (In fact fileutils-4.0 treats the --file-type option like --classify.)
-q, --hide-control-chars
Print question marks instead of nongraphic characters in file names. This is the default.
-r, --reverse
Sort directory contents in reverse order.
-s, --size
Print the size of each file in 1024-byte blocks to the left of the file name. If the environment variable POSIXLY_CORRECT is set, 512-byte blocks are used instead, unless the -k option is given.
-t, --sort=time
Sort by modification time (the `mtime' in the inode) instead of alphabetically, with the newest files listed first.
-u, --time=atime, --time=access, --time=use
Sort directory contents according to the files' last access time instead of the modification time (the `atime' in the inode). If the long listing format is being used, print the last access time instead of the modification time.
-v
Sort directory contents according to the files' version. This takes into account the fact that filenames frequently include indices or version numbers. Standard sorting functions usually do not produce the ordering that people expect because comparisons are made on a character-by-character basis. The version sort addresses this problem, and is especially useful when browsing directories that contain many files with indices/version numbers in their names. For example:

     > ls -1            > ls -1v
     foo.zml-1.gz       foo.zml-1.gz
     foo.zml-100.gz     foo.zml-12.gz
     foo.zml-12.gz      foo.zml-25.gz
     foo.zml-25.gz      foo.zml-100.gz

Note also that numeric parts with leading zeroes are considered as fractional:

     > ls -1            > ls -1v
     abc-1.007.tgz      abc-1.007.tgz
     abc-1.012b.tgz     abc-1.01a.tgz
     abc-1.01a.tgz      abc-1.012b.tgz

(New in fileutils-4.0.)

-w, --width cols
Assume the screen is cols columns wide. The default is taken from the terminal driver if possible; otherwise the environment variable COLUMNS is used if it is set; otherwise the default is 80.
-x, --format=across, --format=horizontal
List the files in columns, sorted horizontally.
-A, --almost-all
List all files in directories, except for `.' and `..'.
-B, --ignore-backups
Do not list files that end with `~', unless they are given on the command line.
-C, --format=vertical
List files in columns, sorted vertically. This is the default if standard output is a terminal. It is always the default for dir and d.
-D, --dired
With the long listing (-l) format, print an additional line after the main output:
//DIRED// BEG1 END1 BEG2 END2 ...

The BEGn and ENDn are unsigned integers which record the byte position of the beginning and end of each file name in the output. This makes it easy for Emacs to find the names, even when they contain unusual characters such as space or newline, without fancy searching.

If directories are being listed recursively (-R), output a similar line after each subdirectory:
//SUBDIRED// BEG1 END1 ...

-F, --classify, --indicator-style=classify
Append a character to each file name indicating the file type. For regular files that are executable, append a `*'. The file type indicators are `/' for directories, `@' for symbolic links, `|' for FIFOs, `=' for sockets, and nothing for regular files.
-G, --no-group
Inhibit display of group information in a long format directory listing.
-H, --si
Do the same as for -h, but use the official SI units (with powers of 1000 instead of 1024, so that M stands for 1000000 instead of 1048576). (New in fileutils-4.0.)
-I, --ignore=pattern
Do not list files whose names match the shell pattern pattern (not regular expression) unless they are given on the command line. As in the shell, an initial `.' in a filename does not match a wildcard at the start of pattern. For simple-minded root-kits: add LS_OPTIONS="$LS_OPTIONS -I mystuff" in /etc/profile or so, to hide your directories.
-L, --dereference
List the file information corresponding to the referrents of symbolic links rather for the links themselves.
-N, --literal
Do not quote file names.
-Q, --quote-name, --quoting-style=c
Enclose file names in double quotes and quote nongraphic characters as in C.
-R, --recursive
List the contents of all directories recursively.
-S, --sort=size
Sort directory contents by file size instead of alphabetically, with the largest files listed first.
-T, --tabsize cols
Assume that each tabstop is cols columns wide. The default is 8 and can be overridden by the environment variable TABSIZE when POSIXLY_CORRECT is not set. ls uses tabs where possible in the output, for efficiency. If cols is zero, do not use tabs at all.
-U, --sort=none
Do not sort directory contents; list them in whatever order they are stored on the disk. (The difference between -U and -f is that the former doesn't disable or enable options.) This is especially useful when listing very large directories, since not doing any sorting can be noticeably faster.
-X, --sort=extension
Sort directory contents alphabetically by file extension (characters after the last `.'); files with no extension are sorted first.
--block-size=size
Print sizes in blocks of size bytes. (New in fileutils-4.0.)
--color[=when]
Specify whether to use color for distinguishing file types. Colors are specified using the LS_COLORS environment variable. For information on how to set this variable, see dircolors(1). when may be omitted, or one of:
none
Do not use color at all. This is the default.
auto
Only use color if standard output is a terminal.
always
Always use color. Specifying --color and no when is equivalent to --color=always.
--full-time
List times in full, rather than using the standard abbreviation heuristics. The format is the same as date(1)'s default; it's not possible to change this, but you can extract out the date string with cut(1) and then pass the result to `date -d'.

This is most useful because the time output includes the seconds. (Unix filesystems store file timestamps only to the nearest second, so this option shows all the information there is.) For example, this can help when you have a Makefile that is not regenerating files properly.

--quoting-style=word
Use style word to quote output names. The word should be one of the following:
literal
Output names as-is. This is the default behavior of ls.
shell
Quote names for the shell if they contain shell metacharacters or would cause ambiguous output.
shell-always
Quote names for the shell, even if they would normally not require quoting.
c
Quote names as for a C language string; this is the same as the -Q option.
escape
Quote as with c except omit the surrounding double-quote characters; this is the same as the -b option.

A default value for this option can be specified with the environment variable QUOTING_STYLE. (See ENVIRONMENT below.)

--show-control-chars
Print nongraphic characters as-is in file names. This is the default unless the output is a terminal and the program is ls.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variable POSIXLY_CORRECT determines the choice of unit. If it is not set, then the variable TABSIZE determines the number of chars per tab stop. The variable COLUMNS (when it contains the representation of a decimal integer) determines the output column width (for use with the -C option). Filenames must not be truncated to make them fit a multi-column output.

The variables LANG, LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES and LC_TIME have the usual meaning. The variable TZ gives the time zone for time strings written by ls. The variable LS_COLORS is used to specify the colors used. The variable LS_OPTIONS gives default options.

The variable QUOTING_STYLE is used to specify the default value for the --quoting-style option. It currently defaults to literal, though the authors have warned that this default may change to shell in some future version of ls.

BUGS

On BSD systems, the -s option reports sizes that are half the correct values for files that are NFS-mounted from HP-UX systems. On HP-UX systems, ls reports sizes that are twice the correct values for files that are NFS-mounted from BSD systems. This is due to a flaw in HP-UX; it also affects the HP-UX ls program.

CONFORMING TO

POSIX 1003.2

SEE ALSO

dircolors(1)

NOTES

This page describes ls as found in the fileutils-4.0 package; other versions may differ slightly.


intro(1)

INTRO

Section: Linux User's Manual (1)
Updated: 2002-08-06 Return to Main Contents

NAME

intro - Introduction to user commands

DESCRIPTION

Linux is a flavor of Unix, and as a first approximation all user commands under Unix work precisely the same under Linux (and FreeBSD and lots of other Unix-like systems).

Under Linux there are GUIs (graphical user interfaces), where you can point and click and drag, and hopefully get work done without first reading lots of documentation. The traditional Unix environment is a CLI (command line interface), where you type commands to tell the computer what to do. That is faster and more powerful, but requires finding out what the commands are. Below a bare minimum, to get started.

Login

In order to start working, you probably first have to login, that is, give your username and password. See also login(1). The program login now starts a shell (command interpreter) for you. In case of a graphical login, you get a screen with menus or icons and a mouse click will start a shell in a window. See also xterm(1).

The shell

One types commands to the shell, the command interpreter. It is not built-in, but is just a program and you can change your shell. Everybody has her own favorite one. The standard one is called sh. See also ash(1), bash(1), csh(1), zsh(1), chsh(1).

A session might go like

knuth login: aeb
Password: ********
% date
Tue Aug  6 23:50:44 CEST 2002
% cal
     August 2002
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

% ls
bin  tel
% ls -l
total 2
drwxrwxr-x   2 aeb       1024 Aug  6 23:51 bin
-rw-rw-r--   1 aeb         37 Aug  6 23:52 tel
% cat tel
maja    0501-1136285
peter   0136-7399214
% cp tel tel2
% ls -l
total 3
drwxr-xr-x   2 aeb       1024 Aug  6 23:51 bin
-rw-r--r--   1 aeb         37 Aug  6 23:52 tel
-rw-r--r--   1 aeb         37 Aug  6 23:53 tel2
% mv tel tel1
% ls -l
total 3
drwxr-xr-x   2 aeb       1024 Aug  6 23:51 bin
-rw-r--r--   1 aeb         37 Aug  6 23:52 tel1
-rw-r--r--   1 aeb         37 Aug  6 23:53 tel2
% diff tel1 tel2
% rm tel1
% grep maja tel2
maja    0501-1136285
%
and here typing Control-D ended the session. The % here was the command prompt --- it is the shell's way of indicating that it is ready for the next command. The prompt can be customized in lots of ways, and one might include stuff like user name, machine name, current directory, time, etc. An assignment PS1="What next, master? " would change the prompt as indicated.

We see that there are commands date (that gives date and time), and cal (that gives a calendar).

The command ls lists the contents of the current directory --- it tells you what files you have. With a -l option it gives a long listing, that includes the owner and size and date of the file, and the permissions people have for reading and/or changing the file. For example, the file "tel" here is 37 bytes long, owned by aeb and the owner can read and write it, others can only read it. Owner and permissions can be changed by the commands chown and chmod.

The command cat will show the contents of a file. (The name is from "concatenate and print": all files given as parameters are concatenated and sent to "standard output", here the terminal screen.)

The command cp (from "copy") will copy a file. On the other hand, the command mv (from "move") only renames it.

The command diff lists the differences between two files. Here there was no output because there were no differences.

The command rm (from "remove") deletes the file, and be careful! it is gone. No wastepaper basket or anything. Deleted means lost.

The command grep (from "g/re/p") finds occurrences of a string in one or more files. Here it finds Maja's telephone number.

Pathnames and the current directory

Files live in a large tree, the file hierarchy. Each has a pathname describing the path from the root of the tree (which is called /) to the file. For example, such a full pathname might be /home/aeb/tel. Always using full pathnames would be inconvenient, and the name of a file in the current directory may be abbreviated by only giving the last component. That is why "/home/aeb/tel" can be abbreviated to "tel" when the current directory is "/home/aeb".

The command pwd prints the current directory.

The command cd changes the current directory. Try "cd /" and "pwd" and "cd" and "pwd".

Directories

The command mkdir makes a new directory.

The command rmdir removes a directory if it is empty, and complains otherwise.

The command find (with a rather baroque syntax) will find files with given name or other properties. For example, "find . -name tel" would find the file "tel" starting in the present directory (which is called "."). And "find / -name tel" would do the same, but starting at the root of the tree. Large searches on a multi-GB disk will be time-consuming, and it may be better to use locate(1).

Disks and Filesystems

The command mount will attach the filesystem found on some disk (or floppy, or CDROM or so) to the big filesystem hierarchy. And umount detaches it again. The command df will tell you how much of your disk is still free.

Processes

On a Unix system many user and system processes run simultaneously. The one you are talking to runs in the foreground, the others in the background. The command ps will show you which processes are active and what numbers these processes have. The command kill allows you to get rid of them. Without option this is a friendly request: please go away. And "kill -9" followed by the number of the process is an immediate kill. Foreground processes can often be killed by typing Control-C.

Getting information

There are thousands of commands, each with many options. Traditionally commands are documented on man pages, (like this one), so that the command "man kill" will document the use of the command "kill" (and "man man" document the command "man"). The program man sends the text through some pager, usually less. Hit the space bar to get the next page, hit q to quit.

In documentation it is customary to refer to man pages by giving the name and section number, as in man(1). Man pages are terse, and allow you to find quickly some forgotten detail. For newcomers an introductory text with more examples and explanations is useful.

A lot of GNU/FSF software is provided with info files. Type "info info" for an introduction on the use of the program "info".

Special topics are often treated in HOWTOs. Look in /usr/share/doc/howto/en and use a browser if you find HTML files there.

SEE ALSO

standards(7)


df(1)

DF

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

df - report filesystem disk space usage

SYNOPSIS

df [options] [file...]

POSIX options: [-kP] [--]

GNU options (shortest form):
[-ahHiklmPv]

[-t fstype]

[-x fstype]

[--block-size=size]

[--print-type]

[--no-sync]

[--sync]

[--help] [--version] [--]

DESCRIPTION

df reports the amount of disk space used and available on filesystems.

With no arguments, df reports the space used and available on all currently mounted filesystems (of all types). Otherwise, df reports on the filesystem containing each argument file.

POSIX DETAILS

The output is in 512-byte units by default, but in 1024-byte units when the -k option is given. The output format is undefined, unless the -P option is given. If file is not a regular file, a directory or a FIFO, the result is unspecified.

GNU DETAILS

The output is in 1024-byte units (when no units are specified by options), unless the environment variable POSIXLY_CORRECT is set, in which case POSIX is followed.

If an argument file is a disk device file containing a mounted filesystem, df shows the space available on that filesystem rather than on the filesystem containing the device node.

POSIX OPTIONS

-k
Use 1024-byte units instead of the default 512-byte units.
-P
Output in six columns, with heading `Filesystem N-blocks Used Available Capacity Mounted on' (with N=512, but N=1024 when the -k option is given).
--
Terminate option list.

GNU OPTIONS

-a, --all
Include in the listing filesystems that have a size of 0 blocks, which are omitted by default. Such filesystems are typically special-purpose pseudo-filesystems, such as automounter entries. Also, filesystems of type "ignore" or "auto", supported by some operating systems, are only included if this option is specified.
--block-size=size
Print sizes in blocks of size bytes. (New but broken in fileutils-4.0.)
-h, --human-readable
Append a size letter such as M for binary megabytes (`mebibytes') to each size.
-H, --si
Do the same as for -h, but use the official SI units (with powers of 1000 instead of 1024, so that M stands for 1000000 instead of 1048576). (New in fileutils-4.0.)
-i, --inodes
List inode usage information instead of block usage. An inode (short for index node) contains information about a file such as its owner, permissions, timestamps, and location on the disk.
-k, --kilobytes
Print sizes in 1024-byte blocks.
-l, --local
Limit the output to local filesystems only. (New in fileutils-4.0.)
-m, --megabytes
Print sizes in binary megabyte (that's 1048576 bytes) blocks. Note that the four options -h, -H, -k, -m are mutually exclusive and only the last one is effective; for example, it is not the case that giving both the --si and -m options would result in output in (actual, 1000000-byte) megabytes. [The interpretation of blocksizes is also influenced by the environment variable BLOCK_SIZE, but this does not work in the fileutils-4.0 version.]
--no-sync
Do not invoke the sync system call before getting any usage data. This may make df run significantly faster, but on some systems (notably SunOS) the results may be slightly out of date. This is the default.
-P, --portability
Use the POSIX output format. This is like the default format except that the information about each filesystem is always printed on exactly one line; a mount device is never put on a line by itself. This means that if the mount device name is more than 20 characters long (e.g., for some network mounts), the columns are misaligned.
--sync
Invoke the sync system call before getting any usage data. On some systems (notably SunOS), doing this yields more up to date results, but in general this option makes df much slower, especially when there are many or very busy filesystems.
-t fstype, --type=fstype
Limit the listing to filesystems of type fstype. Multiple filesystem types can be specified by giving multiple -t options. By default, nothing is omitted.
-T, --print-type
Print each filesystem's type. The types given are those reported by the system (and are found in a system-dependent way, for example by reading /etc/mtab). See also mount(8).
-x fstype, --exclude-type=fstype
Limit the listing to filesystems not of type fstype. Multiple filesystem types can be eliminated by giving multiple -x options. By default, no filesystem types are omitted.
-v
Ignored; for compatibility with System V versions of df.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variable POSIXLY_CORRECT determines the choice of unit. If it is not set, and the variable BLOCKSIZE has a value starting with `HUMAN', then behaviour is as for the -h option, unless overridden by -k or -m options. The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2

SEE ALSO

mount(8)

NOTES

This page describes df as found in the fileutils-4.0 package; other versions may differ slightly.


chmod(1)

CHMOD

Section: User Commands (1)
Updated: 2004-06-17 Return to Main Contents

NAME

chmod - change access permissions of files

SYNOPSIS

chmod [options] mode file...

POSIX options: [-R] [--]

GNU mode denotation: [--reference=rfile]

GNU options (shortest form): [-cfvR] [--help] [--version] [--]

DESCRIPTION

chmod changes the permissions of each given file according to mode, which can be either a symbolic representation of changes to make, or an octal number representing the bit pattern for the new permissions.

The format of a symbolic mode change argument is
`[ugoa...][[+-=][rwxXstugo...]...][,...]'.

Such an argument is a list of symbolic mode change commands, separated by commas. Each symbolic mode change command starts with zero or more of the letters `ugoa'; these control which users' access to the file will be changed: the user who owns it (u), other users in the file's group (g), other users not in the file's group (o), or all users (a). Thus, `a' is here equivalent to `ugo'. If none of these are given, the effect is as if `a' were given, but bits that are set in the umask are not affected.

The operator `+' causes the permissions selected to be added to the existing permissions of each file; `-' causes them to be removed; and `=' causes them to be the only permissions that the file has.

The letters `rwxXstugo' select the new permissions for the affected users: read (r), write (w), execute (or access for directories) (x), execute only if the file is a directory or already has execute permission for some user (X), set user or group ID on execution (s), sticky bit (t), the permissions that the user who owns the file currently has for it (u), the permissions that other users in the file's group have for it (g), and the permissions that other users not in the file's group have for it (o). (Thus, `chmod g-s file' removes the set-group-ID (sgid) bit, `chmod ug+s file' sets both the suid and sgid bits, while `chmod o+s file' does nothing.)

The name of the `sticky bit' derives from the original meaning: keep program text on swap device. These days, when set for a directory, it means that only the owner of the file and the owner of that directory may remove the file from that directory. (This is commonly used on directories like /tmp that have general write permission.)

A numeric mode is from one to four octal digits (0-7), derived by adding up the bits with values 4, 2, and 1. Any omitted digits are assumed to be leading zeros. The first digit selects the set user ID (4) and set group ID (2) and save text image [`sticky'] (1) attributes. The second digit selects permissions for the user who owns the file: read (4), write (2), and execute (1); the third selects permissions for other users in the file's group, with the same values; and the fourth for other users not in the file's group, with the same values.

chmod never changes the permissions of symbolic links, since the chmod system call cannot change their permissions. This is not a problem since the permissions of symbolic links are never used. However, for each symbolic link listed on the command line, chmod changes the permissions of the pointed-to file. In contrast, chmod ignores symbolic links encountered during recursive directory traversals.

POSIX OPTIONS

-R
Recursively change permissions of directories and their contents.
--
Terminate option list.

ADDITIONAL GNU DESCRIPTION

A GNU extension (new in fileutils 4.0) allows one to use --reference=rfile as a mode description: the same mode as that of rfile.

GNU OPTIONS

-c, --changes
Verbosely describe the action for each file whose permissions actually changes.
-f, --silent, --quiet
Do not print error messages about files whose permissions cannot be changed.
-v, --verbose
Verbosely describe the action or non-action taken for every file.
-R, --recursive
Recursively change permissions of directories and their contents.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning. For an XSI-conforming system: NLSPATH has the usual meaning.

CONFORMING TO

POSIX 1003.2 only requires the -R option. Use of other options may not be portable. This standard does not describe the 't' permission bit. This standard does not specify whether chmod must preserve consistency by clearing or refusing to set the suid and sgid bits, e.g., when all execute bits are cleared, or whether chmod honors the `s' bit at all.

NONSTANDARD MODES

Above we described the use of the `t' bit on directories. Various systems attach special meanings to otherwise meaningless combinations of mode bits. In particular, Linux, following System V (see System V Interface Definition (SVID) Version 3), lets the sgid bit for files without group execute permission mark the file for mandatory locking. For more details, see the file /usr/src/linux/Documentation/mandatory.txt.

NOTES

This page describes chmod as found in the fileutils-4.0 package; other versions may differ slightly.

SEE ALSO

chattr(1), chown(1), install(1), chmod(2), stat(2), umask(2)


cp(1)

CP

Section: User Commands (1)
Updated: 2003-11 Return to Main Contents

NAME

cp - copy files and directories

SYNOPSIS

cp [options] file path
cp [options] file... directory

POSIX options: [-fiprR] [--]

Additional POSIX 1003.1-2003 options: [-HLP]

GNU file-utils 4.0 options (shortest form):
[-abdfilprsuvxPR]

[-S SUFFIX]

[-V {numbered,existing,simple}]

[--backup=CONTROL]

[--sparse=WHEN]

[--help] [--version] [--]

Additional GNU file-utils 4.1 options (shortest form):
[-HLP]

[--copy-contents]

[--no-preserve]

[--reply=HOW]

[--remove-destination]

[--strip-trailing-slashes]

[--target-directory=DIR]

DESCRIPTION

cp copies files (or, optionally, directories). You can either copy one file to a given destination, or copy arbitrarily many files to a destination directory.

If the last argument names an existing directory, cp copies each source file into that directory (retaining the same name). Otherwise, if only two files are given, it copies the first onto the second. It is an error if the last argument is not a directory and more than two non-option arguments are given.

(Thus, if /a is a directory, then `cp -r /a /b' will copy /a to /b/a and /a/x to /b/a/x in case a directory /b existed already, but it will copy /a to /b and /a/x to /b/x if there was no /b beforehand, while it will fail in case there was an ordinary file /b.)

The modes of the files and directories created will be the same as those of the original files, ANDed by 0777, and modified by the user's umask (unless the -p option was specified). (But during the recursive copy of directories, newly created directories will temporarily get their final mode ORed with S_IRWXU (0700), so as to allow the process to read, write and search the newly created directory.)

Nothing is done when copying a file to itself (except possibly producing an error message). When copying to a different existing file, it is opened using `open(path, O_WRONLY | O_TRUNC)'. When copying to a new file it is created using `open(path, O_WRONLY | O_CREAT, mode)'. If this fails, the file existed, and the -f option was given, cp tries to delete (unlink) the existing file, and if this succeeds proceeds as for a new file.

POSIX OPTIONS

POSIX recognizes four options and a half:
-f
Remove existing destination files if required. (See above.)
-i
Prompt whether to overwrite existing regular destination files. (Write a question on stderr, and read the answer from stdin. Only copy upon an affirmative answer.)
-p
Preserve the original files' owner, group, permissions (including the setuid and setgid bits), time of last modification and time of last access. In case duplication of owner or group fails, the setuid and setgid bits are cleared. (Note that afterwards source and copy may well have different times of last access, since the copy operation is an access to the source file.)
-R
Copy directories recursively, and do the right thing when objects other than ordinary files or directories are encountered. (Thus, the copy of a FIFO or special file is a FIFO or special file.)
-r
Copy directories recursively, and do something unspecified with objects other than ordinary files or directories. (Thus, it is allowed, in fact encouraged, to have the -r option a synonym for -R. However, silly behaviour, like that of the GNU 4.0 version of cp is not forbidden.)
--
Terminate option list.

ADDITIONAL POSIX 2003 OPTIONS

POSIX 1003.1-2003 adds three options that specify how to handle symbolic links. When doing a non-recursive copy, symbolic links are followed. When doing a recursive copy using the -r option, the results are implementation-defined. When doing a recursive copy using the -R option:
-H
Follow the symbolic links given in the parameter list. Do not follow symbolic links encountered during the recursive copy, but just copy them as symbolic link.
-L
Follow all symbolic links, both those that occur in the parameter list and those encountered during the recursive copy.
-P
Do not follow any symbolic links, neither those that occur in the parameter list nor those encountered during the recursive copy. Just copy them as symbolic link.

There is no default - one should specify the desired behaviour.

GNU DETAILS

Generally, files are written just as they are read. For exceptions, see the --sparse option below.

By default, `cp' does not copy directories (see -r below).

cp generally refuses to copy a file onto itself, with the following exception: if --force --backup is specified with source and dest identical, and referring to a regular file, cp will make a backup file, either regular or numbered, as specified in the usual ways. This is useful when you simply want to make a backup of an existing file before changing it.

By default, symbolic links are not followed.

GNU OPTIONS

-a, --archive
Preserve as much as possible of the structure and attributes of the original files in the copy (but do not preserve directory structure). Equivalent to -dpPR.
-b
See the discussion of backups below.
--copy-contents (since file-utils 4.1)
Do the silly things file-utils 4.0 did, trying to copy the contents of device files and FIFOs during a recursive copy. Never use this option. With it, `cp' may well hang indefinitely reading a FIFO or /dev/tty, or fill the destination disk copying /dev/zero.
-d
Copy symbolic links as symbolic links rather than copying the files that they point to, and preserve hard links between source files in the copies.

With file-utils 4.0 the long option --no-dereference was a synonym for -d, with file-utils 4.1 it is a synonym for -P, while -d is equivalent to --no-dereference --preserve=links.

-f, --force
Remove existing destination files in case an open for writing fails, and never prompt before doing so. (Thus since file-utils 4.1. With file-utils 4.0 this option was equivalent to the new --remove-destination.)
-H (since file-utils 4.1)
See POSIX description above.
-i, --interactive
Prompt whether to overwrite existing regular destination files.
-l, --link
Make hard links instead of copies of non-directories.
-L, --dereference (since file-utils 4.1)
See POSIX description above.
--no-preserve=ATTRIBUTES (since file-utils 4.1)
Do not preserve the specified attributes. See the --preserve option below.
-p, --preserve
Preserve the original files' owner, group, permissions, and timestamps.
--preserve=ATTRIBUTES (since file-utils 4.1)
Here ATTRIBUTES can be one of "mode" (permissions), "ownership" (owner and group), "timestamps", "links", "all" (all of the foregoing).
-P, --no-dereference (since file-utils 4.1)
See POSIX description above. This replaces the file-utils 4.0 meaning of the -P option, that was a synonym for --parents. See also -d above.
--parents (in file-utils 4.0 also -P)
Form the name of each destination file by appending to the target directory a slash and the specified name of the source file. The last argument given to cp must be the name of an existing directory. For example, the command:
    cp --parents a/b/c existing_dir
copies the file `a/b/c' to `existing_dir/a/b/c', creating any missing intermediate directories.
-r
In file-utils 4.1: synonym of -R. In file-utils 4.0: Copy directories recursively, copying any non-directories and non-symbolic links (that is, FIFOs and special files) as if they were regular files. This silly behaviour is obtained in file-utils 4.1 if the --copy-contents option is given.
-R, --recursive
Copy directories recursively, preserving non-directories.
--reply=HOW (since file-utils 4.1)
Here HOW can be one of "yes", "no", "query", specifying that to all questions the answer is yes, or is no, or must be obtained by querying the user, respectively.
--remove-destination (since file-utils 4.1)
Remove each existing destination file before copying. With file-utils 4.0 this option was implied by -f.
--sparse=WHEN
A `sparse file' contains `holes' - sequences of zero bytes that do not occupy any physical disk blocks; the `read' system call reads these as zeroes. This can both save considerable disk space and increase speed, since many binary files contain lots of consecutive zero bytes. By default, cp detects holes in input source files via a crude heuristic and makes the corresponding output file sparse as well.

The WHEN value can be one of the following:

auto
The default behavior: the output file is sparse if the input file is sparse.
always
Always make the output file sparse. This is useful when the input file resides on a filesystem that does not support sparse files, but the output file is on a filesystem that does.
never
Never make the output file sparse. If you find an application for this option, let us know.
--strip-trailing-slashes (since file-utils 4.1)
Remove any trailing slashes from each source argument. (This can change the interpretation in case of a symbolic link to a directory.)
-s, --symbolic-link
Make symbolic links instead of copies of non-directories. All source file names must be absolute (starting with `/') unless the destination files are in the current directory. This option merely results in an error message on systems that do not support symbolic links.
-S
Backup suffix, see below.
--target-directory=DIR (since file-utils 4.1)
Specify the destination directory. Meant for use with xargs(1), as in "ls | xargs cp --target-directory=../d".
-u, --update
Do not copy a nondirectory that has an existing destination with the same or newer modification time.
-v, --verbose
Print the name of each file before copying it.
-x, --one-file-system
Skip subdirectories that are on different filesystems from the one that the copy started on.

GNU BACKUP OPTIONS

The GNU versions of programs like cp, mv, ln, install and patch will make a backup of files about to be overwritten, changed or destroyed if that is desired. That backup files are desired is indicated by the -b option. How they should be named is specified by the -V option. In case the name of the backup file is given by the name of the file extended by a suffix, this suffix is specified by the -S option.
-b, --backup
Make backups of files that are about to be overwritten or removed.
--backup=CONTROL
(Since fileutils-4.1.)
-S SUFFIX, --suffix=SUFFIX
Append SUFFIX to each backup file made. If this option is not specified, the value of the SIMPLE_BACKUP_SUFFIX environment variable is used. And if SIMPLE_BACKUP_SUFFIX is not set, the default is `~'.
-V METHOD, --version-control=METHOD
Specify how backup files are named. The METHOD argument can be `numbered' (or `t'), `existing' (or `nil'), or `never' (or `simple'). If this option is not specified, the value of the VERSION_CONTROL environment variable is used. And if VERSION_CONTROL is not set, the default backup type is `existing'.

This option corresponds to the Emacs variable `version-control'. The valid METHODs are (unique abbreviations are accepted):

t, numbered
Always make numbered backups.
nil, existing
Make numbered backups of files that already have them, simple backups of the others.
never, simple
Always make simple backups.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_COLLATE, LC_CTYPE and LC_MESSAGES have the usual meaning. For the GNU version, the variables SIMPLE_BACKUP_SUFFIX and VERSION_CONTROL control backup file naming, as described above.

CONFORMING TO

POSIX 1003.2

NOTES

This page describes cp as found in the fileutils-4.1 package; other versions may differ slightly.


touch(1)

TOUCH

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

touch - change file timestamps

SYNOPSIS

touch [-acm][-r ref_file|-t time] [--] file...

Obsolescent version:
touch [-acm][ugly_time] file...

GNU version:
touch [-acfm] [-r file] [-t decimtime] [-d time] [--time={atime,access,use,mtime,modify}] [--date=time] [--reference=file] [--no-create] [--help] [--version] [--] file...

DESCRIPTION

touch changes the access and/or modification timestamps of each specified file. These timestamps are changed to the current time, unless the -r option is specified, in which case they are changed to the corresponding timestamps of the file ref_file, or the -t option is specified, in which case they are changed to the specified time. Both times are changed when neither or both of the -a and -m options are given. Only the access or only the modification time is changed when one of the options -a and -m is given. If the file did not exist yet, it is created (as an empty file with mode 0666, modified by the umask), unless the -c option is given.

POSIX OPTIONS

-a
Change the access time of file.
-c
Do not create file.
-m
Change the modification time of file.
-r ref_file
Use the corresponding timestamp of ref_file as the new value for the changed timestamp(s).
-t time
Use the specified time as the new value for the changed timestamp(s). The argument is a decimal number of the form
    [[CC]YY]MMDDhhmm[.SS]
with the obvious meaning. If CC is not specified, the year CCYY is taken to be in the range 1969-2068. If SS is not specified, it is taken to be 0. It may be specified in the range 0-61 so that it is possible to refer to leap seconds. The resulting time is taken as a time for the time zone specified by the environment variable TZ. It is an error if the resulting time precedes 1 January 1970.
--
Terminate option list.

POSIX DETAILS

The second form of invocation has the disadvantage that there is some ambiguity as to whether ugly_time is a time or a file argument. It is taken to be a time when no -r or -t option is present, there are at least two arguments, and the first argument is an eight- or ten-digit decimal integer. The format of ugly_time is MMDDhhmm[yy], where an yy in the range 69-99 denotes a year in the range 1969-1999, and an unspecified yy denotes the current year. This form is obsolete.

GNU DETAILS

If the first file would be a valid argument to the -t option and no timestamp is given with any of the -d, -r or -t options and the `--' argument is not given, that argument is interpreted as the time for the other files instead of as a file name.

If changing both the access and modification times to the current time, touch can change the timestamps for files that the user running it does not own but has write permission for. Otherwise, the user must own the files.

GNU OPTIONS

-a, --time=atime, --time=access, --time=use
Change the access time only.
-c, --no-create
Do not create files that do not exist.
-d, --date=time
Use time instead of the current time. It can contain month names, time zones, `am' and `pm', etc.
-f
Ignored; for compatibility with BSD versions of touch(1).
-m, --time=mtime, --time=modify
Change the modification time only.
-r file, --reference=file
Use the times of the reference file instead of the current time.
-t decimtime
Here decimtime has the format MMDDhhmm[[CC]YY][.ss] Use the argument (months, days, hours, minutes, optional century and years, optional seconds) instead of the current time. Note that this format violates the POSIX specification.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variable TZ is used to interpret explicitly given times. The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2 describes a syntax for the argument of the -t option that differs from that used by the GNU implementation.

EXAMPLE OF USE

The command `touch foo' will create the file foo if it didn't exist, and change the time of last modification to now. It is often used to guide the actions of make.

NOTES

This page describes touch as found in the fileutils-4.0 package; other versions may differ slightly.


rm(1)

RM

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

rm - remove files or directories

SYNOPSIS

rm [options] file...

POSIX options: [-fiRr] [--]

GNU options (shortest form): [-dfirvR] [--help] [--version] [--]

DESCRIPTION

rm removes each given file. By default, it does not remove directories. But when the -r or -R option is given, the entire directory tree below the specified directory is removed (and there are no limitations on the depth of directory trees that can be removed by `rm -r'). It is an error when the last path component of file is either . or .. (so as to avoid unpleasant surprises with `rm -r .*' or so).

If the -i option is given, or if a file is unwritable, standard input is a terminal, and the -f option is not given, rm prompts the user for whether to remove the file, writing a question to stderr and reading an answer from stdin. If the response is not affirmative, the file is skipped.

POSIX OPTIONS

-f
Do not prompt for confirmation. Do not write diagnostic messages. Do not produce an error return status if the only errors were nonexisting files.
-i
Prompt for confirmation. (In case both -f and -i are given, the last one given takes effect.)
-r or -R
Recursively remove directory trees.
--
Terminate option list.

SVID DETAILS

The System V Interface Definition forbids removal of the last link to an executable binary file that is being executed.

GNU DETAILS

The GNU implementation (in fileutils-3.16) is broken in the sense that there is an upper limit to the depth of hierarchies that can be removed. (If necessary, a utility `deltree' can be used to remove very deep trees.)

GNU OPTIONS

-d, --directory
Remove directories with unlink(2) instead of rmdir(2), and don't require a directory to be empty before trying to unlink it. Only works if you have appropriate privileges. Because unlinking a directory causes any files in the deleted directory to become unreferenced, it is wise to fsck(8) the filesystem after doing this.
-f, --force
Ignore nonexistent files and never prompt the user.
-i, --interactive
Prompt whether to remove each file. If the response is not affirmative, the file is skipped.
-r, -R, --recursive
Remove the contents of directories recursively.
-v, --verbose
Print the name of each file before removing it.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_COLLATE, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2, except for the limitation on file hierarchy depth.

NOTES

This page describes rm as found in the fileutils-4.0 package; other versions may differ slightly.

Sometimes one wishes to recover deleted files. It helps to have backups. It helps to use a trash directory, so that removed files are only moved to the trash. But actually removed files, although gone in principle, can sometimes be recovered. For details for the ext2 filesystem, see the Ext2fs-Undeletion mini-Howto.


mv(1)

MV

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

mv - move (rename) files

SYNOPSIS

mv [option...] source target
mv [option...] source... target

POSIX options: [-fi] [--]

GNU options (shortest form): [-bfiuv] [-S suffix] [-V {numbered,existing,simple}] [--help] [--version] [--]

DESCRIPTION

mv moves or renames files or directories.

If the last argument names an existing directory, mv moves each other given file into a file with the same name in that directory. Otherwise, if only two files are given, it renames the first as the second. It is an error if the last argument is not a directory and more than two files are given.

Thus, `mv /a/x/y /b' will rename the file /a/x/y into /b/y if /b was an existing directory, and into /b otherwise.

Let us call the file a given file is going to be moved into its destination. If destination exists, and either the -i option is given, or destination is unwritable, standard input is a terminal, and the -f option is not given, mv prompts the user for whether to replace the file, writing a question to stderr and reading an answer from stdin. If the response is not affirmative, the file is skipped.

When both source and destination are on the same filesystem, they are the same file (just the name is changed; owner, mode, timestamps remain unchanged). When they are on different filesystems, the source file is copied and then deleted. mv will copy modification time, access time, user and group ID, and mode if possible. When copying user and/or group ID fails, the setuid and setgid bits are cleared in the copy.

POSIX OPTIONS

-f
Do not prompt for confirmation.
-i
Prompt for confirmation when destination exists. (In case both -f and -i are given, the last one given takes effect.)
--
Terminate option list.

GNU DETAILS

The GNU implementation (in fileutils-3.16) is broken in the sense that mv can move only regular files across filesystems.

GNU OPTIONS

-f, --force
Remove existing destination files and never prompt the user.
-i, --interactive
Prompt whether to overwrite existing regular destination files. If the response is not affirmative, the file is skipped.
-u, --update
Do not move a nondirectory that has an existing destination with the same or newer modification time.
-v, --verbose
Print the name of each file before moving it.

GNU BACKUP OPTIONS

The GNU versions of programs like cp, mv, ln, install and patch will make a backup of files about to be overwritten, changed or destroyed if that is desired. That backup files are desired is indicated by the -b option. How they should be named is specified by the -V option. In case the name of the backup file is given by the name of the file extended by a suffix, this suffix is specified by the -S option.
-b, --backup
Make backups of files that are about to be overwritten or removed.
-S SUFFIX, --suffix=SUFFIX
Append SUFFIX to each backup file made. If this option is not specified, the value of the SIMPLE_BACKUP_SUFFIX environment variable is used. And if SIMPLE_BACKUP_SUFFIX is not set, the default is `~'.
-V METHOD, --version-control=METHOD
Specify how backup files are named. The METHOD argument can be `numbered' (or `t'), `existing' (or `nil'), or `never' (or `simple'). If this option is not specified, the value of the VERSION_CONTROL environment variable is used. And if VERSION_CONTROL is not set, the default backup type is `existing'.

This option corresponds to the Emacs variable `version-control'. The valid METHODs are (unique abbreviations are accepted):

t, numbered
Always make numbered backups.
nil, existing
Make numbered backups of files that already have them, simple backups of the others.
never, simple
Always make simple backups.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_COLLATE, LC_CTYPE and LC_MESSAGES have the usual meaning. For the GNU version, the variables SIMPLE_BACKUP_SUFFIX and VERSION_CONTROL control backup file naming, as described above.

CONFORMING TO

POSIX 1003.2, except that directory hierarchies cannot be moved across filesystems.

NOTES

This page describes mv as found in the fileutils-4.0 package; other versions may differ slightly.


du(1)

DU

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

du - estimate file space usage

SYNOPSIS

du [options] [file...]

POSIX options: [-askx] [--]

GNU options (shortest form):
[-abcDhHklLmsSxX]

[--block-size=size]

[--exclude=pattern]

[--max-depth=n]

[--help] [--version] [--]

DESCRIPTION

du reports the amount of disk space used by the specified files, and by each directory in the hierarchies rooted at the specified files. Here `disk space used' means space used for the entire file hierarchy below the specified file.

With no arguments, du reports the disk space for the current directory.

POSIX DETAILS

The output is in 512-byte units by default, but in 1024-byte units when the -k option is given.

GNU DETAILS

The output is in 1024-byte units (when no units are specified by options), unless the environment variable POSIXLY_CORRECT is set, in which case POSIX is followed.

POSIX OPTIONS

-a
Show counts for all files encountered, not just directories.
-k
Use 1024-byte units instead of the default 512-byte units.
-s
Only output space usage for the actual arguments given, not for their subdirectories.
-x
Only count space on the same device as the argument given.
--
Terminate option list.

GNU OPTIONS

-a, --all
Show counts for all files, not just directories.
-b, --bytes
Print sizes in bytes, instead of kilobytes.
--block-size=size
Print sizes in blocks of size bytes. (New in fileutils-4.0.)
-c, --total
Print a grand total of all arguments after all arguments have been processed. This can be used to find out the total disk usage of a given set of files or directories.
-D, --dereference-args
Dereference symbolic links that are command line arguments. Does not affect other symbolic links. This is helpful for finding out the disk usage of directories, such as /usr/tmp, which are often symbolic links.
--exclude=pattern
When recursing, skip subdirectories or files matching pattern. The pattern may be any standard Bourne shell file glob pattern. (New in fileutils-4.0.)
-h, --human-readable
Append a size letter, such as M for binary megabytes (`mebibytes'), to each size.
-H, --si
Do the same as for -h, but use the official SI units (with powers of 1000 instead of 1024, so that M stands for 1000000 instead of 1048576). (New in fileutils-4.0.)
-k, --kilobytes
Print sizes in KiB (binary kilobytes, 1024 bytes).
-l, --count-links
Count the size of all files, even if they have appeared already (as a hard link).
-L, --dereference
Dereference symbolic links (show the disk space used by the file or directory that the link points to instead of the space used by the link).
-m, --megabytes
Print sizes in MiB (binary megabytes, 1048576 bytes).
--max-depth=n
Print the total for a directory (or file, with the -a flag) only if it is n or fewer levels below the command line argument; --max-depth=0 is the same as the -s flag. (New in fileutils-4.0.)
-s, --summarize
Display only a total for each argument.
-S, --separate-dirs
Report the size of each directory separately, not including the sizes of subdirectories.
-x, --one-file-system
Skip directories that are on different filesystems from the one that the argument being processed is on.
-X file, --exclude-from=file
Like --exclude, except take the patterns to exclude from the specified file. Patterns are listed one per line. If file is given as `-', patterns are read from standard input. (New in fileutils-4.0.)

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

BUGS

On BSD systems, du reports sizes that are half the correct values for files that are NFS-mounted from HP-UX systems. On HP-UX systems, it reports sizes that are twice the correct values for files that are NFS-mounted from BSD systems. This is due to a flaw in HP-UX; it also affects the HP-UX du program.

ENVIRONMENT

The variable POSIXLY_CORRECT determines the choice of unit. If it is not set, and the variable BLOCKSIZE has a value starting with `HUMAN', then behaviour is as for the -h option, unless overridden by -k or -m options. The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2

NOTES

This page describes du as found in the fileutils-4.0 package; other versions may differ slightly.


mkfifo(1)

MKFIFO

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

mkfifo - make FIFOs (named pipes)

SYNOPSIS

mkfifo [options] file...

POSIX options: [-m mode] [--]

GNU options (shortest form): [-m mode] [--help] [--version] [--]

DESCRIPTION

mkfifo creates FIFOs (also called "named pipes") with the specified filenames.

A "FIFO" is a special file type that permits independent processes to communicate. One process opens the FIFO file for writing, and another for reading, after which data can flow as with the usual anonymous pipe in shells or elsewhere.

By default, the mode of created FIFOs is 0666 (`a+rw') minus the bits set in the umask.

OPTIONS

-m mode, --mode=mode
Set the mode of created FIFOs to mode, which can be symbolic as in chmod(1) and uses the default mode as the point of departure.
--
Terminate option list.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2

NOTES

This page describes mkfifo as found in the fileutils-4.0 package; other versions may differ slightly.


ln(1)

LN

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

ln - make links between files

SYNOPSIS

ln [options] source [dest]
ln [options] source... directory

POSIX options: [-f] [--]

GNU options (shortest form):
[-bdfinsvF]

[-S backup-suffix]

[-V {numbered,existing,simple}]

[--help] [--version] [--]

DESCRIPTION

There are two concepts of `link' in Unix, usually called hard link and soft link. A hard link is just a name for a file. (And a file can have several names. It is deleted from disk only when the last name is removed. The number of names is given by ls(1). There is no such thing as an `original' name: all names have the same status. Usually, but not necessarily, all names of a file are found in the filesystem that also contains its data.)

A soft link (or symbolic link, or symlink) is an entirely different animal: it is a small special file that contains a pathname. Thus, soft links can point at files on different filesystems (possibly NFS mounted from different machines), and need not point to actually existing files. When accessed (with the open(2) or stat(2) system calls), a reference to a symlink is replaced by the operating system kernel with a reference to the file named by the path name. (However, with rm(1) and unlink(2) the link itself is removed, not the file it points to. There are special system calls lstat(2) and readlink(2) that read the status of a symlink and the filename it points to. For various other system calls there is some uncertainty and variation between operating systems as to whether the operation acts on the symlink itself, or on the file pointed to.)

ln makes links between files. By default, it makes hard links; with the -s option, it makes symbolic (or `soft') links.

If only one file is given, it links that file into the current directory, that is, creates a link to that file in the current directory, with name equal to (the last component of) the name of that file. (This is a GNU extension.) Otherwise, if the last argument names an existing directory, ln will create links to each mentioned source file in that directory, with a name equal to (the last component of) the name of that source file. (But see the description of the --no-dereference option below.) Otherwise, if only two files are given, it creates a link named dest to the file source. It is an error if the last argument is not a directory and more than two files are given.

By default, ln does not remove existing files or existing symbolic links. (Thus, it can be used for locking purposes: it will succeed only if dest did not exist already.) But it can be forced to do so with the option -f.

On existing implementations, if it is at all possible to make a hard link to a directory, this may be done by the superuser only. POSIX forbids the system call link(2) and the utility ln to make hard links to directories (but does not forbid hard links to cross filesystem boundaries).

POSIX OPTIONS

-f
Remove existing destination files.
--
Terminate option list.

GNU OPTIONS

-d, -F, --directory
Allow the superuser to make hard links to directories.
-f, --force
Remove existing destination files.
-i, --interactive
Prompt whether to remove existing destination files.
-n, --no-dereference
When given an explicit destination that is a symlink to a directory, treat that destination as if it were a normal file.

When the destination is an actual directory (not a symlink to one), there is no ambiguity. The link is created in that directory. But when the specified destination is a symlink to a directory, there are two ways to treat the user's request. ln can treat the destination just as it would a normal directory and create the link in it. On the other hand, the destination can be viewed as a non-directory - as the symlink itself. In that case, ln must delete or backup that symlink before creating the new link. The default is to treat a destination that is a symlink to a directory just like a directory.

-s, --symbolic
Make symbolic links instead of hard links. This option merely produces an error message on systems that do not support symbolic links.
-v, --verbose
Print the name of each file before linking it.

GNU BACKUP OPTIONS

The GNU versions of programs like cp, mv, ln, install and patch will make a backup of files about to be overwritten, changed or destroyed if that is desired. That backup files are desired is indicated by the -b option. How they should be named is specified by the -V option. In case the name of the backup file is given by the name of the file extended by a suffix, this suffix is specified by the -S option.
-b, --backup
Make backups of files that are about to be overwritten or removed.
-S SUFFIX, --suffix=SUFFIX
Append SUFFIX to each backup file made. If this option is not specified, the value of the SIMPLE_BACKUP_SUFFIX environment variable is used. And if SIMPLE_BACKUP_SUFFIX is not set, the default is `~'.
-V METHOD, --version-control=METHOD
Specify how backup files are named. The METHOD argument can be `numbered' (or `t'), `existing' (or `nil'), or `never' (or `simple'). If this option is not specified, the value of the VERSION_CONTROL environment variable is used. And if VERSION_CONTROL is not set, the default backup type is `existing'.

This option corresponds to the Emacs variable `version-control'. The valid METHODs are (unique abbreviations are accepted):

t, numbered
Always make numbered backups.
nil, existing
Make numbered backups of files that already have them, simple backups of the others.
never, simple
Always make simple backups.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2. However, POSIX 1003.2 (1996) does not discuss soft links. Soft links were introduced by BSD, and do not occur in System V release 3 (and older) systems.

SEE ALSO

ls(1), rm(1), link(2), lstat(2), open(2), readlink(2), stat(2), unlink(2)

NOTES

This page describes ln as found in the fileutils-4.0 package; other versions may differ slightly.


diff(1)

DIFF

Section: GNU Tools (1)
Updated: 1993-09-22 Return to Main Contents

NAME

diff - find differences between two files

SYNOPSIS

diff [options] from-file to-file

DESCRIPTION

In the simplest case, diff compares the contents of the two files from-file and to-file. A file name of - stands for text read from the standard input. As a special case, diff - - compares a copy of standard input to itself.

If from-file is a directory and to-file is not, diff compares the file in from-file whose file name is that of to-file, and vice versa. The non-directory file must not be -.

If both from-file and to-file are directories, diff compares corresponding files in both directories, in alphabetical order; this comparison is not recursive unless the -r or --recursive option is given. diff never compares the actual contents of a directory as if it were a file. The file that is fully specified may not be standard input, because standard input is nameless and the notion of ``file with the same name'' does not apply.

diff options begin with -, so normally from-file and to-file may not begin with -. However, -- as an argument by itself treats the remaining arguments as file names even if they begin with -.

Options

Below is a summary of all of the options that GNU diff accepts. Most options have two equivalent names, one of which is a single letter preceded by -, and the other of which is a long name preceded by --. Multiple single letter options (unless they take an argument) can be combined into a single command line word: -ac is equivalent to -a -c. Long named options can be abbreviated to any unique prefix of their name. Brackets ([ and ]) indicate that an option takes an optional argument.
-lines
Show lines (an integer) lines of context. This option does not specify an output format by itself; it has no effect unless it is combined with -c or -u. This option is obsolete. For proper operation, patch typically needs at least two lines of context.
-a
Treat all files as text and compare them line-by-line, even if they do not seem to be text.
-b
Ignore changes in amount of white space.
-B
Ignore changes that just insert or delete blank lines.
--brief
Report only whether the files differ, not the details of the differences.
-c
Use the context output format.
-C lines

--context[=lines]
Use the context output format, showing lines (an integer) lines of context, or three if lines is not given. For proper operation, patch typically needs at least two lines of context.
--changed-group-format=format
Use format to output a line group containing differing lines from both files in if-then-else format.
-d
Change the algorithm to perhaps find a smaller set of changes. This makes diff slower (sometimes much slower).
-D name
Make merged if-then-else format output, conditional on the preprocessor macro name.
-e

--ed
Make output that is a valid ed script.
--exclude=pattern
When comparing directories, ignore files and subdirectories whose basenames match pattern.
--exclude-from=file
When comparing directories, ignore files and subdirectories whose basenames match any pattern contained in file.
--expand-tabs
Expand tabs to spaces in the output, to preserve the alignment of tabs in the input files.
-f
Make output that looks vaguely like an ed script but has changes in the order they appear in the file.
-F regexp
In context and unified format, for each hunk of differences, show some of the last preceding line that matches regexp.
--forward-ed
Make output that looks vaguely like an ed script but has changes in the order they appear in the file.
-h
This option currently has no effect; it is present for Unix compatibility.
-H
Use heuristics to speed handling of large files that have numerous scattered small changes.
--horizon-lines=lines
Do not discard the last lines lines of the common prefix and the first lines lines of the common suffix.
-i
Ignore changes in case; consider upper- and lower-case letters equivalent.
-I regexp
Ignore changes that just insert or delete lines that match regexp.
--ifdef=name
Make merged if-then-else format output, conditional on the preprocessor macro name.
--ignore-all-space
Ignore white space when comparing lines.
--ignore-blank-lines
Ignore changes that just insert or delete blank lines.
--ignore-case
Ignore changes in case; consider upper- and lower-case to be the same.
--ignore-matching-lines=regexp
Ignore changes that just insert or delete lines that match regexp.
--ignore-space-change
Ignore changes in amount of white space.
--initial-tab
Output a tab rather than a space before the text of a line in normal or context format. This causes the alignment of tabs in the line to look normal.
-l
Pass the output through pr to paginate it.
-L label

--label=label
Use label instead of the file name in the context format and unified format headers.
--left-column
Print only the left column of two common lines in side by side format.
--line-format=format
Use format to output all input lines in in-then-else format.
--minimal
Change the algorithm to perhaps find a smaller set of changes. This makes diff slower (sometimes much slower).
-n
Output RCS-format diffs; like -f except that each command specifies the number of lines affected.
-N

--new-file
In directory comparison, if a file is found in only one directory, treat it as present but empty in the other directory.
--new-group-format=format
Use format to output a group of lines taken from just the second file in if-then-else format.
--new-line-format=format
Use format to output a line taken from just the second file in if-then-else format.
--old-group-format=format
Use format to output a group of lines taken from just the first file in if-then-else format.
--old-line-format=format
Use format to output a line taken from just the first file in if-then-else format.
-p
Show which C function each change is in.
-P
When comparing directories, if a file appears only in the second directory of the two, treat it as present but empty in the other.
--paginate
Pass the output through pr to paginate it.
-q
Report only whether the files differ, not the details of the differences.
-r
When comparing directories, recursively compare any subdirectories found.
--rcs
Output RCS-format diffs; like -f except that each command specifies the number of lines affected.
--recursive
When comparing directories, recursively compare any subdirectories found.
--report-identical-files

-s
Report when two files are the same.
-S file
When comparing directories, start with the file file. This is used for resuming an aborted comparison.
--sdiff-merge-assist
Print extra information to help sdiff. sdiff uses this option when it runs diff. This option is not intended for users to use directly.
--show-c-function
Show which C function each change is in.
--show-function-line=regexp
In context and unified format, for each hunk of differences, show some of the last preceding line that matches regexp.
--side-by-side
Use the side by side output format.
--speed-large-files
Use heuristics to speed handling of large files that have numerous scattered small changes.
--starting-file=file
When comparing directories, start with the file file. This is used for resuming an aborted comparison.
--suppress-common-lines
Do not print common lines in side by side format.
-t
Expand tabs to spaces in the output, to preserve the alignment of tabs in the input files.
-T
Output a tab rather than a space before the text of a line in normal or context format. This causes the alignment of tabs in the line to look normal.
--text
Treat all files as text and compare them line-by-line, even if they do not appear to be text.
-u
Use the unified output format.
--unchanged-group-format=format
Use format to output a group of common lines taken from both files in if-then-else format.
--unchanged-line-format=format
Use format to output a line common to both files in if-then-else format.
--unidirectional-new-file
When comparing directories, if a file appears only in the second directory of the two, treat it as present but empty in the other.
-U lines

--unified[=lines]
Use the unified output format, showing lines (an integer) lines of context, or three if lines is not given. For proper operation, patch typically needs at least two lines of context.
-v

--version
Output the version number of diff.
-w
Ignore white space when comparing lines.
-W columns

--width=columns
Use an output width of columns in side by side format.
-x pattern
When comparing directories, ignore files and subdirectories whose basenames match pattern.
-X file
When comparing directories, ignore files and subdirectories whose basenames match any pattern contained in file.
-y
Use the side by side output format.

SEE ALSO

cmp(1), comm(1), diff3(1), ed(1), patch(1), pr(1), sdiff(1).

DIAGNOSTICS

An exit status of 0 means no differences were found, 1 means some differences were found, and 2 means trouble.


mkdir(1)

MKDIR

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

mkdir - make directories

SYNOPSIS

mkdir [options] directory...

POSIX options: [-p] [-m mode] [--]

GNU options (shortest form): [-p] [-m mode] [--verbose] [--help] [--version] [--]

DESCRIPTION

mkdir creates directories with the specified names.

By default, the mode of created directories is 0777 (`a+rwx') minus the bits set in the umask.

OPTIONS

-m mode, --mode=mode
Set the mode of created directories to mode, which may be symbolic as in chmod(1) and then uses the default mode as the point of departure.
-p, --parents
Make any missing parent directories for each directory argument. The mode for parent directories is set to the umask modified by `u+wx'. Ignore arguments corresponding to existing directories. (Thus, if a directory /a exists, then `mkdir /a' is an error, but `mkdir -p /a' is not.)
--verbose
Print a message for each created directory. This is most useful with --parents.
--
Terminate option list.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2

NOTES

This page describes mkdir as found in the fileutils-4.0 package; other versions may differ slightly.


mknod(1)

MKNOD

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

mknod - make block or character special files

SYNOPSIS

mknod [options] name {bc} major minor
mknod [options] name p

GNU options (shortest form): [-m mode] [--help] [--version] [--]

DESCRIPTION

mknod creates a FIFO (named pipe), character special file, or block special file with the specified name.

A special file is a triple (boolean, integer, integer) stored in the filesystem. The boolean chooses between character special file and block special file. The two integers are the major and minor device number.

Thus, a special file takes almost no place on disk, and is used only for communication with the operating system, not for data storage. Often special files refer to hardware devices (disk, tape, tty, printer) or to operating system services (/dev/null, /dev/random).

Block special files usually are disk-like devices (where data can be accessed given a block number, and e.g. it is meaningful to have a block cache). All other devices are character special files. (Long ago the distinction was a different one: I/O to a character special file would be unbuffered, to a block special file buffered.)

The mknod command is what creates files of this type.

The argument following name specifies the type of file to make:

p
for a FIFO
b
for a block (buffered) special file
c
for a character (unbuffered) special file

The GNU version of mknod allows u (`unbuffered') as a synonym for c.

When making a block or character special file, the major and minor device numbers must be given after the file type (in decimal, or in octal with leading 0; the GNU version also allows hexadecimal with leading 0x). By default, the mode of created files is 0666 (`a+rw') minus the bits set in the umask.

OPTIONS

-m mode, --mode=mode
Set the mode of created files to mode, which can be symbolic as in chmod(1) and then uses the default mode as the point of departure.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

CONFORMING TO

POSIX does not describe this command as it is nonportable, and recommends using mkfifo(1) to make FIFOs. SVID has a command /etc/mknod with the above syntax, but without the mode option.

NOTES

On a Linux system (version 1.3.22 or newer) the file /usr/src/linux/Documentation/devices.tex contains a list of devices with device name, type, major and minor number.

The present page describes mknod as found in the fileutils-4.0 package; other versions may differ slightly.

SEE ALSO

chmod(1), mkfifo(1), mknod(2)


dircolors(1)

DIRCOLORS

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

dircolors - color setup for `ls'

SYNOPSIS

dircolors [-b] [--sh] [--bourne-shell] [-c] [--csh] [--c-shell] [-p] [--print-database] [--help] [--version] [FILE]

DESCRIPTION

dircolors outputs a sequence of shell commands to define the desired color output from ls (and dir, etc.). Typical usage:
eval `dircolors [OPTION]... [FILE]`

If FILE is specified, dircolors reads it to determine which colors to use for which file types and extensions. Otherwise, a compiled-in database is used. For details on the format of these files, run `dircolors -p'.

The output is a shell command to set the LS_COLORS environment variable. You can specify the shell syntax to use on the command line, or dircolors will guess it from the value of the SHELL environment variable.

After execution of this command, `ls --color' (which one might alias to ls) will list files in the desired colors.

OPTIONS

-b, --sh, --bourne-shell
Output Bourne shell commands. This is the default if the SHELL environment variable is set and does not end with csh or tcsh.
-c, --csh, --c-shell
Output C shell commands. This is the default if SHELL ends with csh or tcsh.
-p, --print-database
Print the (compiled-in) default color configuration database. This output is itself a valid configuration file, and is fairly descriptive of the possibilities.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables SHELL and TERM are used to find the proper form of the shell command. The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning. The variable LS_COLORS is used to transfer information to ls.

CONFORMING TO

Coloured output for ls(1) is a GNU extension. This implementation is not entirely compatible with the original dircolors/color-ls package distributed with Slackware Linux. Notably, specific support for the Z shell and Korn shell is not present. Users of these shells should use the Bourne shell (-b) mode.

SEE ALSO

ls(1), dir_colors(5)

FILES

The program dircolors itself does not use any configuration files. However, customarily the shell initialization scripts invoke dircolors with one of the following.
/etc/DIR_COLORS
System-wide configuration file for dircolors.
~/.dir_colors
Per-user configuration file for dircolors.

NOTES

This page describes dircolors as found in the fileutils-4.0 package; other versions may differ slightly.


install(1)

INSTALL

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

install - copy files and set attributes

SYNOPSIS

install [options] [-s] [--strip] source dest
install [options] [-s] [--strip] source... directory
install [options] [-d,--directory] directory...

Options (shortest form):
[-b]

[-c]

[-D]

[-g group]

[-m mode]

[-o owner]

[-S SUFFIX]

[-V {numbered,existing,simple}]

[--help] [--version] [--]

DESCRIPTION

install copies files while setting their permission modes and, if possible, their owner and group.

In the first of these invocation forms, the source file is copied to the dest target file. In the second, each of the source files are copied to the destination directory. In the last, each directory (and any missing parent directories) is created.

install is similar to cp, but allows you to control the attributes of destination files. It is typically used in Makefiles to copy programs into their destination directories. It refuses to copy files onto themselves.

OPTIONS

-c
Ignored; for compatibility with old Unix versions of install.
-d, --directory
Create each given directory and any missing parent directories, setting the owner, group and mode as given on the command line or to the defaults. It also gives any parent directories it creates those attributes. (This is different from the SunOS 4.x install, which gives directories that it creates the default attributes.)
-D
Create all leading components of the dest except the last, then copy source to dest. This option is useful in the first format in the synopsis, above. (New in fileutils-4.0.)
-g group, --group=group
Set the group ownership of installed files or directories to group. The default is the process's current group. group may be either a group name or a numeric group id.
-m mode, --mode=mode
Set the permissions for the installed file or directory to mode, which can be either an octal number, or a symbolic mode as in chmod, with 0 as the point of departure. The default mode is 0755 - read, write, and execute for the owner, and read and execute for group and other.
-o owner, --owner=owner
If install has appropriate privileges (is run as root), set the ownership of installed files or directories to owner. The default is `root'. owner may be either a user name or a numeric user ID.
-s, --strip
Strip the symbol tables from installed binary executables.

GNU BACKUP OPTIONS

The GNU versions of programs like cp, mv, ln, install and patch will make a backup of files about to be overwritten, changed or destroyed if that is desired. That backup files are desired is indicated by the -b option. How they should be named is specified by the -V option. In case the name of the backup file is given by the name of the file extended by a suffix, this suffix is specified by the -S option.
-b, --backup
Make backups of files that are about to be overwritten or removed.
-S SUFFIX, --suffix=SUFFIX
Append SUFFIX to each backup file made. If this option is not specified, the value of the SIMPLE_BACKUP_SUFFIX environment variable is used. And if SIMPLE_BACKUP_SUFFIX is not set, the default is `~'.
-V METHOD, --version-control=METHOD
Specify how backup files are named. The METHOD argument can be `numbered' (or `t'), `existing' (or `nil'), or `never' (or `simple'). If this option is not specified, the value of the VERSION_CONTROL environment variable is used. And if VERSION_CONTROL is not set, the default backup type is `existing'.

This option corresponds to the Emacs variable `version-control'. The valid METHODs are (unique abbreviations are accepted):

t, numbered
Always make numbered backups.
nil, existing
Make numbered backups of files that already have them, simple backups of the others.
never, simple
Always make simple backups.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning. For the GNU version, the variables SIMPLE_BACKUP_SUFFIX and VERSION_CONTROL control backup file naming, as described above.

CONFORMING TO

BSD 4.2 (which had the -c, -m, -o, -g and -s options).

NOTES

This page describes install as found in the fileutils-4.0 package; other versions may differ slightly.


rmdir(1)

RMDIR

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

rmdir - remove empty directories

SYNOPSIS

rmdir [options] directory...

POSIX options: [-p] [--]

GNU options (shortest form): [-p] [--ignore-fail-on-non-empty] [--help] [--version] [--]

DESCRIPTION

rmdir removes empty directories.

If any directory argument does not refer to an existing empty directory, it is an error.

POSIX OPTIONS

-p
If directory includes more than one pathname component, remove it, then strip the last component and remove the resulting directory, etc., until all components have been removed. Thus, `rmdir -p a/b/c' is equivalent to `rmdir a/b/c; rmdir a/b; rmdir a'.
--
Terminate option list.

GNU OPTIONS

--ignore-fail-on-non-empty
Normally rmdir will refuse to remove a directory that is not empty. This option causes rmdir to ignore the failure to remove a directory, if that failure is due to the directory being non-empty. (New in fileutils-4.0.)
-p, --parents
As above.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2

EXAMPLE OF USE

The command `rmdir foo' will remove the directory foo if it is empty. To remove a nonempty directory, together with everything below, use `rm -r foo'.

NOTES

This page describes rmdir as found in the fileutils-4.0 package; other versions may differ slightly.


chgrp(1)

CHGRP

Section: User Commands (1)
Updated: 2000-08 Return to Main Contents

NAME

chgrp - change group ownership of files

SYNOPSIS

chgrp [options] group file...

POSIX options: [-R] [--]

POSIX 1003.1-2001 options: [-hHLPR]

GNU group denotation: [--reference=rfile]

GNU options (shortest form): [-cfvR] [--help] [--version] [--]

DESCRIPTION

chgrp changes the group ownership of each given file to group, which can be either a group name or a numeric group ID.

POSIX OPTIONS

-R
Recursively change the group ownership of directories and their contents. (And continue even when errors are encountered.)
--
Terminate option list.

AUSTIN DRAFT OPTIONS

-h
For each file operand given that is a symlink, change the group ownership of the symlink itself, rather than the object it points to. If the system does not support a group ownership for symlinks, do nothing for a symlink.
-H (half-logical)
(When given together with -R.) For each file operand given that is a symlink to a directory, change the group ownership of the directory and all files in the file hierarchy below it.
-L (logical)
(When given together with -R.) For each file, either command line operand or encountered during the tree walk, that is a symlink to a directory, change the group ownership of the directory and all files in the file hierarchy below it.
-P (physical)
(When given together with -R.) For each file, either command line operand or encountered during the tree walk, that is a symlink, change the group ownership of the symlink itself, rather than the object it points to. If the system does not support a group ownership for symlinks, do nothing for a symlink. This is the default.
-R
Recursively change the group ownership of directories and their contents.

ADDITIONAL GNU DESCRIPTION

A GNU extension (new in fileutils 4.0) allows one to use --reference=rfile as a group description: the same group as that of rfile.

GNU OPTIONS

-c, --changes
Verbosely describe the action for each file whose group actually changes.
-f, --silent, --quiet
Do not print error messages about files whose group cannot be changed.
-h, --no-dereference
Act on symbolic links themselves instead of what they point to. Only available if the lchown system call is provided.
-v, --verbose
Verbosely describe the action or non-action taken for every file.
-R, --recursive
Recursively change the group ownership of directories and their contents.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning. For an XSI-conforming system: NLSPATH has the usual meaning.

CONFORMING TO

POSIX 1003.2 only requires the -R option. Use of other options may not be portable.

NOTES

This page describes chgrp as found in the fileutils-4.0 package; other versions may differ slightly.


chown(1)

CHOWN

Section: User Commands (1)
Updated: 1998-11 Return to Main Contents

NAME

chown - change file owner and group

SYNOPSIS

chown [options] user[:group] file...

POSIX options: [-R] [--]

GNU options (shortest form): [-cfhvR] [--dereference] [--reference=rfile] [--help] [--version] [--]

DESCRIPTION

chown changes the user and/or group ownership of each given file as specified by the first non-option argument as follows: if only a user name (or numeric user ID) is given, that user is made the owner of each given file, and the files' group is not changed. If the user name is followed by a colon and a group name (or numeric group ID), with no spaces between them, the group ownership of the files is changed as well.

GNU DETAILS

The GNU version allows a dot instead of a colon (following BSD). [This was not allowed by POSIX since a dot is a valid character in a user name.] If a colon or dot but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group. If the colon or dot and group are given, but the user name is omitted, only the group of the files is changed; in this case, chown performs the same function as chgrp.

POSIX OPTIONS

-R
Recursively change ownership of directories and their contents.
--
Terminate option list.

GNU OPTIONS

-c, --changes
Verbosely describe the action for each file whose ownership actually changes.
-f, --silent, --quiet
Do not print error messages about files whose ownership cannot be changed.
-h, --no-dereference
Act on symbolic links themselves instead of what they point to. Only available if the lchown system call is provided.
-v, --verbose
Verbosely describe the action (or non-action) taken for every file.
-R, --recursive
Recursively change ownership of directories and their contents.
--dereference
Change the ownership of the target of a symbolic link instead of the symbolic link itself. (New in fileutils-4.0.)
--reference=rfile
(New in fileutils 4.0.) Change the ownership of file to that of rfile.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX 1003.2 does not allow use of the dot as separator between user name and group name.

NOTES

This page describes chown as found in the fileutils-4.0 package; other versions may differ slightly.


dir (1)

 Continue to this page.


vdir (1)

 Continue to this page.


time(1)

TIME

Section: (1)
Updated: 2000-12-11 Return to Main Contents

NAME

time - time a simple command or give resource usage

SYNOPSIS

time [options] command [arguments...]

DESCRIPTION

The time command runs the specified program command with the given arguments. When command finishes, time writes a message to standard error giving timing statistics about this program run. These statistics consist of (i) the elapsed real time between invocation and termination, (ii) the user CPU time (the sum of the tms_utime and tms_cutime values in a struct tms as returned by times(2)), and (iii) the system CPU time (the sum of the tms_stime and tms_cstime values in a struct tms as returned by times(2)).

OPTION

-p
When in the POSIX locale, use the precise traditional format
"real %f\nuser %f\nsys %f\n"
(with numbers in seconds) where the number of decimals in the output for %f is unspecified but is sufficient to express the clock tick accuracy, and at least one.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE, LC_MESSAGES, LC_NUMERIC, NLSPATH and PATH are used. The last one to search for command. The remaining ones for the text and formatting of the output.

EXIT STATUS

If command was invoked, the exit status is that of command. Otherwise it is 127 if command could not be found, 126 if it could be found but could not be invoked, and some other non-zero value (1-125) if something else went wrong.

GNU VERSION

Below a description of the GNU 1.7 version of time. Disregarding the name of the utility, GNU makes it output lots of useful information, not only about time used, but also on other resources like memory, I/O and IPC calls (where available). The output is formatted using a format string that can be specified using the -f option or the TIME environment variable.

The default format string is
%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata %Mmax)k
%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps

When the -p option is given the (portable) output format
real %e
user %U
sys %S
is used.

The format string

The format is interpreted in the usual printf-like way. Ordinary characters are directly copied, tab, newline and backslash are escaped using \t, \n and \\, a percent sign is represented by %%, and otherwise % indicates a conversion. The program time will always add a trailing newline itself. The conversions follow. All of those used by tcsh(1) are supported.

Time

%E
Elapsed real time (in [hours:]minutes:seconds).
%e
(Not in tcsh.) Elapsed real time (in seconds).
%S
Total number of CPU-seconds that the process spent in kernel mode.
%U
Total number of CPU-seconds that the process spent in user mode.
%P
Percentage of the CPU that this job got, computed as (%U + %S) / %E.

Memory

%M
Maximum resident set size of the process during its lifetime, in Kbytes.
%t
(Not in tcsh.) Average resident set size of the process, in Kbytes.
%K
Average total (data+stack+text) memory use of the process, in Kbytes.
%D
Average size of the process's unshared data area, in Kbytes.
%p
(Not in tcsh.) Average size of the process's unshared stack space, in Kbytes.
%X
Average size of the process's shared text space, in Kbytes.
%Z
(Not in tcsh.) System's page size, in bytes. This is a per-system constant, but varies between systems.
%F
Number of major page faults that occurred while the process was running. These are faults where the page has to be read in from disk.
%R
Number of minor, or recoverable, page faults. These are faults for pages that are not valid but which have not yet been claimed by other virtual pages. Thus the data in the page is still valid but the system tables must be updated.
%W
Number of times the process was swapped out of main memory.
%c
Number of times the process was context-switched involuntarily (because the time slice expired).
%w
Number of waits: times that the program was context-switched voluntarily, for instance while waiting for an I/O operation to complete.

I/O

%I
Number of file system inputs by the process.
%O
Number of file system outputs by the process.
%r
Number of socket messages received by the process.
%s
Number of socket messages sent by the process.
%k
Number of signals delivered to the process.
%C
(Not in tcsh.) Name and command line arguments of the command being timed.
%x
(Not in tcsh.) Exit status of the command.

GNU OPTIONS

-f FORMAT, --format=FORMAT
Specify output format, possibly overriding the format specified in the environment variable TIME.
-p, --portability
Use the portable output format.
-o FILE, --output=FILE
Do not send the results to stderr, but overwrite the specified file.
-a, --append
(Used together with -o.) Do not overwrite but append.
-v, --verbose
Give very verbose output about all the program knows about.

GNU STANDARD OPTIONS

--help
Print a usage message on standard output and exit successfully.
-V, --version
Print version information on standard output, then exit successfully.
--
Terminate option list.

BUGS

Not all resources are measured by all versions of Unix, so some of the values might be reported as zero. The present selection was mostly inspired by the data provided by 4.2 or 4.3BSD.

GNU time version 1.7 is not yet localized. Thus, it does not implement the POSIX requirements.

The environment variable TIME was badly chosen. It is not unusual for systems like autoconf or make to use environment variables with the name of a utility to override the utility to be used. Uses like MORE or TIME for options to programs (instead of program pathnames) tend to lead to difficulties.

It seems unfortunate that -o overwrites instead of appends. (That is, the -a option should be the default.)

Mail suggestions and bug reports for GNU time to
bug-utils@prep.ai.mit.edu
Please include the version of time, which you can get by running
time --version
and the operating system and C compiler you used.

SEE ALSO

tcsh(1), times(2), wait3(2)


ldd(1)

LDD

Section: Linux Programmer's Manual (1)
Updated: 2000-10-30 Return to Main Contents

NAME

ldd - print shared library dependencies

SYNOPSIS

ldd [OPTION]... FILE...

DESCRIPTION

ldd prints the shared libraries required by each program or shared library specified on the command line.

OPTIONS

--version
Print the version number of ldd.
-v --verbose
Print all information, including, for example, symbol versioning information.
-u --unused
Print unused direct dependencies. (Since glibc 2.3.4.)
-d --data-relocs
Perform relocations and report any missing objects (ELF only).
-r --function-relocs
Perform relocations for both data objects and functions, and report any missing objects or functions (ELF only).
--help
Usage information.

NOTES

The standard version of ldd comes with glibc2. Libc5 came with an older version, still present on some systems. The long options are not supported by the libc5 version. On the other hand, the glibc2 version does not support -V and only has the equivalent --version.

The libc5 version of this program will use the name of a library given on the command line as-is when it contains a '/'; otherwise it searches for the library in the standard locations. To run it on a shared library in the current directory, prefix the name with "./".

BUGS

ldd does not work on a.out shared libraries.

ldd does not work with some extremely old a.out programs which were built before ldd support was added to the compiler releases. If you use ldd on one of these programs, the program will attempt to run with argc = 0 and the results will be unpredictable.

SEE ALSO

ld.so(8), ldconfig(8)


date(1p)

DATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

date - write the date and time

SYNOPSIS

date [-u] [+format]

date [-u] mmddhhmm[[cc]yy]

DESCRIPTION

The date utility shall write the date and time to standard output or attempt to set the system date and time. By default, the current date and time shall be written. If an operand beginning with '+' is specified, the output format of date shall be controlled by the conversion specifications and other text in the operand.

OPTIONS

The date utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-u
Perform operations as if the TZ environment variable was set to the string "UTC0" , or its equivalent historical value of "GMT0" . Otherwise, date shall use the timezone indicated by the TZ environment variable or the system default if that variable is unset or null.

OPERANDS

The following operands shall be supported:

+format
When the format is specified, each conversion specifier shall be replaced in the standard output by its corresponding value. All other characters shall be copied to the output without change. The output shall always be terminated with a <newline>.

Conversion Specifications

%a
Locale's abbreviated weekday name.
%A
Locale's full weekday name.
%b
Locale's abbreviated month name.
%B
Locale's full month name.
%c
Locale's appropriate date and time representation.
%C
Century (a year divided by 100 and truncated to an integer) as a decimal number [00,99].
%d
Day of the month as a decimal number [01,31].
%D
Date in the format mm/dd/yy.
%e
Day of the month as a decimal number [1,31] in a two-digit field with leading space character fill.
%h
A synonym for %b .
%H
Hour (24-hour clock) as a decimal number [00,23].
%I
Hour (12-hour clock) as a decimal number [01,12].
%j
Day of the year as a decimal number [001,366].
%m
Month as a decimal number [01,12].
%M
Minute as a decimal number [00,59].
%n
A <newline>.
%p
Locale's equivalent of either AM or PM.
%r
12-hour clock time [01,12] using the AM/PM notation; in the POSIX locale, this shall be equivalent to %I : %M : %S %p .
%S
Seconds as a decimal number [00,60].
%t
A <tab>.
%T
24-hour clock time [00,23] in the format HH:MM:SS.
%u
Weekday as a decimal number [1,7] (1=Monday).
%U
Week of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday shall be considered to be in week 0.
%V
Week of the year (Monday as the first day of the week) as a decimal number [01,53]. If the week containing January 1 has four or more days in the new year, then it shall be considered week 1; otherwise, it shall be the last week of the previous year, and the next week shall be week 1.
%w
Weekday as a decimal number [0,6] (0=Sunday).
%W
Week of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday shall be considered to be in week 0.
%x
Locale's appropriate date representation.
%X
Locale's appropriate time representation.
%y
Year within century [00,99].
%Y
Year with century as a decimal number.
%Z
Timezone name, or no characters if no timezone is determinable.
%%
A percent sign character.

See the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.5, LC_TIME for the conversion specifier values in the POSIX locale.

Modified Conversion Specifications

Some conversion specifiers can be modified by the E and O modifier characters to indicate a different format or specification as specified in the LC_TIME locale description (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.5, LC_TIME). If the corresponding keyword (see era, era_year, era_d_fmt, and alt_digits in the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.5, LC_TIME) is not specified or not supported for the current locale, the unmodified conversion specifier value shall be used.

%Ec
Locale's alternative appropriate date and time representation.
%EC
The name of the base year (period) in the locale's alternative representation.
%Ex
Locale's alternative date representation.
%EX
Locale's alternative time representation.
%Ey
Offset from %EC (year only) in the locale's alternative representation.
%EY
Full alternative year representation.
%Od
Day of month using the locale's alternative numeric symbols.
%Oe
Day of month using the locale's alternative numeric symbols.
%OH
Hour (24-hour clock) using the locale's alternative numeric symbols.
%OI
Hour (12-hour clock) using the locale's alternative numeric symbols.
%Om
Month using the locale's alternative numeric symbols.
%OM
Minutes using the locale's alternative numeric symbols.
%OS
Seconds using the locale's alternative numeric symbols.
%Ou
Weekday as a number in the locale's alternative representation (Monday = 1).
%OU
Week number of the year (Sunday as the first day of the week) using the locale's alternative numeric symbols.
%OV
Week number of the year (Monday as the first day of the week, rules corresponding to %V ), using the locale's alternative numeric symbols.
%Ow
Weekday as a number in the locale's alternative representation (Sunday = 0).
%OW
Week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols.
%Oy
Year (offset from %C ) in alternative representation.

mmddhhmm[[cc]yy]

Attempt to set the system date and time from the value given in the operand. This is only possible if the user has appropriate privileges and the system permits the setting of the system date and time. The first mm is the month (number); dd is the day (number); hh is the hour (number, 24-hour system); the second mm is the minute (number); cc is the century and is the first two digits of the year (this is optional); yy is the last two digits of the year and is optional. If century is not specified, then values in the range [69,99] shall refer to years 1969 to 1999 inclusive, and values in the range [00,68] shall refer to years 2000 to 2068 inclusive. The current year is the default if yy is omitted.

Note:
It is expected that in a future version of IEEE Std 1003.1-2001 the default century inferred from a 2-digit year will change. (This would apply to all commands accepting a 2-digit year as input.)

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of date:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_TIME
Determine the format and contents of date and time strings written by date.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone in which the time and date are written, unless the -u option is specified. If the TZ variable is unset or null and -u is not specified, an unspecified system default timezone is used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

When no formatting operand is specified, the output in the POSIX locale shall be equivalent to specifying:

date "+%a %b %e %H:%M:%S %Z %Y"

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The date was written successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Conversion specifiers are of unspecified format when not in the POSIX locale. Some of them can contain <newline>s in some locales, so it may be difficult to use the format shown in standard output for parsing the output of date in those locales.

The range of values for %S extends from 0 to 60 seconds to accommodate the occasional leap second.

Although certain of the conversion specifiers in the POSIX locale (such as the name of the month) are shown with initial capital letters, this need not be the case in other locales. Programs using these fields may need to adjust the capitalization if the output is going to be used at the beginning of a sentence.

The date string formatting capabilities are intended for use in Gregorian-style calendars, possibly with a different starting year (or years). The %x and %c conversion specifications, however, are intended for local representation; these may be based on a different, non-Gregorian calendar.

The %C conversion specification was introduced to allow a fallback for the %EC (alternative year format base year); it can be viewed as the base of the current subdivision in the Gregorian calendar. The century number is calculated as the year divided by 100 and truncated to an integer; it should not be confused with the use of ordinal numbers for centuries (for example, "twenty-first century".) Both the %Ey and %y can then be viewed as the offset from %EC and %C , respectively.

The E and O modifiers modify the traditional conversion specifiers, so that they can always be used, even if the implementation (or the current locale) does not support the modifier.

The E modifier supports alternative date formats, such as the Japanese Emperor's Era, as long as these are based on the Gregorian calendar system. Extending the E modifiers to other date elements may provide an implementation-defined extension capable of supporting other calendar systems, especially in combination with the O modifier.

The O modifier supports time and date formats using the locale's alternative numerical symbols, such as Kanji or Hindi digits or ordinal number representation.

Non-European locales, whether they use Latin digits in computational items or not, often have local forms of the digits for use in date formats. This is not totally unknown even in Europe; a variant of dates uses Roman numerals for the months: the third day of September 1991 would be written as 3.IX.1991. In Japan, Kanji digits are regularly used for dates; in Arabic-speaking countries, Hindi digits are used. The %d , %e , %H , %I , %m , %S , %U , %w , %W , and %y conversion specifications always return the date and time field in Latin digits (that is, 0 to 9). The %O modifier was introduced to support the use for display purposes of non-Latin digits. In the LC_TIME category in localedef, the optional alt_digits keyword is intended for this purpose. As an example, assume the following (partial) localedef source:

alt_digits  "";"I";"II";"III";"IV";"V";"VI";"VII";"VIII" \
            "IX";"X";"XI";"XII"
d_fmt       "%e.%Om.%Y"

With the above date, the command:

date "+%x"

would yield 3.IX.1991. With the same d_fmt, but without the alt_digits, the command would yield 3.9.1991.

EXAMPLES

1.
The following are input/output examples of date used at arbitrary times in the POSIX locale:

$ date
Tue Jun 26 09:58:10 PDT 1990

$ date "+DATE: %m/%d/%y%nTIME: %H:%M:%S"
DATE: 11/02/91
TIME: 13:36:16

$ date "+TIME: %r"
TIME: 01:36:32 PM

2.
Examples for Denmark, where the default date and time format is %a %d %b %Y %T %Z :

$ LANG=da_DK.iso_8859-1 date
ons 02 okt 1991 15:03:32 CET

$ LANG=da_DK.iso_8859-1 \
    date "+DATO: %A den %e. %B %Y%nKLOKKEN: %H:%M:%S"
DATO: onsdag den 2. oktober 1991
KLOKKEN: 15:03:56

3.
Examples for Germany, where the default date and time format is %a %d . %h . %Y , %T %Z :

$ LANG=De_DE.88591 date
Mi 02.Okt.1991, 15:01:21 MEZ

$ LANG=De_DE.88591 date "+DATUM: %A, %d. %B %Y%nZEIT: %H:%M:%S"
DATUM: Mittwoch, 02. Oktober 1991
ZEIT: 15:02:02

4.
Examples for France, where the default date and time format is %a %d %h %Y %Z %T :

$ LANG=Fr_FR.88591 date
Mer 02 oct 1991 MET 15:03:32

$ LANG=Fr_FR.88591 date "+JOUR: %A %d %B %Y%nHEURE: %H:%M:%S"
JOUR: Mercredi 02 octobre 1991
HEURE: 15:03:56

RATIONALE

Some of the new options for formatting are from the ISO C standard. The -u option was introduced to allow portable access to Coordinated Universal Time (UTC). The string "GMT0" is allowed as an equivalent TZ value to be compatible with all of the systems using the BSD implementation, where this option originated.

The %e format conversion specification (adopted from System V) was added because the ISO C standard conversion specifications did not provide any way to produce the historical default date output during the first nine days of any month.

There are two varieties of day and week numbering supported (in addition to any others created with the locale-dependent %E and %O modifier characters):

*
The historical variety in which Sunday is the first day of the week and the weekdays preceding the first Sunday of the year are considered week 0. These are represented by %w and %U . A variant of this is %W , using Monday as the first day of the week, but still referring to week 0. This view of the calendar was retained because so many historical applications depend on it and the ISO C standard strftime() function, on which many date implementations are based, was defined in this way.

*
The international standard, based on the ISO 8601:2000 standard where Monday is the first weekday and the algorithm for the first week number is more complex: If the week (Monday to Sunday) containing January 1 has four or more days in the new year, then it is week 1; otherwise, it is week 53 of the previous year, and the next week is week 1. These are represented by the new conversion specifications %u and %V , added as a result of international comments.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, printf(), strftime()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uncompress(1p)

UNCOMPRESS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uncompress - expand compressed data

SYNOPSIS

uncompress [-cfv][file...]

DESCRIPTION

The uncompress utility shall restore files to their original state after they have been compressed using the compress utility. If no files are specified, the standard input shall be uncompressed to the standard output. If the invoking process has appropriate privileges, the ownership, modes, access time, and modification time of the original file shall be preserved.

This utility shall support the uncompressing of any files produced by the compress utility on the same implementation. For files produced by compress on other systems, uncompress supports 9 to 14-bit compression (see compress , -b); it is implementation-defined whether values of -b greater than 14 are supported.

OPTIONS

The uncompress utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Write to standard output; no files are changed.
-f
Do not prompt for overwriting files. Except when run in the background, if -f is not given the user shall be prompted as to whether an existing file should be overwritten. If the standard input is not a terminal and -f is not given, uncompress shall write a diagnostic message to standard error and exit with a status greater than zero.
-v
Write messages to standard error concerning the expansion of each file.

OPERANDS

The following operand shall be supported:

file
A pathname of a file. If file already has the .Z suffix specified, it shall be used as the input file and the output file shall be named file with the .Z suffix removed. Otherwise, file shall be used as the name of the output file and file with the .Z suffix appended shall be used as the input file.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' .

INPUT FILES

Input files shall be in the format produced by the compress utility.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uncompress:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

When there are no file operands or the -c option is specified, the uncompressed output is written to standard output.

STDERR

Prompts shall be written to the standard error output under the conditions specified in the DESCRIPTION and OPTIONS sections. The prompts shall contain the file pathname, but their format is otherwise unspecified. Otherwise, the standard error output shall be used only for diagnostic messages.

OUTPUT FILES

Output files are the same as the respective input files to compress.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

The input file remains unmodified.

The following sections are informative.

APPLICATION USAGE

The limit of 14 on the compress -b bits argument is to achieve portability to all systems (within the restrictions imposed by the lack of an explicit published file format). Some implementations based on 16-bit architectures cannot support 15 or 16-bit uncompression.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

compress , zcat

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uname(1p)

UNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uname - return system name

SYNOPSIS

uname [-snrvma]

DESCRIPTION

By default, the uname utility shall write the operating system name to standard output. When options are specified, symbols representing one or more system characteristics shall be written to the standard output. The format and contents of the symbols are implementation-defined. On systems conforming to the System Interfaces volume of IEEE Std 1003.1-2001, the symbols written shall be those supported by the uname() function as defined in the System Interfaces volume of IEEE Std 1003.1-2001.

OPTIONS

The uname utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Behave as though all of the options -mnrsv were specified.
-m
Write the name of the hardware type on which the system is running to standard output.
-n
Write the name of this node within an implementation-defined communications network.
-r
Write the current release level of the operating system implementation.
-s
Write the name of the implementation of the operating system.
-v
Write the current version level of this release of the operating system implementation.

If no options are specified, the uname utility shall write the operating system name, as if the -s option had been specified.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uname:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

By default, the output shall be a single line of the following form:

"%s\n", <sysname>

If the -a option is specified, the output shall be a single line of the following form:

"%s %s %s %s %s\n", <sysname>, <nodename>, <release>,
    <version>, <machine>

Additional implementation-defined symbols may be written; all such symbols shall be written at the end of the line of output before the <newline>.

If options are specified to select different combinations of the symbols, only those symbols shall be written, in the order shown above for the -a option. If a symbol is not selected for writing, its corresponding trailing <blank>s also shall not be written.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The requested information was successfully written.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Note that any of the symbols could include embedded <space>s, which may affect parsing algorithms if multiple options are selected for output.

The node name is typically a name that the system uses to identify itself for inter-system communication addressing.

EXAMPLES

The following command:

uname -sr

writes the operating system name and release level, separated by one or more <blank>s.

RATIONALE

It was suggested that this utility cannot be used portably since the format of the symbols is implementation-defined. The POSIX.1 working group could not achieve consensus on defining these formats in the underlying uname() function, and there was no expectation that this volume of IEEE Std 1003.1-2001 would be any more successful. Some applications may still find this historical utility of value. For example, the symbols could be used for system log entries or for comparison with operator or user input.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, uname()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


localedef(1p)

LOCALEDEF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

localedef - define locale environment

SYNOPSIS

localedef [-c][-f charmap][-i sourcefile][-u code_set_name] name

DESCRIPTION

The localedef utility shall convert source definitions for locale categories into a format usable by the functions and utilities whose operational behavior is determined by the setting of the locale environment variables defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale. It is implementation-defined whether users have the capability to create new locales, in addition to those supplied by the implementation. If the symbolic constant POSIX2_LOCALEDEF is defined, the system supports the creation of new locales. On XSI-conformant systems, the symbolic constant POSIX2_LOCALEDEF shall be defined.

The utility shall read source definitions for one or more locale categories belonging to the same locale from the file named in the -i option (if specified) or from standard input.

The name operand identifies the target locale. The utility shall support the creation of public, or generally accessible locales, as well as private, or restricted-access locales. Implementations may restrict the capability to create or modify public locales to users with the appropriate privileges.

Each category source definition shall be identified by the corresponding environment variable name and terminated by an END category-name statement. The following categories shall be supported. In addition, the input may contain source for implementation-defined categories.

LC_CTYPE
Defines character classification and case conversion.
LC_COLLATE

Defines collation rules.

LC_MONETARY

Defines the format and symbols used in formatting of monetary information.

LC_NUMERIC

Defines the decimal delimiter, grouping, and grouping symbol for non-monetary numeric editing.

LC_TIME
Defines the format and content of date and time information.
LC_MESSAGES

Defines the format and values of affirmative and negative responses.

OPTIONS

The localedef utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Create permanent output even if warning messages have been issued.
-f charmap
Specify the pathname of a file containing a mapping of character symbols and collating element symbols to actual character encodings. The format of the charmap is described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.4, Character Set Description File. The application shall ensure that this option is specified if symbolic names (other than collating symbols defined in a collating-symbol keyword) are used. If the -f option is not present, an implementation-defined character mapping shall be used.
-i inputfile
The pathname of a file containing the source definitions. If this option is not present, source definitions shall be read from standard input. The format of the inputfile is described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3, Locale Definition.
-u code_set_name

Specify the name of a codeset used as the target mapping of character symbols and collating element symbols whose encoding values are defined in terms of the ISO/IEC 10646-1:2000 standard position constant values.

OPERANDS

The following operand shall be supported:

name
Identifies the locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale for a description of the use of this name. If the name contains one or more slash characters, name shall be interpreted as a pathname where the created locale definitions shall be stored. If name does not contain any slash characters, the interpretation of the name is implementation-defined and the locale shall be public. This capability may be restricted to users with appropriate privileges. (As a consequence of specifying one name, although several categories can be processed in one execution, only categories belonging to the same locale can be processed.)

STDIN

Unless the -i option is specified, the standard input shall be a text file containing one or more locale category source definitions, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3, Locale Definition. When lines are continued using the escape character mechanism, there is no limit to the length of the accumulated continued line.

INPUT FILES

The character set mapping file specified as the charmap option-argument is described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.4, Character Set Description File. If a locale category source definition contains a copy statement, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, and the copy statement names a valid, existing locale, then localedef shall behave as if the source definition had contained a valid category source definition for the named locale.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of localedef:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

(This variable has no affect on localedef; the POSIX locale is used for this category.)

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files). This variable has no affect on the processing of localedef input data; the POSIX locale is used for this purpose, regardless of the value of this variable.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The utility shall report all categories successfully processed, in an unspecified format.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The format of the created output is unspecified. If the name operand does not contain a slash, the existence of an output file for the locale is unspecified.

EXTENDED DESCRIPTION

When the -u option is used, the code_set_name option-argument shall be interpreted as an implementation-defined name of a codeset to which the ISO/IEC 10646-1:2000 standard position constant values shall be converted via an implementation-defined method. Both the ISO/IEC 10646-1:2000 standard position constant values and other formats (decimal, hexadecimal, or octal) shall be valid as encoding values within the charmap file. The codeset represented by the implementation-defined name can be any codeset that is supported by the implementation.

When conflicts occur between the charmap specification of <code_set_name>, <mb_cur_max>, or <mb_cur_min> and the implementation-defined interpretation of these respective items for the codeset represented by the -u option-argument code_set_name, the result is unspecified.

When conflicts occur between the charmap encoding values specified for symbolic names of characters of the portable character set and the implementation-defined assignment of character encoding values, the result is unspecified.

If a non-printable character in the charmap has a width specified that is not -1, localedef shall generate a warning.

EXIT STATUS

The following exit values shall be returned:

0
No errors occurred and the locales were successfully created.
1
Warnings occurred and the locales were successfully created.
2
The locale specification exceeded implementation limits or the coded character set or sets used were not supported by the implementation, and no locale was created.
3
The capability to create new locales is not supported by the implementation.
>3
Warnings or errors occurred and no output was created.

CONSEQUENCES OF ERRORS

If an error is detected, no permanent output shall be created.

If warnings occur, permanent output shall be created if the -c option was specified. The following conditions shall cause warning messages to be issued:

*
If a symbolic name not found in the charmap file is used for the descriptions of the LC_CTYPE or LC_COLLATE categories (for other categories, this shall be an error condition).

*
If the number of operands to the order keyword exceeds the {COLL_WEIGHTS_MAX} limit.

*
If optional keywords not supported by the implementation are present in the source.

*
If a non-printable character has a width specified other than -1.

Other implementation-defined conditions may also cause warnings.

The following sections are informative.

APPLICATION USAGE

The charmap definition is optional, and is contained outside the locale definition. This allows both completely self-defined source files, and generic sources (applicable to more than one codeset). To aid portability, all charmap definitions must use the same symbolic names for the portable character set. As explained in the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.4, Character Set Description File, it is implementation-defined whether or not users or applications can provide additional character set description files. Therefore, the -f option might be operable only when an implementation-defined charmap is named.

EXAMPLES

None.

RATIONALE

The output produced by the localedef utility is implementation-defined. The name operand is used to identify the specific locale. (As a consequence, although several categories can be processed in one execution, only categories belonging to the same locale can be processed.)

FUTURE DIRECTIONS

None.

SEE ALSO

locale , the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3, Locale Definition

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qrerun(1p)

QRERUN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qrerun - rerun batch jobs

SYNOPSIS

qrerun job_identifier ...

DESCRIPTION

To rerun a batch job is to terminate the session leader of the batch job, delete any associated checkpoint files, and return the batch job to the batch queued state. A batch job is rerun by a request to the batch server that manages the batch job. The qrerun utility is a user-accessible batch client that requests the rerunning of one or more batch jobs.

The qrerun utility shall rerun those batch jobs for which a batch job_identifier is presented to the utility.

The qrerun utility shall rerun batch jobs in the order in which their batch job_identifiers are presented to the utility.

If the qrerun utility fails to process any batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

The qrerun utility shall rerun batch jobs by sending a Rerun Job Request to the batch server that manages each batch job.

For each successfully processed batch job_identifier, the qrerun utility shall have rerun the corresponding batch job at the time the utility exits.

OPTIONS

None.

OPERANDS

The qrerun utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qrerun:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qrerun utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qrerun utility waits to output the diagnostic message while attempting to locate the job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qrerun utility allows users to cause jobs in the running state to exit and rerun.

The qrerun utility is a new utility, vis-a-vis existing practice, that has been defined in this volume of IEEE Std 1003.1-2001 to correct user-perceived deficiencies in the existing practice.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctags(1p)

CTAGS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ctags - create a tags file (DEVELOPMENT, FORTRAN)

SYNOPSIS

ctags [-a][-f tagsfile] pathname ...

ctags -x pathname ...

DESCRIPTION

The ctags utility shall be provided on systems that support the User Portability Utilities option, the Software Development Utilities option, and either or both of the C-Language Development Utilities option and FORTRAN Development Utilities option. On other systems, it is optional.

The ctags utility shall write a tagsfile or an index of objects from C-language or FORTRAN source files specified by the pathname operands. The tagsfile shall list the locators of language-specific objects within the source files. A locator consists of a name, pathname, and either a search pattern or a line number that can be used in searching for the object definition. The objects that shall be recognized are specified in the EXTENDED DESCRIPTION section.

OPTIONS

The ctags utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Append to tagsfile.
-f tagsfile
Write the object locator lists into tagsfile instead of the default file named tags in the current directory.
-x
Produce a list of object names, the line number, and filename in which each is defined, as well as the text of that line, and write this to the standard output. A tagsfile shall not be created when -x is specified.

OPERANDS

The following pathname operands are supported:

file.c
Files with basenames ending with the .c suffix shall be treated as C-language source code. Such files that are not valid input to c99 produce unspecified results.
file.h
Files with basenames ending with the .h suffix shall be treated as C-language source code. Such files that are not valid input to c99 produce unspecified results.
file.f
Files with basenames ending with the .f suffix shall be treated as FORTRAN-language source code. Such files that are not valid input to fort77 produce unspecified results.

The handling of other files is implementation-defined.

STDIN

See the INPUT FILES section.

INPUT FILES

The input files shall be text files containing source code in the language indicated by the operand filename suffixes.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ctags:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the order in which output is sorted for the -x option. The POSIX locale determines the order in which the tagsfile is written.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files). When processing C-language source code, if the locale is not compatible with the C locale described by the ISO C standard, the results are unspecified.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The list of object name information produced by the -x option shall be written to standard output in the following format:

"%s %d %s %s", <object-name>, <line-number>, <filename>, <text>

where <text> is the text of line <line-number> of file <filename>.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

When the -x option is not specified, the format of the output file shall be:

"%s\t%s\t/%s/\n", <identifier>, <filename>, <pattern>

where <pattern> is a search pattern that could be used by an editor to find the defining instance of <identifier> in <filename> (where defining instance is indicated by the declarations listed in the EXTENDED DESCRIPTION).

An optional circumflex ( '^' ) can be added as a prefix to <pattern>, and an optional dollar sign can be appended to <pattern> to indicate that the pattern is anchored to the beginning (end) of a line of text. Any slash or backslash characters in <pattern> shall be preceded by a backslash character. The anchoring circumflex, dollar sign, and escaping backslash characters shall not be considered part of the search pattern. All other characters in the search pattern shall be considered literal characters.

An alternative format is:

"%s\t%s\t?%s?\n", <identifier>, <filename>, <pattern>

which is identical to the first format except that slashes in <pattern> shall not be preceded by escaping backslash characters, and question mark characters in <pattern> shall be preceded by backslash characters.

A second alternative format is:

"%s\t%s\t%d\n", <identifier>, <filename>, <lineno>

where <lineno> is a decimal line number that could be used by an editor to find <identifier> in <filename>.

Neither alternative format shall be produced by ctags when it is used as described by IEEE Std 1003.1-2001, but the standard utilities that process tags files shall be able to process those formats as well as the first format.

In any of these formats, the file shall be sorted by identifier, based on the collation sequence in the POSIX locale.

EXTENDED DESCRIPTION

If the operand identifies C-language source, the ctags utility shall attempt to produce an output line for each of the following objects:

*
Function definitions

*
Type definitions

*
Macros with arguments

It may also produce output for any of the following objects:

*
Function prototypes

*
Structures

*
Unions

*
Global variable definitions

*
Enumeration types

*
Macros without arguments

*
#define statements

*
#line statements

Any #if and #ifdef statements shall produce no output. The tag main is treated specially in C programs. The tag formed shall be created by prefixing M to the name of the file, with the trailing .c, and leading pathname components (if any) removed.

On systems that do not support the C-Language Development Utilities option, ctags produces unspecified results for C-language source code files. It should write to standard error a message identifying this condition and cause a non-zero exit status to be produced.

If the operand identifies FORTRAN source, the ctags utility shall produce an output line for each function definition. It may also produce output for any of the following objects:

*
Subroutine definitions

*
COMMON statements

*
PARAMETER statements

*
DATA and BLOCK DATA statements

*
Statement numbers

On systems that do not support the FORTRAN Development Utilities option, ctags produces unspecified results for FORTRAN source code files. It should write to standard error a message identifying this condition and cause a non-zero exit status to be produced.

It is implementation-defined what other objects (including duplicate identifiers) produce output.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The output with -x is meant to be a simple index that can be written out as an off-line readable function index. If the input files to ctags (such as .c files) were not created using the same locale as that in effect when ctags -x is run, results might not be as expected.

The description of C-language processing says "attempts to" because the C language can be greatly confused, especially through the use of #defines, and this utility would be of no use if the real C preprocessor were run to identify them. The output from ctags may be fooled and incorrect for various constructs.

EXAMPLES

None.

RATIONALE

The option list was significantly reduced from that provided by historical implementations. The -F option was omitted as redundant, since it is the default. The -B option was omitted as being of very limited usefulness. The -t option was omitted since the recognition of typedefs is now required for C source files. The -u option was omitted because the update function was judged to be not only inefficient, but also rarely needed.

An early proposal included a -w option to suppress warning diagnostics. Since the types of such diagnostics could not be described, the option was omitted as being not useful.

The text for LC_CTYPE about compatibility with the C locale acknowledges that the ISO C standard imposes requirements on the locale used to process C source. This could easily be a superset of that known as "the C locale" by way of implementation extensions, or one of a few alternative locales for systems supporting different codesets. No statement is made for FORTRAN because the ANSI X3.9-1978 standard (FORTRAN 77) does not (yet) define a similar locale concept. However, a general rule in this volume of IEEE Std 1003.1-2001 is that any time that locales do not match (preparing a file for one locale and processing it in another), the results are suspect.

The collation sequence of the tags file is not affected by LC_COLLATE because it is typically not used by human readers, but only by programs such as vi to locate the tag within the source files. Using the POSIX locale eliminates some of the problems of coordinating locales between the ctags file creator and the vi file reader.

Historically, the tags file has been used only by ex and vi. However, the format of the tags file has been published to encourage other programs to use the tags in new ways. The format allows either patterns or line numbers to find the identifiers because the historical vi recognizes either. The ctags utility does not produce the format using line numbers because it is not useful following any source file changes that add or delete lines. The documented search patterns match historical practice. It should be noted that literal leading circumflex or trailing dollar-sign characters in the search pattern will only behave correctly if anchored to the beginning of the line or end of the line by an additional circumflex or dollar-sign character.

Historical implementations also understand the objects used by the languages Pascal and sometimes LISP, and they understand the C source output by lex and yacc. The ctags utility is not required to accommodate these languages, although implementors are encouraged to do so.

The following historical option was not specified, as vgrind is not included in this volume of IEEE Std 1003.1-2001:

-v
If the -v flag is given, an index of the form expected by vgrind is produced on the standard output. This listing contains the function name, filename, and page number (assuming 64-line pages). Since the output is sorted into lexicographic order, it may be desired to run the output through sort -f. Sample use:

ctags -v files | sort -f > index vgrind -x index

The special treatment of the tag main makes the use of ctags practical in directories with more than one program.

FUTURE DIRECTIONS

None.

SEE ALSO

c99 , fort77 , vi

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


comm(1p)

COMM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

comm - select or reject lines common to two files

SYNOPSIS

comm [-123] file1 file2

DESCRIPTION

The comm utility shall read file1 and file2, which should be ordered in the current collating sequence, and produce three text columns as output: lines only in file1, lines only in file2, and lines in both files.

If the lines in both files are not ordered according to the collating sequence of the current locale, the results are unspecified.

OPTIONS

The comm utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-1
Suppress the output column of lines unique to file1.
-2
Suppress the output column of lines unique to file2.
-3
Suppress the output column of lines duplicated in file1 and file2.

OPERANDS

The following operands shall be supported:

file1
A pathname of the first file to be compared. If file1 is '-' , the standard input shall be used.
file2
A pathname of the second file to be compared. If file2 is '-' , the standard input shall be used.

If both file1 and file2 refer to standard input or to the same FIFO special, block special, or character special file, the results are undefined.

STDIN

The standard input shall be used only if one of the file1 or file2 operands refers to standard input. See the INPUT FILES section.

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of comm:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the collating sequence comm expects to have been used when the input files were sorted.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The comm utility shall produce output depending on the options selected. If the -1, -2, and -3 options are all selected, comm shall write nothing to standard output.

If the -1 option is not selected, lines contained only in file1 shall be written using the format:

"%s\n", <line in file1>

If the -2 option is not selected, lines contained only in file2 are written using the format:

"%s%s\n", <lead>, <line in file2>

where the string <lead> is as follows:

<tab>
The -1 option is not selected.
null string
The -1 option is selected.

If the -3 option is not selected, lines contained in both files shall be written using the format:

"%s%s\n", <lead>, <line in both>

where the string <lead> is as follows:

<tab><tab>
Neither the -1 nor the -2 option is selected.
<tab>
Exactly one of the -1 and -2 options is selected.
null string
Both the -1 and -2 options are selected.

If the input files were ordered according to the collating sequence of the current locale, the lines written shall be in the collating sequence of the original lines.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were successfully output as specified.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

If the input files are not properly presorted, the output of comm might not be useful.

EXAMPLES

If a file named xcu contains a sorted list of the utilities in this volume of IEEE Std 1003.1-2001, a file named xpg3 contains a sorted list of the utilities specified in the X/Open Portability Guide, Issue 3, and a file named svid89 contains a sorted list of the utilities in the System V Interface Definition Third Edition:

comm -23 xcu xpg3 | comm -23 - svid89

would print a list of utilities in this volume of IEEE Std 1003.1-2001 not specified by either of the other documents:

comm -12 xcu xpg3 | comm -12 - svid89

would print a list of utilities specified by all three documents, and:

comm -12 xpg3 svid89 | comm -23 - xcu

would print a list of utilities specified by both XPG3 and the SVID, but not specified in this volume of IEEE Std 1003.1-2001.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cmp , diff , sort , uniq

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


jobs(1p)

JOBS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

jobs - display status of jobs in the current session

SYNOPSIS

jobs [-l| -p][job_id...]

DESCRIPTION

The jobs utility shall display the status of jobs that were started in the current shell environment; see Shell Execution Environment .

When jobs reports the termination status of a job, the shell shall remove its process ID from the list of those "known in the current shell execution environment''; see Asynchronous Lists .

OPTIONS

The jobs utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-l
(The letter ell.) Provide more information about each job listed. This information shall include the job number, current job, process group ID, state, and the command that formed the job.
-p
Display only the process IDs for the process group leaders of the selected jobs.

By default, the jobs utility shall display the status of all stopped jobs, running background jobs and all jobs whose status has changed and have not been reported by the shell.

OPERANDS

The following operand shall be supported:

job_id
Specifies the jobs for which the status is to be displayed. If no job_id is given, the status information for all jobs shall be displayed. The format of job_id is described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.203, Job Control Job ID.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of jobs:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If the -p option is specified, the output shall consist of one line for each process ID:

"%d\n", <process ID>

Otherwise, if the -l option is not specified, the output shall be a series of lines of the form:

"[%d] %c %s %s\n", <job-number>, <current>, <state>, <command>

where the fields shall be as follows:

<current>
The character '+' identifies the job that would be used as a default for the fg or bg utilities; this job can also be specified using the job_id %+ or "%%" . The character '-' identifies the job that would become the default if the current default job were to exit; this job can also be specified using the job_id %-. For other jobs, this field is a <space>. At most one job can be identified with '+' and at most one job can be identified with '-' . If there is any suspended job, then the current job shall be a suspended job. If there are at least two suspended jobs, then the previous job also shall be a suspended job.
<job-number>
A number that can be used to identify the process group to the wait, fg, bg, and kill utilities. Using these utilities, the job can be identified by prefixing the job number with '%' .
<state>
One of the following strings (in the POSIX locale):
Running
Indicates that the job has not been suspended by a signal and has not exited.
Done
Indicates that the job completed and returned exit status zero.
Done(code)
Indicates that the job completed normally and that it exited with the specified non-zero exit status, code, expressed as a decimal number.
Stopped
Indicates that the job was suspended by the SIGTSTP signal.
Stopped (SIGTSTP)

Indicates that the job was suspended by the SIGTSTP signal.

Stopped (SIGSTOP)

Indicates that the job was suspended by the SIGSTOP signal.

Stopped (SIGTTIN)

Indicates that the job was suspended by the SIGTTIN signal.

Stopped (SIGTTOU)

Indicates that the job was suspended by the SIGTTOU signal.

The implementation may substitute the string Suspended in place of Stopped. If the job was terminated by a signal, the format of <state> is unspecified, but it shall be visibly distinct from all of the other <state> formats shown here and shall indicate the name or description of the signal causing the termination.

<command>
The associated command that was given to the shell.

If the -l option is specified, a field containing the process group ID shall be inserted before the <state> field. Also, more processes in a process group may be output on separate lines, using only the process ID and <command> fields.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The -p option is the only portable way to find out the process group of a job because different implementations have different strategies for defining the process group of the job. Usage such as $( jobs -p) provides a way of referring to the process group of the job in an implementation-independent way.

The jobs utility does not work as expected when it is operating in its own utility execution environment because that environment has no applicable jobs to manipulate. See the APPLICATION USAGE section for bg . For this reason, jobs is generally implemented as a shell regular built-in.

EXAMPLES

None.

RATIONALE

Both "%%" and "%+" are used to refer to the current job. Both forms are of equal validity-the "%%" mirroring "$$" and "%+" mirroring the output of jobs. Both forms reflect historical practice of the KornShell and the C shell with job control.

The job control features provided by bg, fg, and jobs are based on the KornShell. The standard developers examined the characteristics of the C shell versions of these utilities and found that differences exist. Despite widespread use of the C shell, the KornShell versions were selected for this volume of IEEE Std 1003.1-2001 to maintain a degree of uniformity with the rest of the KornShell features selected (such as the very popular command line editing features).

The jobs utility is not dependent on the job control option, as are the seemingly related bg and fg utilities because jobs is useful for examining background jobs, regardless of the condition of job control. When the user has invoked a set +m command and job control has been turned off, jobs can still be used to examine the background jobs associated with that current session. Similarly, kill can then be used to kill background jobs with kill% <background job number>.

The output for terminated jobs is left unspecified to accommodate various historical systems. The following formats have been witnessed:

1.
Killed( signal name)

2.
signal name

3.
signal name( coredump)

4.
signal description- core dumped

Most users should be able to understand these formats, although it means that applications have trouble parsing them.

The calculation of job IDs was not described since this would suggest an implementation, which may impose unnecessary restrictions.

In an early proposal, a -n option was included to "Display the status of jobs that have changed, exited, or stopped since the last status report". It was removed because the shell always writes any changed status of jobs before each prompt.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Execution Environment , bg , fg , kill() , wait()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


shift(1p)

SHIFT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shift - shift positional parameters

SYNOPSIS

shift [n]

DESCRIPTION

The positional parameters shall be shifted. Positional parameter 1 shall be assigned the value of parameter (1+n), parameter 2 shall be assigned the value of parameter (2+n), and so on. The parameters represented by the numbers "$#" down to "$#-n+1" shall be unset, and the parameter '#' is updated to reflect the new number of positional parameters.

The value n shall be an unsigned decimal integer less than or equal to the value of the special parameter '#' . If n is not given, it shall be assumed to be 1. If n is 0, the positional and special parameters are not changed.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The exit status is >0 if n>$#; otherwise, it is zero.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

$ set a b c d e
$ shift 2
$ echo $*
c d e

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


yacc(1p)

YACC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

yacc - yet another compiler compiler (DEVELOPMENT)

SYNOPSIS

yacc [-dltv][-b file_prefix][-p sym_prefix] grammar

DESCRIPTION

The yacc utility shall read a description of a context-free grammar in grammar and write C source code, conforming to the ISO C standard, to a code file, and optionally header information into a header file, in the current directory. The C code shall define a function and related routines and macros for an automaton that executes a parsing algorithm meeting the requirements in Algorithms .

The form and meaning of the grammar are described in the EXTENDED DESCRIPTION section.

The C source code and header file shall be produced in a form suitable as input for the C compiler (see c99 ).

OPTIONS

The yacc utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-b file_prefix
Use file_prefix instead of y as the prefix for all output filenames. The code file y.tab.c, the header file y.tab.h (created when -d is specified), and the description file y.output (created when -v is specified), shall be changed to file_prefix .tab.c, file_prefix .tab.h, and file_prefix .output, respectively.
-d
Write the header file; by default only the code file is written. The #define statements associate the token codes assigned by yacc with the user-declared token names. This allows source files other than y.tab.c to access the token codes.
-l
Produce a code file that does not contain any #line constructs. If this option is not present, it is unspecified whether the code file or header file contains #line directives. This should only be used after the grammar and the associated actions are fully debugged.
-p sym_prefix

Use sym_prefix instead of yy as the prefix for all external names produced by yacc. The names affected shall include the functions yyparse(), yylex(), and yyerror(), and the variables yylval, yychar, and yydebug. (In the remainder of this section, the six symbols cited are referenced using their default names only as a notational convenience.) Local names may also be affected by the -p option; however, the -p option shall not affect #define symbols generated by yacc.

-t
Modify conditional compilation directives to permit compilation of debugging code in the code file. Runtime debugging statements shall always be contained in the code file, but by default conditional compilation directives prevent their compilation.
-v
Write a file containing a description of the parser and a report of conflicts generated by ambiguities in the grammar.

OPERANDS

The following operand is required:

grammar
A pathname of a file containing instructions, hereafter called grammar, for which a parser is to be created. The format for the grammar is described in the EXTENDED DESCRIPTION section.

STDIN

Not used.

INPUT FILES

The file grammar shall be a text file formatted as specified in the EXTENDED DESCRIPTION section.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of yacc:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

The LANG and LC_* variables affect the execution of the yacc utility as stated. The main() function defined in Yacc Library shall call:

setlocale(LC_ALL, "")

and thus the program generated by yacc shall also be affected by the contents of these variables at runtime.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

If shift/reduce or reduce/reduce conflicts are detected in grammar, yacc shall write a report of those conflicts to the standard error in an unspecified format.

Standard error shall also be used for diagnostic messages.

OUTPUT FILES

The code file, the header file, and the description file shall be text files. All are described in the following sections.

Code File

This file shall contain the C source code for the yyparse() function. It shall contain code for the various semantic actions with macro substitution performed on them as described in the EXTENDED DESCRIPTION section. It also shall contain a copy of the #define statements in the header file. If a %union declaration is used, the declaration for YYSTYPE shall also be included in this file.

Header File

The header file shall contain #define statements that associate the token numbers with the token names. This allows source files other than the code file to access the token codes. If a %union declaration is used, the declaration for YYSTYPE and an extern YYSTYPE yylval declaration shall also be included in this file.

Description File

The description file shall be a text file containing a description of the state machine corresponding to the parser, using an unspecified format. Limits for internal tables (see Limits ) shall also be reported, in an implementation-defined manner. (Some implementations may use dynamic allocation techniques and have no specific limit values to report.)

EXTENDED DESCRIPTION

The yacc command accepts a language that is used to define a grammar for a target language to be parsed by the tables and code generated by yacc. The language accepted by yacc as a grammar for the target language is described below using the yacc input language itself.

The input grammar includes rules describing the input structure of the target language and code to be invoked when these rules are recognized to provide the associated semantic action. The code to be executed shall appear as bodies of text that are intended to be C-language code. The C-language inclusions are presumed to form a correct function when processed by yacc into its output files. The code included in this way shall be executed during the recognition of the target language.

Given a grammar, the yacc utility generates the files described in the OUTPUT FILES section. The code file can be compiled and linked using c99. If the declaration and programs sections of the grammar file did not include definitions of main(), yylex(), and yyerror(), the compiled output requires linking with externally supplied versions of those functions. Default versions of main() and yyerror() are supplied in the yacc library and can be linked in by using the -l y operand to c99. The yacc library interfaces need not support interfaces with other than the default yy symbol prefix. The application provides the lexical analyzer function, yylex(); the lex utility is specifically designed to generate such a routine.

Input Language

The application shall ensure that every specification file consists of three sections in order: declarations, grammar rules, and programs, separated by double percent signs ( "%%" ). The declarations and programs sections can be empty. If the latter is empty, the preceding "%%" mark separating it from the rules section can be omitted.

The input is free form text following the structure of the grammar defined below.

Lexical Structure of the Grammar

The <blank>s, <newline>s, and <form-feed>s shall be ignored, except that the application shall ensure that they do not appear in names or multi-character reserved symbols. Comments shall be enclosed in "/* ... */" , and can appear wherever a name is valid.

Names are of arbitrary length, made up of letters, periods ( '.' ), underscores ( '_' ), and non-initial digits. Uppercase and lowercase letters are distinct. Conforming applications shall not use names beginning in yy or YY since the yacc parser uses such names. Many of the names appear in the final output of yacc, and thus they should be chosen to conform with any additional rules created by the C compiler to be used. In particular they appear in #define statements.

A literal shall consist of a single character enclosed in single-quotes ( '" ). All of the escape sequences supported for character constants by the ISO C standard shall be supported by yacc.

The relationship with the lexical analyzer is discussed in detail below.

The application shall ensure that the NUL character is not used in grammar rules or literals.

Declarations Section

The declarations section is used to define the symbols used to define the target language and their relationship with each other. In particular, much of the additional information required to resolve ambiguities in the context-free grammar for the target language is provided here.

Usually yacc assigns the relationship between the symbolic names it generates and their underlying numeric value. The declarations section makes it possible to control the assignment of these values.

It is also possible to keep semantic information associated with the tokens currently on the parse stack in a user-defined C-language union, if the members of the union are associated with the various names in the grammar. The declarations section provides for this as well.

The first group of declarators below all take a list of names as arguments. That list can optionally be preceded by the name of a C union member (called a tag below) appearing within '<' and '>' . (As an exception to the typographical conventions of the rest of this volume of IEEE Std 1003.1-2001, in this case <tag> does not represent a metavariable, but the literal angle bracket characters surrounding a symbol.) The use of tag specifies that the tokens named on this line shall be of the same C type as the union member referenced by tag. This is discussed in more detail below.

For lists used to define tokens, the first appearance of a given token can be followed by a positive integer (as a string of decimal digits). If this is done, the underlying value assigned to it for lexical purposes shall be taken to be that number.

The following declares name to be a token:

%token [<tag>] name [number][name [number]]...

If tag is present, the C type for all tokens on this line shall be declared to be the type referenced by tag. If a positive integer, number, follows a name, that value shall be assigned to the token.

The following declares name to be a token, and assigns precedence to it:

%left [<tag>] name [number][name [number]]...
%right [<tag>] name [number][name [number]]...

One or more lines, each beginning with one of these symbols, can appear in this section. All tokens on the same line have the same precedence level and associativity; the lines are in order of increasing precedence or binding strength. %left denotes that the operators on that line are left associative, and %right similarly denotes right associative operators. If tag is present, it shall declare a C type for names as described for %token.

The following declares name to be a token, and indicates that this cannot be used associatively:

%nonassoc [<tag>] name [number][name [number]]...

If the parser encounters associative use of this token it reports an error. If tag is present, it shall declare a C type for names as described for %token.

The following declares that union member names are non-terminals, and thus it is required to have a tag field at its beginning:

%type <tag> name...

Because it deals with non-terminals only, assigning a token number or using a literal is also prohibited. If this construct is present, yacc shall perform type checking; if this construct is not present, the parse stack shall hold only the int type.

Every name used in grammar not defined by a %token, %left, %right, or %nonassoc declaration is assumed to represent a non-terminal symbol. The yacc utility shall report an error for any non-terminal symbol that does not appear on the left side of at least one grammar rule.

Once the type, precedence, or token number of a name is specified, it shall not be changed. If the first declaration of a token does not assign a token number, yacc shall assign a token number. Once this assignment is made, the token number shall not be changed by explicit assignment.

The following declarators do not follow the previous pattern.

The following declares the non-terminal name to be the start symbol, which represents the largest, most general structure described by the grammar rules:

%start name

By default, it is the left-hand side of the first grammar rule; this default can be overridden with this declaration.

The following declares the yacc value stack to be a union of the various types of values desired:

%union { body of union (in C) }

By default, the values returned by actions (see below) and the lexical analyzer shall be of type int. The yacc utility keeps track of types, and it shall insert corresponding union member names in order to perform strict type checking of the resulting parser.

Alternatively, given that at least one <tag> construct is used, the union can be declared in a header file (which shall be included in the declarations section by using a #include construct within %{ and %}), and a typedef used to define the symbol YYSTYPE to represent this union. The effect of %union is to provide the declaration of YYSTYPE directly from the yacc input.

C-language declarations and definitions can appear in the declarations section, enclosed by the following marks:

%{ ... %}

These statements shall be copied into the code file, and have global scope within it so that they can be used in the rules and program sections.

The application shall ensure that the declarations section is terminated by the token %%.

Grammar Rules in yacc

The rules section defines the context-free grammar to be accepted by the function yacc generates, and associates with those rules C-language actions and additional precedence information. The grammar is described below, and a formal definition follows.

The rules section is comprised of one or more grammar rules. A grammar rule has the form:

A : BODY ;

The symbol A represents a non-terminal name, and BODY represents a sequence of zero or more names, literals, and semantic actions that can then be followed by optional precedence rules. Only the names and literals participate in the formation of the grammar; the semantic actions and precedence rules are used in other ways. The colon and the semicolon are yacc punctuation. If there are several successive grammar rules with the same left-hand side, the vertical bar '|' can be used to avoid rewriting the left-hand side; in this case the semicolon appears only after the last rule. The BODY part can be empty (or empty of names and literals) to indicate that the non-terminal symbol matches the empty string.

The yacc utility assigns a unique number to each rule. Rules using the vertical bar notation are distinct rules. The number assigned to the rule appears in the description file.

The elements comprising a BODY are:

name, literal
These form the rules of the grammar: name is either a token or a non-terminal; literal stands for itself (less the lexically required quotation marks).
semantic action

With each grammar rule, the user can associate actions to be performed each time the rule is recognized in the input process. (Note that the word "action" can also refer to the actions of the parser-shift, reduce, and so on.)

These actions can return values and can obtain the values returned by previous actions. These values are kept in objects of type YYSTYPE (see %union). The result value of the action shall be kept on the parse stack with the left-hand side of the rule, to be accessed by other reductions as part of their right-hand side. By using the <tag> information provided in the declarations section, the code generated by yacc can be strictly type checked and contain arbitrary information. In addition, the lexical analyzer can provide the same kinds of values for tokens, if desired.

An action is an arbitrary C statement and as such can do input or output, call subprograms, and alter external variables. An action is one or more C statements enclosed in curly braces '{' and '}' .

Certain pseudo-variables can be used in the action. These are macros for access to data structures known internally to yacc.

$$
The value of the action can be set by assigning it to $$. If type checking is enabled and the type of the value to be assigned cannot be determined, a diagnostic message may be generated.
$number
This refers to the value returned by the component specified by the token number in the right side of a rule, reading from left to right; number can be zero or negative. If number is zero or negative, it refers to the data associated with the name on the parser's stack preceding the leftmost symbol of the current rule. (That is, "$0" refers to the name immediately preceding the leftmost name in the current rule to be found on the parser's stack and "$-1" refers to the symbol to its left.) If number refers to an element past the current point in the rule, or beyond the bottom of the stack, the result is undefined. If type checking is enabled and the type of the value to be assigned cannot be determined, a diagnostic message may be generated.
$<tag>number

These correspond exactly to the corresponding symbols without the tag inclusion, but allow for strict type checking (and preclude unwanted type conversions). The effect is that the macro is expanded to use tag to select an element from the YYSTYPE union (using dataname.tag). This is particularly useful if number is not positive.

$<tag>$
This imposes on the reference the type of the union member referenced by tag. This construction is applicable when a reference to a left context value occurs in the grammar, and provides yacc with a means for selecting a type.

Actions can occur anywhere in a rule (not just at the end); an action can access values returned by actions to its left, and in turn the value it returns can be accessed by actions to its right. An action appearing in the middle of a rule shall be equivalent to replacing the action with a new non-terminal symbol and adding an empty rule with that non-terminal symbol on the left-hand side. The semantic action associated with the new rule shall be equivalent to the original action. The use of actions within rules might introduce conflicts that would not otherwise exist.

By default, the value of a rule shall be the value of the first element in it. If the first element does not have a type (particularly in the case of a literal) and type checking is turned on by %type, an error message shall result.

precedence
The keyword %prec can be used to change the precedence level associated with a particular grammar rule. Examples of this are in cases where a unary and binary operator have the same symbolic representation, but need to be given different precedences, or where the handling of an ambiguous if-else construction is necessary. The reserved symbol %prec can appear immediately after the body of the grammar rule and can be followed by a token name or a literal. It shall cause the precedence of the grammar rule to become that of the following token name or literal. The action for the rule as a whole can follow %prec.

If a program section follows, the application shall ensure that the grammar rules are terminated by %%.

Programs Section

The programs section can include the definition of the lexical analyzer yylex(), and any other functions; for example, those used in the actions specified in the grammar rules. It is unspecified whether the programs section precedes or follows the semantic actions in the output file; therefore, if the application contains any macro definitions and declarations intended to apply to the code in the semantic actions, it shall place them within "%{ ... %}" in the declarations section.

Input Grammar

The following input to yacc yields a parser for the input to yacc. This formal syntax takes precedence over the preceding text syntax description.

The lexical structure is defined less precisely; Lexical Structure of the Grammar defines most terms. The correspondence between the previous terms and the tokens below is as follows.

IDENTIFIER
This corresponds to the concept of name, given previously. It also includes literals as defined previously.
C_IDENTIFIER
This is a name, and additionally it is known to be followed by a colon. A literal cannot yield this token.
NUMBER
A string of digits (a non-negative decimal integer).
TYPE, LEFT, MARK, LCURL, RCURL

These correspond directly to %type, %left, %%, %{, and %}.

{ ... }
This indicates C-language source code, with the possible inclusion of '$' macros as discussed previously.

/* Grammar for the input to yacc. */
/* Basic entries. */
/* The following are recognized by the lexical analyzer. */

%token    IDENTIFIER      /* Includes identifiers and literals */
%token    C_IDENTIFIER    /* identifier (but not literal)
                             followed by a :. */
%token    NUMBER          /* [0-9][0-9]* */

/* Reserved words : %type=>TYPE %left=>LEFT, and so on */

%token    LEFT RIGHT NONASSOC TOKEN PREC TYPE START UNION

%token    MARK            /* The %% mark. */
%token    LCURL           /* The %{ mark. */
%token    RCURL           /* The %} mark. */

/* 8-bit character literals stand for themselves; */
/* tokens have to be defined for multi-byte characters. */

%start    spec

%%

spec  : defs MARK rules tail
      ;
tail  : MARK
      {
        /* In this action, set up the rest of the file. */
      }
      | /* Empty; the second MARK is optional. */
      ;
defs  : /* Empty. */
      |    defs def
      ;
def   : START IDENTIFIER
      |    UNION
      {
        /* Copy union definition to output. */
      }
      |    LCURL
      {
        /* Copy C code to output file. */
      }
        RCURL
      |    rword tag nlist
      ;
rword : TOKEN
      | LEFT
      | RIGHT
      | NONASSOC
      | TYPE
      ;
tag   : /* Empty: union tag ID optional. */
      | '<' IDENTIFIER '>'
      ;
nlist : nmno
      | nlist nmno
      ;
nmno  : IDENTIFIER         /* Note: literal invalid with % type. */
      | IDENTIFIER NUMBER  /* Note: invalid with % type. */
      ;

/* Rule section */

rules : C_IDENTIFIER rbody prec
      | rules  rule
      ;
rule  : C_IDENTIFIER rbody prec
      | '|' rbody prec
      ;
rbody : /* empty */
      | rbody IDENTIFIER
      | rbody act
      ;
act   : '{'
        {
          /* Copy action, translate $$, and so on. */
        }
        '}'
      ;
prec  : /* Empty */
      | PREC IDENTIFIER
      | PREC IDENTIFIER act
      | prec ';'
      ;

Conflicts

The parser produced for an input grammar may contain states in which conflicts occur. The conflicts occur because the grammar is not LALR(1). An ambiguous grammar always contains at least one LALR(1) conflict. The yacc utility shall resolve all conflicts, using either default rules or user-specified precedence rules.

Conflicts are either shift/reduce conflicts or reduce/reduce conflicts. A shift/reduce conflict is where, for a given state and lookahead symbol, both a shift action and a reduce action are possible. A reduce/reduce conflict is where, for a given state and lookahead symbol, reductions by two different rules are possible.

The rules below describe how to specify what actions to take when a conflict occurs. Not all shift/reduce conflicts can be successfully resolved this way because the conflict may be due to something other than ambiguity, so incautious use of these facilities can cause the language accepted by the parser to be much different from that which was intended. The description file shall contain sufficient information to understand the cause of the conflict. Where ambiguity is the reason either the default or explicit rules should be adequate to produce a working parser.

The declared precedences and associativities (see Declarations Section ) are used to resolve parsing conflicts as follows:

1.
A precedence and associativity is associated with each grammar rule; it is the precedence and associativity of the last token or literal in the body of the rule. If the %prec keyword is used, it overrides this default. Some grammar rules might not have both precedence and associativity.

2.
If there is a shift/reduce conflict, and both the grammar rule and the input symbol have precedence and associativity associated with them, then the conflict is resolved in favor of the action (shift or reduce) associated with the higher precedence. If the precedences are the same, then the associativity is used; left associative implies reduce, right associative implies shift, and non-associative implies an error in the string being parsed.

3.
When there is a shift/reduce conflict that cannot be resolved by rule 2, the shift is done. Conflicts resolved this way are counted in the diagnostic output described in Error Handling .

4.
When there is a reduce/reduce conflict, a reduction is done by the grammar rule that occurs earlier in the input sequence. Conflicts resolved this way are counted in the diagnostic output described in Error Handling .

Conflicts resolved by precedence or associativity shall not be counted in the shift/reduce and reduce/reduce conflicts reported by yacc on either standard error or in the description file.

Error Handling

The token error shall be reserved for error handling. The name error can be used in grammar rules. It indicates places where the parser can recover from a syntax error. The default value of error shall be 256. Its value can be changed using a %token declaration. The lexical analyzer should not return the value of error.

The parser shall detect a syntax error when it is in a state where the action associated with the lookahead symbol is error. A semantic action can cause the parser to initiate error handling by executing the macro YYERROR. When YYERROR is executed, the semantic action passes control back to the parser. YYERROR cannot be used outside of semantic actions.

When the parser detects a syntax error, it normally calls yyerror() with the character string "syntax error" as its argument. The call shall not be made if the parser is still recovering from a previous error when the error is detected. The parser is considered to be recovering from a previous error until the parser has shifted over at least three normal input symbols since the last error was detected or a semantic action has executed the macro yyerrok. The parser shall not call yyerror() when YYERROR is executed.

The macro function YYRECOVERING shall return 1 if a syntax error has been detected and the parser has not yet fully recovered from it. Otherwise, zero shall be returned.

When a syntax error is detected by the parser, the parser shall check if a previous syntax error has been detected. If a previous error was detected, and if no normal input symbols have been shifted since the preceding error was detected, the parser checks if the lookahead symbol is an endmarker (see Interface to the Lexical Analyzer ). If it is, the parser shall return with a non-zero value. Otherwise, the lookahead symbol shall be discarded and normal parsing shall resume.

When YYERROR is executed or when the parser detects a syntax error and no previous error has been detected, or at least one normal input symbol has been shifted since the previous error was detected, the parser shall pop back one state at a time until the parse stack is empty or the current state allows a shift over error. If the parser empties the parse stack, it shall return with a non-zero value. Otherwise, it shall shift over error and then resume normal parsing. If the parser reads a lookahead symbol before the error was detected, that symbol shall still be the lookahead symbol when parsing is resumed.

The macro yyerrok in a semantic action shall cause the parser to act as if it has fully recovered from any previous errors. The macro yyclearin shall cause the parser to discard the current lookahead token. If the current lookahead token has not yet been read, yyclearin shall have no effect.

The macro YYACCEPT shall cause the parser to return with the value zero. The macro YYABORT shall cause the parser to return with a non-zero value.

Interface to the Lexical Analyzer

The yylex() function is an integer-valued function that returns a token number representing the kind of token read. If there is a value associated with the token returned by yylex() (see the discussion of tag above), it shall be assigned to the external variable yylval.

If the parser and yylex() do not agree on these token numbers, reliable communication between them cannot occur. For (single-byte character) literals, the token is simply the numeric value of the character in the current character set. The numbers for other tokens can either be chosen by yacc, or chosen by the user. In either case, the #define construct of C is used to allow yylex() to return these numbers symbolically. The #define statements are put into the code file, and the header file if that file is requested. The set of characters permitted by yacc in an identifier is larger than that permitted by C. Token names found to contain such characters shall not be included in the #define declarations.

If the token numbers are chosen by yacc, the tokens other than literals shall be assigned numbers greater than 256, although no order is implied. A token can be explicitly assigned a number by following its first appearance in the declarations section with a number. Names and literals not defined this way retain their default definition. All token numbers assigned by yacc shall be unique and distinct from the token numbers used for literals and user-assigned tokens. If duplicate token numbers cause conflicts in parser generation, yacc shall report an error; otherwise, it is unspecified whether the token assignment is accepted or an error is reported.

The end of the input is marked by a special token called the endmarker, which has a token number that is zero or negative. (These values are invalid for any other token.) All lexical analyzers shall return zero or negative as a token number upon reaching the end of their input. If the tokens up to, but excluding, the endmarker form a structure that matches the start symbol, the parser shall accept the input. If the endmarker is seen in any other context, it shall be considered an error.

Completing the Program

In addition to yyparse() and yylex(), the functions yyerror() and main() are required to make a complete program. The application can supply main() and yyerror(), or those routines can be obtained from the yacc library.

Yacc Library

The following functions shall appear only in the yacc library accessible through the -l y operand to c99; they can therefore be redefined by a conforming application:

int main(void)

This function shall call yyparse() and exit with an unspecified value. Other actions within this function are unspecified.

int yyerror(const char *s)

This function shall write the NUL-terminated argument to standard error, followed by a <newline>.

The order of the -l y and -l l operands given to c99 is significant; the application shall either provide its own main() function or ensure that -l y precedes -l l.

Debugging the Parser

The parser generated by yacc shall have diagnostic facilities in it that can be optionally enabled at either compile time or at runtime (if enabled at compile time). The compilation of the runtime debugging code is under the control of YYDEBUG, a preprocessor symbol. If YYDEBUG has a non-zero value, the debugging code shall be included. If its value is zero, the code shall not be included.

In parsers where the debugging code has been included, the external int yydebug can be used to turn debugging on (with a non-zero value) and off (zero value) at runtime. The initial value of yydebug shall be zero.

When -t is specified, the code file shall be built such that, if YYDEBUG is not already defined at compilation time (using the c99 -D YYDEBUG option, for example), YYDEBUG shall be set explicitly to 1. When -t is not specified, the code file shall be built such that, if YYDEBUG is not already defined, it shall be set explicitly to zero.

The format of the debugging output is unspecified but includes at least enough information to determine the shift and reduce actions, and the input symbols. It also provides information about error recovery.

Algorithms

The parser constructed by yacc implements an LALR(1) parsing algorithm as documented in the literature. It is unspecified whether the parser is table-driven or direct-coded.

A parser generated by yacc shall never request an input symbol from yylex() while in a state where the only actions other than the error action are reductions by a single rule.

The literature of parsing theory defines these concepts.

Limits

The yacc utility may have several internal tables. The minimum maximums for these tables are shown in the following table. The exact meaning of these values is implementation-defined. The implementation shall define the relationship between these values and between them and any error messages that the implementation may generate should it run out of space for any internal structure. An implementation may combine groups of these resources into a single pool as long as the total available to the user does not fall below the sum of the sizes specified by this section.

Table: Internal Limits in yacc
 | Minimum |
Limit | Maximum | Description
{NTERMS} | 126 | Number of tokens.
{NNONTERM} | 200 | Number of non-terminals.
{NPROD} | 300 | Number of rules.
{NSTATES} | 600 | Number of states.
{MEMSIZE} | 5200 | Length of rules. The total length, in names (tokens and non-terminals), of all the rules of the grammar. The left-hand side is counted for each rule, even if it is not explicitly repeated, as specified in Grammar Rules in yacc .
{ACTSIZE} | 4000 | Number of actions. "Actions" here (and in the description file) refer to parser actions (shift, reduce, and so on) not to semantic actions defined in Grammar Rules in yacc .

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If any errors are encountered, the run is aborted and yacc exits with a non-zero status. Partial code files and header files may be produced. The summary information in the description file shall always be produced if the -v flag is present.

The following sections are informative.

APPLICATION USAGE

Historical implementations experience name conflicts on the names yacc.tmp, yacc.acts, yacc.debug, y.tab.c, y.tab.h, and y.output if more than one copy of yacc is running in a single directory at one time. The -b option was added to overcome this problem. The related problem of allowing multiple yacc parsers to be placed in the same file was addressed by adding a -p option to override the previously hard-coded yy variable prefix.

The description of the -p option specifies the minimal set of function and variable names that cause conflict when multiple parsers are linked together. YYSTYPE does not need to be changed. Instead, the programmer can use -b to give the header files for different parsers different names, and then the file with the yylex() for a given parser can include the header for that parser. Names such as yyclearerr do not need to be changed because they are used only in the actions; they do not have linkage. It is possible that an implementation has other names, either internal ones for implementing things such as yyclearerr, or providing non-standard features that it wants to change with -p.

Unary operators that are the same token as a binary operator in general need their precedence adjusted. This is handled by the %prec advisory symbol associated with the particular grammar rule defining that unary operator. (See Grammar Rules in yacc .) Applications are not required to use this operator for unary operators, but the grammars that do not require it are rare.

EXAMPLES

Access to the yacc library is obtained with library search operands to c99. To use the yacc library main():

c99 y.tab.c -l y

Both the lex library and the yacc library contain main(). To access the yacc main():

c99 y.tab.c lex.yy.c -l y -l l

This ensures that the yacc library is searched first, so that its main() is used.

The historical yacc libraries have contained two simple functions that are normally coded by the application programmer. These functions are similar to the following code:

#include <locale.h>
int main(void)
{
    extern int yyparse();

    setlocale(LC_ALL, "");

    /* If the following parser is one created by lex, the
       application must be careful to ensure that LC_CTYPE
       and LC_COLLATE are set to the POSIX locale. */
    (void) yyparse();
    return (0);
}

#include <stdio.h>

int yyerror(const char *msg)
{
    (void) fprintf(stderr, "%s\n", msg);
    return (0);
}

RATIONALE

The references in may be helpful in constructing the parser generator. The referenced DeRemer and Pennello article (along with the works it references) describes a technique to generate parsers that conform to this volume of IEEE Std 1003.1-2001. Work in this area continues to be done, so implementors should consult current literature before doing any new implementations. The original Knuth article is the theoretical basis for this kind of parser, but the tables it generates are impractically large for reasonable grammars and should not be used. The "equivalent to" wording is intentional to assure that the best tables that are LALR(1) can be generated.

There has been confusion between the class of grammars, the algorithms needed to generate parsers, and the algorithms needed to parse the languages. They are all reasonably orthogonal. In particular, a parser generator that accepts the full range of LR(1) grammars need not generate a table any more complex than one that accepts SLR(1) (a relatively weak class of LR grammars) for a grammar that happens to be SLR(1). Such an implementation need not recognize the case, either; table compression can yield the SLR(1) table (or one even smaller than that) without recognizing that the grammar is SLR(1). The speed of an LR(1) parser for any class is dependent more upon the table representation and compression (or the code generation if a direct parser is generated) than upon the class of grammar that the table generator handles.

The speed of the parser generator is somewhat dependent upon the class of grammar it handles. However, the original Knuth article algorithms for constructing LR parsers were judged by its author to be impractically slow at that time. Although full LR is more complex than LALR(1), as computer speeds and algorithms improve, the difference (in terms of acceptable wall-clock execution time) is becoming less significant.

Potential authors are cautioned that the referenced DeRemer and Pennello article previously cited identifies a bug (an over-simplification of the computation of LALR(1) lookahead sets) in some of the LALR(1) algorithm statements that preceded it to publication. They should take the time to seek out that paper, as well as current relevant work, particularly Aho's.

The -b option was added to provide a portable method for permitting yacc to work on multiple separate parsers in the same directory. If a directory contains more than one yacc grammar, and both grammars are constructed at the same time (by, for example, a parallel make program), conflict results. While the solution is not historical practice, it corrects a known deficiency in historical implementations. Corresponding changes were made to all sections that referenced the filenames y.tab.c (now "the code file"), y.tab.h (now "the header file"), and y.output (now "the description file").

The grammar for yacc input is based on System V documentation. The textual description shows there that the ';' is required at the end of the rule. The grammar and the implementation do not require this. (The use of C_IDENTIFIER causes a reduce to occur in the right place.)

Also, in that implementation, the constructs such as %token can be terminated by a semicolon, but this is not permitted by the grammar. The keywords such as %token can also appear in uppercase, which is again not discussed. In most places where '%' is used, '\' can be substituted, and there are alternate spellings for some of the symbols (for example, %LEFT can be "%<" or even "\<" ).

Historically, <tag> can contain any characters except '>' , including white space, in the implementation. However, since the tag must reference an ISO C standard union member, in practice conforming implementations need to support only the set of characters for ISO C standard identifiers in this context.

Some historical implementations are known to accept actions that are terminated by a period. Historical implementations often allow '$' in names. A conforming implementation does not need to support either of these behaviors.

Deciding when to use %prec illustrates the difficulty in specifying the behavior of yacc. There may be situations in which the grammar is not, strictly speaking, in error, and yet yacc cannot interpret it unambiguously. The resolution of ambiguities in the grammar can in many instances be resolved by providing additional information, such as using %type or %union declarations. It is often easier and it usually yields a smaller parser to take this alternative when it is appropriate.

The size and execution time of a program produced without the runtime debugging code is usually smaller and slightly faster in historical implementations.

Statistics messages from several historical implementations include the following types of information:

n/512 terminals, n/300 non-terminals
n/600 grammar rules, n/1500 states
n shift/reduce, n reduce/reduce conflicts reported
n/350 working sets used
Memory: states, etc. n/15000, parser n/15000
n/600 distinct lookahead sets
n extra closures
n shift entries, n exceptions
n goto entries
n entries saved by goto default
Optimizer space used: input n/15000, output n/15000
n table entries, n zero
Maximum spread: n, Maximum offset: n

The report of internal tables in the description file is left implementation-defined because all aspects of these limits are also implementation-defined. Some implementations may use dynamic allocation techniques and have no specific limit values to report.

The format of the y.output file is not given because specification of the format was not seen to enhance applications portability. The listing is primarily intended to help human users understand and debug the parser; use of y.output by a conforming application script would be unusual. Furthermore, implementations have not produced consistent output and no popular format was apparent. The format selected by the implementation should be human-readable, in addition to the requirement that it be a text file.

Standard error reports are not specifically described because they are seldom of use to conforming applications and there was no reason to restrict implementations.

Some implementations recognize "={" as equivalent to '{' because it appears in historical documentation. This construction was recognized and documented as obsolete as long ago as 1978, in the referenced Yacc: Yet Another Compiler-Compiler. This volume of IEEE Std 1003.1-2001 chose to leave it as obsolete and omit it.

Multi-byte characters should be recognized by the lexical analyzer and returned as tokens. They should not be returned as multi-byte character literals. The token error that is used for error recovery is normally assigned the value 256 in the historical implementation. Thus, the token value 256, which is used in many multi-byte character sets, is not available for use as the value of a user-defined token.

FUTURE DIRECTIONS

None.

SEE ALSO

c99 , lex

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


join(1p)

JOIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

join - relational database operator

SYNOPSIS

join [-a file_number | -v file_number][-e string][-o list][-t char]
[-1 field][-2 field] file1 file2

DESCRIPTION

The join utility shall perform an equality join on the files file1 and file2. The joined files shall be written to the standard output.

The join field is a field in each file on which the files are compared. The join utility shall write one line in the output for each pair of lines in file1 and file2 that have identical join fields. The output line by default shall consist of the join field, then the remaining fields from file1, then the remaining fields from file2. This format can be changed by using the -o option (see below). The -a option can be used to add unmatched lines to the output. The -v option can be used to output only unmatched lines.

The files file1 and file2 shall be ordered in the collating sequence of sort -b on the fields on which they shall be joined, by default the first in each line. All selected output shall be written in the same collating sequence.

The default input field separators shall be <blank>s. In this case, multiple separators shall count as one field separator, and leading separators shall be ignored. The default output field separator shall be a <space>.

The field separator and collating sequence can be changed by using the -t option (see below).

If the same key appears more than once in either file, all combinations of the set of remaining fields in file1 and the set of remaining fields in file2 are output in the order of the lines encountered.

If the input files are not in the appropriate collating sequence, the results are unspecified.

OPTIONS

The join utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a file_number

Produce a line for each unpairable line in file file_number, where file_number is 1 or 2, in addition to the default output. If both -a1 and -a2 are specified, all unpairable lines shall be output.

-e string
Replace empty output fields in the list selected by -o with the string string.
-o list
Construct the output line to comprise the fields specified in list, each element of which shall have one of the following two forms:
1.
file_number.field, where file_number is a file number and field is a decimal integer field number

2.
0 (zero), representing the join field

The elements of list shall be either comma-separated or <blank>-separated, as specified in Guideline 8 of the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. The fields specified by list shall be written for all selected output lines. Fields selected by list that do not appear in the input shall be treated as empty output fields. (See the -e option.) Only specifically requested fields shall be written. The application shall ensure that list is a single command line argument.

-t char
Use character char as a separator, for both input and output. Every appearance of char in a line shall be significant. When this option is specified, the collating sequence shall be the same as sort without the -b option.
-v file_number

Instead of the default output, produce a line only for each unpairable line in file_number, where file_number is 1 or 2. If both -v1 and -v2 are specified, all unpairable lines shall be output.

-1 field
Join on the fieldth field of file 1. Fields are decimal integers starting with 1.
-2 field
Join on the fieldth field of file 2. Fields are decimal integers starting with 1.

OPERANDS

The following operands shall be supported:

file1, file2
A pathname of a file to be joined. If either of the file1 or file2 operands is '-' , the standard input shall be used in its place.

STDIN

The standard input shall be used only if the file1 or file2 operand is '-' . See the INPUT FILES section.

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of join:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale of the collating sequence join expects to have been used when the input files were sorted.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The join utility output shall be a concatenation of selected character fields. When the -o option is not specified, the output shall be:

"%s%s%s\n", <join field>, <other file1 fields>,
    <other file2 fields>

If the join field is not the first field in a file, the <other file fields> for that file shall be:

<fields preceding join field>, <fields following join field>

When the -o option is specified, the output format shall be:

"%s\n", <concatenation of fields>

where the concatenation of fields is described by the -o option, above.

For either format, each field (except the last) shall be written with its trailing separator character. If the separator is the default ( <blank>s), a single <space> shall be written after each field (except the last).

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were output successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Pathnames consisting of numeric digits or of the form string.string should not be specified directly following the -o list.

EXAMPLES

The -o 0 field essentially selects the union of the join fields. For example, given file phone:

!Name           Phone Number
Don             +1 123-456-7890
Hal             +1 234-567-8901
Yasushi         +2 345-678-9012

and file fax:

!Name           Fax Number
Don             +1 123-456-7899
Keith           +1 456-789-0122
Yasushi         +2 345-678-9011

(where the large expanses of white space are meant to each represent a single <tab>), the command:

join -t "<tab>" -a 1 -a 2 -e '(unknown)' -o 0,1.2,2.2 phone fax

would produce:

!Name           Phone Number            Fax Number
Don             +1 123-456-7890         +1 123-456-7899
Hal             +1 234-567-8901         (unknown)
Keith           (unknown)               +1 456-789-0122
Yasushi         +2 345-678-9012         +2 345-678-9011

Multiple instances of the same key will produce combinatorial results. The following:

fa:
    a x
    a y
    a z
fb:
    a p

will produce:

a x p
a y p
a z p

And the following:

fa:
    a b c
    a d e
fb:
    a w x
    a y z
    a o p

will produce:

a b c w x
a b c y z
a b c o p
a d e w x
a d e y z
a d e o p

RATIONALE

The -e option is only effective when used with -o because, unless specific fields are identified using -o, join is not aware of what fields might be empty. The exception to this is the join field, but identifying an empty join field with the -e string is not historical practice and some scripts might break if this were changed.

The 0 field in the -o list was adopted from the Tenth Edition version of join to satisfy international objections that the join in the base documents does not support the "full join" or "outer join" described in relational database literature. Although it has been possible to include a join field in the output (by default, or by field number using -o), the join field could not be included for an unpaired line selected by -a. The -o 0 field essentially selects the union of the join fields.

This sort of outer join was not possible with the join commands in the base documents. The -o 0 field was chosen because it is an upwards-compatible change for applications. An alternative was considered: have the join field represent the union of the fields in the files (where they are identical for matched lines, and one or both are null for unmatched lines). This was not adopted because it would break some historical applications.

The ability to specify file2 as - is not historical practice; it was added for completeness.

The -v option is not historical practice, but was considered necessary because it permitted the writing of only those lines that do not match on the join field, as opposed to the -a option, which prints both lines that do and do not match. This additional facility is parallel with the -v option of grep.

Some historical implementations have been encountered where a blank line in one of the input files was considered to be the end of the file; the description in this volume of IEEE Std 1003.1-2001 does not cite this as an allowable case.

FUTURE DIRECTIONS

None.

SEE ALSO

awk , comm , sort , uniq

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qmsg(1p)

QMSG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qmsg - send message to batch jobs

SYNOPSIS

qmsg [-E][-O] message_string job_identifier ...

DESCRIPTION

To send a message to a batch job is to request that a server write a message string into one or more output files of the batch job. A message is sent to a batch job by a request to the batch server that manages the batch job. The qmsg utility is a user-accessible batch client that requests the sending of messages to one or more batch jobs.

The qmsg utility shall write messages into the files of batch jobs by sending a Job Message Request to the batch server that manages the batch job. The qmsg utility shall not directly write the message into the files of the batch job.

The qmsg utility shall send a Job Message Request for those batch jobs, and only those batch jobs, for which a batch job_identifier is presented to the utility.

The qmsg utility shall send Job Message Requests for batch jobs in the order in which their batch job_identifiers are presented to the utility.

If the qmsg utility fails to process any batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

The qmsg utility shall not exit before a Job Message Request has been sent to the server that manages the batch job that corresponds to each successfully processed batch job_identifier.

OPTIONS

The qmsg utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-E
Specify that the message is written to the standard error of each batch job.

The qmsg utility shall write the message into the standard error of the batch job.

-O
Specify that the message is written to the standard output of each batch job.

The qmsg utility shall write the message into the standard output of the batch job.

If neither the -O nor the -E option is presented to the qmsg utility, the utility shall write the message into an implementation-defined file. The conformance document for the implementation shall describe the name and location of the implementation-defined file. If both the -O and the -E options are presented to the qmsg utility, then the utility shall write the messages to both standard output and standard error.

OPERANDS

The qmsg utility shall accept a minimum of two operands, message_string and one or more batch job_identifiers.

The message_string operand shall be the string to be written to one or more output files of the batch job followed by a <newline>. If the string contains <blank>s, then the application shall ensure that the string is quoted. The message_string shall be encoded in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set).

All remaining operands are batch job_identifiers that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qmsg:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qmsg utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qmsg utility waits to output the diagnostic message while attempting to locate the job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qmsg utility allows users to write messages into the output files of running jobs. Users, including operators and administrators, have a number of occasions when they want to place messages in the output files of a batch job. For example, if a disk that is being used by a batch job is showing errors, the operator might note this in the standard error stream of the batch job.

The options of the qmsg utility provide users with the means of placing the message in the output stream of their choice. The default output stream for the message-if the user does not designate an output stream-is implementation-defined, since many implementations will provide, as an extension to this volume of IEEE Std 1003.1-2001, a log file that shows the history of utility execution.

If users wish to send a message to a set of jobs that meet a selection criteria, the qselect utility can be used to acquire the appropriate list of job identifiers.

The -E option allows users to place the message in the standard error stream of the batch job.

The -O option allows users to place the message in the standard output stream of the batch job.

Historically, the qmsg utility is an existing practice in the offerings of one or more implementors of an NQS-derived batch system. The utility has been found to be useful enough that it deserves to be included in this volume of IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , qselect

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


expand(1p)

EXPAND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

expand - convert tabs to spaces

SYNOPSIS

expand [-t tablist][file ...]

DESCRIPTION

The expand utility shall write files or the standard input to the standard output with <tab>s replaced with one or more <space>s needed to pad to the next tab stop. Any <backspace>s shall be copied to the output and cause the column position count for tab stop calculations to be decremented; the column position count shall not be decremented below zero.

OPTIONS

The expand utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-t tablist
Specify the tab stops. The application shall ensure that the argument tablist consists of either a single positive decimal integer or a list of tabstops. If a single number is given, tabs shall be set that number of column positions apart instead of the default 8.

If a list of tabstops is given, the application shall ensure that it consists of a list of two or more positive decimal integers, separated by <blank>s or commas, in ascending order. The tabs shall be set at those specific column positions. Each tab stop N shall be an integer value greater than zero, and the list is in strictly ascending order. This is taken to mean that, from the start of a line of output, tabbing to position N shall cause the next character output to be in the ( N+1)th column position on that line.

In the event of expand having to process a <tab> at a position beyond the last of those specified in a multiple tab-stop list, the <tab> shall be replaced by a single <space> in the output.

OPERANDS

The following operand shall be supported:

file
The pathname of a text file to be used as input.

STDIN

See the INPUT FILES section.

INPUT FILES

Input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of expand:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the processing of <tab>s and <space>s, and for the determination of the width in column positions each character would occupy on an output device.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be equivalent to the input files with <tab>s converted into the appropriate number of <space>s.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion
>0
An error occurred.

CONSEQUENCES OF ERRORS

The expand utility shall terminate with an error message and non-zero exit status upon encountering difficulties accessing one of the file operands.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The expand utility is useful for preprocessing text files (before sorting, looking at specific columns, and so on) that contain <tab>s.

See the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.103, Column Position.

The tablist option-argument consists of integers in ascending order. Utility Syntax Guideline 8 mandates that expand shall accept the integers (within the single argument) separated using either commas or <blank>s.

FUTURE DIRECTIONS

None.

SEE ALSO

tabs , unexpand

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getconf(1p)

GETCONF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getconf - get configuration values

SYNOPSIS

getconf [ -v specification ] system_var

getconf [ -v specification ] path_var pathname

DESCRIPTION

In the first synopsis form, the getconf utility shall write to the standard output the value of the variable specified by the system_var operand.

In the second synopsis form, the getconf utility shall write to the standard output the value of the variable specified by the path_var operand for the path specified by the pathname operand.

The value of each configuration variable shall be determined as if it were obtained by calling the function from which it is defined to be available by this volume of IEEE Std 1003.1-2001 or by the System Interfaces volume of IEEE Std 1003.1-2001 (see the OPERANDS section). The value shall reflect conditions in the current operating environment.

OPTIONS

The getconf utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-v specification

Indicate a specific specification and version for which configuration variables shall be determined. If this option is not specified, the values returned correspond to an implementation default conforming compilation environment.

If the command:

getconf _POSIX_V6_ILP32_OFF32

does not write "-1\n" or "undefined\n" to standard output, then commands of the form:

getconf -v POSIX_V6_ILP32_OFF32 ...

determine values for configuration variables corresponding to the POSIX_V6_ILP32_OFF32 compilation environment specified in c99 , the EXTENDED DESCRIPTION.

If the command:

getconf _POSIX_V6_ILP32_OFFBIG

does not write "-1\n" or "undefined\n" to standard output, then commands of the form:

getconf -v POSIX_V6_ILP32_OFFBIG ...

determine values for configuration variables corresponding to the POSIX_V6_ILP32_OFFBIG compilation environment specified in c99 , the EXTENDED DESCRIPTION.

If the command:

getconf _POSIX_V6_LP64_OFF64

does not write "-1\n" or "undefined\n" to standard output, then commands of the form:

getconf -v POSIX_V6_LP64_OFF64 ...

determine values for configuration variables corresponding to the POSIX_V6_LP64_OFF64 compilation environment specified in c99 , the EXTENDED DESCRIPTION.

If the command:

getconf _POSIX_V6_LPBIG_OFFBIG

does not write "-1\n" or "undefined\n" to standard output, then commands of the form:

getconf -v POSIX_V6_LPBIG_OFFBIG ...

determine values for configuration variables corresponding to the POSIX_V6_LPBIG_OFFBIG compilation environment specified in c99 , the EXTENDED DESCRIPTION.

OPERANDS

The following operands shall be supported:

path_var
A name of a configuration variable. All of the variables in the Variable column of the table in the DESCRIPTION of the fpathconf() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, without the enclosing braces, shall be supported. The implementation may add other local variables.
pathname
A pathname for which the variable specified by path_var is to be determined.
system_var
A name of a configuration variable. All of the following variables shall be supported:
*
The names in the Variable column of the table in the DESCRIPTION of the sysconf() function in the System Interfaces volume of IEEE Std 1003.1-2001, except for the entries corresponding to _SC_CLK_TCK, _SC_GETGR_R_SIZE_MAX, and _SC_GETPW_R_SIZE_MAX, without the enclosing braces.

For compatibility with earlier versions, the following variable names shall also be supported:

POSIX2_C_BIND
POSIX2_C_DEV
POSIX2_CHAR_TERM
POSIX2_FORT_DEV
POSIX2_FORT_RUN
POSIX2_LOCALEDEF
POSIX2_SW_DEV
POSIX2_UPE
POSIX2_VERSION

and shall be equivalent to the same name prefixed with an underscore. This requirement may be removed in a future version.

*
The names of the symbolic constants used as the name argument of the confstr() function in the System Interfaces volume of IEEE Std 1003.1-2001, without the _CS_ prefix.

*
The names of the symbolic constants listed under the headings ``Maximum Values'' and ``Minimum Values'' in the description of the <limits.h> header in the Base Definitions volume of IEEE Std 1003.1-2001, without the enclosing braces.

For compatibility with earlier versions, the following variable names shall also be supported:

POSIX2_BC_BASE_MAX
POSIX2_BC_DIM_MAX
POSIX2_BC_SCALE_MAX
POSIX2_BC_STRING_MAX
POSIX2_COLL_WEIGHTS_MAX
POSIX2_EXPR_NEST_MAX
POSIX2_LINE_MAX
POSIX2_RE_DUP_MAX

and shall be equivalent to the same name prefixed with an underscore. This requirement may be removed in a future version.

The implementation may add other local values.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of getconf:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If the specified variable is defined on the system and its value is described to be available from the confstr() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, its value shall be written in the following format:

"%s\n", <value>

Otherwise, if the specified variable is defined on the system, its value shall be written in the following format:

"%d\n", <value>

If the specified variable is valid, but is undefined on the system, getconf shall write using the following format:

"undefined\n"

If the variable name is invalid or an error occurs, nothing shall be written to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The specified variable is valid and information about its current state was written successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

The following example illustrates the value of {NGROUPS_MAX}:

getconf NGROUPS_MAX

The following example illustrates the value of {NAME_MAX} for a specific directory:

getconf NAME_MAX /usr

The following example shows how to deal more carefully with results that might be unspecified:

if value=$(getconf PATH_MAX /usr); then
    if [ "$value" = "undefined" ]; then
        echo PATH_MAX in /usr is infinite.
    else
        echo PATH_MAX in /usr is $value.
    fi
else
    echo Error in getconf.
fi

Note that:

sysconf(_SC_POSIX_C_BIND);

and:

system("getconf POSIX2_C_BIND");

in a C program could give different answers. The sysconf() call supplies a value that corresponds to the conditions when the program was either compiled or executed, depending on the implementation; the system() call to getconf always supplies a value corresponding to conditions when the program is executed.

RATIONALE

The original need for this utility, and for the confstr() function, was to provide a way of finding the configuration-defined default value for the PATH environment variable. Since PATH can be modified by the user to include directories that could contain utilities replacing the standard utilities, shell scripts need a way to determine the system-supplied PATH environment variable value that contains the correct search path for the standard utilities. It was later suggested that access to the other variables described in this volume of IEEE Std 1003.1-2001 could also be useful to applications.

This functionality of getconf would not be adequately subsumed by another command such as:

grep var /etc/conf

because such a strategy would provide correct values for neither those variables that can vary at runtime, nor those that can vary depending on the path.

Early proposal versions of getconf specified exit status 1 when the specified variable was valid, but not defined on the system. The output string "undefined" is now used to specify this case with exit code 0 because so many things depend on an exit code of zero when an invoked utility is successful.

FUTURE DIRECTIONS

None.

SEE ALSO

c99 , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, the System Interfaces volume of IEEE Std 1003.1-2001, confstr(), pathconf(), sysconf(), system()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ipcrm(1p)

IPCRM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ipcrm - remove an XSI message queue, semaphore set, or shared memory segment identifier

SYNOPSIS

ipcrm [ -q msgid | -Q msgkey | -s semid | -S semkey |
-m shmid | -M shmkey ] ...

DESCRIPTION

The ipcrm utility shall remove zero or more message queues, semaphore sets, or shared memory segments. The interprocess communication facilities to be removed are specified by the options.

Only a user with appropriate privilege shall be allowed to remove an interprocess communication facility that was not created by or owned by the user invoking ipcrm.

OPTIONS

The ipcrm facility supports the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-q msgid
Remove the message queue identifier msgid from the system and destroy the message queue and data structure associated with it.
-m shmid
Remove the shared memory identifier shmid from the system. The shared memory segment and data structure associated with it shall be destroyed after the last detach.
-s semid
Remove the semaphore identifier semid from the system and destroy the set of semaphores and data structure associated with it.
-Q msgkey
Remove the message queue identifier, created with key msgkey, from the system and destroy the message queue and data structure associated with it.
-M shmkey
Remove the shared memory identifier, created with key shmkey, from the system. The shared memory segment and data structure associated with it shall be destroyed after the last detach.
-S semkey
Remove the semaphore identifier, created with key semkey, from the system and destroy the set of semaphores and data structure associated with it.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ipcrm:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ipcs , the System Interfaces volume of IEEE Std 1003.1-2001, msgctl(), semctl(), shmctl()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


read(1p)

READ

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

read - read a line from standard input

SYNOPSIS

read [-r] var...

DESCRIPTION

The read utility shall read a single line from standard input.

By default, unless the -r option is specified, backslash ( '\' ) shall act as an escape character, as described in Escape Character (Backslash) . If standard input is a terminal device and the invoking shell is interactive, read shall prompt for a continuation line when:

*
The shell reads an input line ending with a backslash, unless the -r option is specified.

*
A here-document is not terminated after a <newline> is entered.

The line shall be split into fields as in the shell (see Field Splitting ); the first field shall be assigned to the first variable var, the second field to the second variable var, and so on. If there are fewer var operands specified than there are fields, the leftover fields and their intervening separators shall be assigned to the last var. If there are fewer fields than vars, the remaining vars shall be set to empty strings.

The setting of variables specified by the var operands shall affect the current shell execution environment; see Shell Execution Environment . If it is called in a subshell or separate utility execution environment, such as one of the following:

(read foo)
nohup read ...
find . -exec read ... \;

it shall not affect the shell variables in the caller's environment.

OPTIONS

The read utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option is supported:

-r
Do not treat a backslash character in any special way. Consider each backslash to be part of the input line.

OPERANDS

The following operand shall be supported:

var
The name of an existing or nonexisting shell variable.

STDIN

The standard input shall be a text file.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of read:

IFS
Determine the internal field separators used to delimit fields; see Shell Variables .
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PS2
Provide the prompt string that an interactive shell shall write to standard error when a line ending with a backslash is read and the -r option was not specified, or if a here-document is not terminated after a <newline> is entered.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used for diagnostic messages and prompts for continued input.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
End-of-file was detected or an error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The -r option is included to enable read to subsume the purpose of the line utility, which is not included in IEEE Std 1003.1-2001.

The results are undefined if an end-of-file is detected following a backslash at the end of a line when -r is not specified.

EXAMPLES

The following command:

while read -r xx yy
do
    printf "%s %s\n" "$yy" "$xx"
done < input_file

prints a file with the first field of each line moved to the end of the line.

RATIONALE

The read utility historically has been a shell built-in. It was separated off into its own utility to take advantage of the richer description of functionality introduced by this volume of IEEE Std 1003.1-2001.

Since read affects the current shell execution environment, it is generally provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:

(read foo)
nohup read ...
find . -exec read ... \;

it does not affect the shell variables in the environment of the caller.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


unget(1p)

UNGET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unget - undo a previous get of an SCCS file (DEVELOPMENT)

SYNOPSIS

unget [-ns][-r SID] file...

DESCRIPTION

The unget utility shall reverse the effect of a get -e done prior to creating the intended new delta.

OPTIONS

The unget utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-r SID
Uniquely identify which delta is no longer intended. (This would have been specified by get as the new delta.) The use of this option is necessary only if two or more outstanding get commands for editing on the same SCCS file were done by the same person (login name).
-s
Suppress the writing to standard output of the intended delta's SID.
-n
Retain the file that was obtained by get, which would normally be removed from the current directory.

OPERANDS

The following operands shall be supported:

file
A pathname of an existing SCCS file or a directory. If file is a directory, the unget utility shall behave as though each file in the directory were specified as a named file, except that non-SCCS files (last component of the pathname does not begin with s.) and unreadable files shall be silently ignored.

If exactly one file operand appears, and it is '-' , the standard input shall be read; each line of the standard input shall be taken to be the name of an SCCS file to be processed. Non-SCCS files and unreadable files shall be silently ignored.

STDIN

The standard input shall be a text file used only when the file operand is specified as '-' . Each line of the text file shall be interpreted as an SCCS pathname.

INPUT FILES

Any SCCS files processed shall be files of an unspecified format.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of unget:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall consist of a line for each file, in the following format:

"%s\n", <SID removed from file>

If there is more than one named file or if a directory or standard input is named, each pathname shall be written before each of the preceding lines:

"\n%s:\n", <pathname>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

Any SCCS files updated shall be files of an unspecified format. During processing of a file, a locking z-file, as described in get, and a q-file (a working copy of the p-file), may be created and deleted. The p-file and g-file, as described in get, shall be deleted.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

delta , get , sact

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


csplit(1p)

CSPLIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

csplit - split files based on context

SYNOPSIS

csplit [-ks][-f prefix][-n number] file arg1 ...argn

DESCRIPTION

The csplit utility shall read the file named by the file operand, write all or part of that file into other files as directed by the arg operands, and write the sizes of the files.

OPTIONS

The csplit utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-f prefix
Name the created files prefix 00, prefix 01, ..., prefixn. The default is xx00 ... xx n. If the prefix argument would create a filename exceeding {NAME_MAX} bytes, an error shall result, csplit shall exit with a diagnostic message, and no files shall be created.
-k
Leave previously created files intact. By default, csplit shall remove created files if an error occurs.
-n number
Use number decimal digits to form filenames for the file pieces. The default shall be 2.
-s
Suppress the output of file size messages.

OPERANDS

The following operands shall be supported:

file
The pathname of a text file to be split. If file is '-' , the standard input shall be used.

The operands arg1 ... argn can be a combination of the following:

/rexp/[offset]

A file shall be created using the content of the lines from the current line up to, but not including, the line that results from the evaluation of the regular expression with offset, if any, applied. The regular expression rexp shall follow the rules for basic regular expressions described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions. The application shall use the sequence "\/" to specify a slash character within the rexp. The optional offset shall be a positive or negative integer value representing a number of lines. A positive integer value can be preceded by '+' . If the selection of lines from an offset expression of this type would create a file with zero lines, or one with greater than the number of lines left in the input file, the results are unspecified. After the section is created, the current line shall be set to the line that results from the evaluation of the regular expression with any offset applied. If the current line is the first line in the file and a regular expression operation has not yet been performed, the pattern match of rexp shall be applied from the current line to the end of the file. Otherwise, the pattern match of rexp shall be applied from the line following the current line to the end of the file.

%rexp%[offset]

Equivalent to /rexp/[offset], except that no file shall be created for the selected section of the input file. The application shall use the sequence "\%" to specify a percent-sign character within the rexp.

line_no
Create a file from the current line up to (but not including) the line number line_no. Lines in the file shall be numbered starting at one. The current line becomes line_no.
{num}
Repeat operand. This operand can follow any of the operands described previously. If it follows a rexp type operand, that operand shall be applied num more times. If it follows a line_no operand, the file shall be split every line_no lines, num times, from that point.

An error shall be reported if an operand does not reference a line between the current position and the end of the file.

STDIN

See the INPUT FILES section.

INPUT FILES

The input file shall be a text file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of csplit:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classes within regular expressions.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

If the -k option is specified, created files shall be retained. Otherwise, the default action occurs.

STDOUT

Unless the -s option is used, the standard output shall consist of one line per file created, with a format as follows:

"%d\n", <file size in bytes>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output files shall contain portions of the original input file; otherwise, unchanged.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

By default, created files shall be removed if an error occurs. When the -k option is specified, created files shall not be removed if an error occurs.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

1.
This example creates four files, cobol00 ... cobol03:

csplit -f cobol file '/procedure division/' /par5./ /par16./

After editing the split files, they can be recombined as follows:

cat cobol0[0-3] > file

Note that this example overwrites the original file.

2.
This example would split the file after the first 99 lines, and every 100 lines thereafter, up to 9999 lines; this is because lines in the file are numbered from 1 rather than zero, for historical reasons:

csplit -k file  100  {99}

3.
Assuming that prog.c follows the C-language coding convention of ending routines with a '}' at the beginning of the line, this example creates a file containing each separate C routine (up to 21) in prog.c:

csplit -k prog.c '%main(%'  '/^}/+1' {20}

RATIONALE

The -n option was added to extend the range of filenames that could be handled.

Consideration was given to adding a -a flag to use the alphabetic filename generation used by the historical split utility, but the functionality added by the -n option was deemed to make alphabetic naming unnecessary.

FUTURE DIRECTIONS

None.

SEE ALSO

sed , split

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


diff(1p)

DIFF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

diff - compare two files

SYNOPSIS

diff [-c| -e| -f| -C n][-br] file1 file2

DESCRIPTION

The diff utility shall compare the contents of file1 and file2 and write to standard output a list of changes necessary to convert file1 into file2. This list should be minimal. No output shall be produced if the files are identical.

OPTIONS

The diff utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-b
Cause any amount of white space at the end of a line to be treated as a single <newline> (that is, the white-space characters preceding the <newline> are ignored) and other strings of white-space characters, not including <newline>s, to compare equal.
-c
Produce output in a form that provides three lines of context.
-C n
Produce output in a form that provides n lines of context (where n shall be interpreted as a positive decimal integer).
-e
Produce output in a form suitable as input for the ed utility, which can then be used to convert file1 into file2.
-f
Produce output in an alternative form, similar in format to -e, but not intended to be suitable as input for the ed utility, and in the opposite order.
-r
Apply diff recursively to files and directories of the same name when file1 and file2 are both directories.

OPERANDS

The following operands shall be supported:

file1, file2
A pathname of a file to be compared. If either the file1 or file2 operand is '-' , the standard input shall be used in its place.

If both file1 and file2 are directories, diff shall not compare block special files, character special files, or FIFO special files to any files and shall not compare regular files to directories. Further details are as specified in Diff Directory Comparison Format . The behavior of diff on other file types is implementation-defined when found in directories.

If only one of file1 and file2 is a directory, diff shall be applied to the non-directory file and the file contained in the directory file with a filename that is the same as the last component of the non-directory file.

STDIN

The standard input shall be used only if one of the file1 or file2 operands references standard input. See the INPUT FILES section.

INPUT FILES

The input files may be of any type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of diff:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
LC_TIME
Determine the locale for affecting the format of file timestamps written with the -C and -c options.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone used for calculating file timestamps written with the -C and -c options. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Diff Directory Comparison Format

If both file1 and file2 are directories, the following output formats shall be used.

In the POSIX locale, each file that is present in only one directory shall be reported using the following format:

"Only in %s: %s\n", <directory pathname>, <filename>

In the POSIX locale, subdirectories that are common to the two directories may be reported with the following format:

"Common subdirectories: %s and %s\n", <directory1 pathname>,
    <directory2 pathname>

For each file common to the two directories if the two files are not to be compared, the following format shall be used in the POSIX locale:

"File %s is a %s while file %s is a %s\n", <directory1 pathname>,
    <file type of directory1 pathname>, <directory2 pathname>,
    <file type of directory2 pathname>

For each file common to the two directories, if the files are compared and are identical, no output shall be written. If the two files differ, the following format is written:

"diff %s %s %s\n", <diff_options>, <filename1>, <filename2>

where <diff_options> are the options as specified on the command line.

All directory pathnames listed in this section shall be relative to the original command line arguments. All other names of files listed in this section shall be filenames (pathname components).

Diff Binary Output Format

In the POSIX locale, if one or both of the files being compared are not text files, an unspecified format shall be used that contains the pathnames of two files being compared and the string "differ" .

If both files being compared are text files, depending on the options specified, one of the following formats shall be used to write the differences.

Diff Default Output Format

The default (without -e, -f, -c, or -C options) diff utility output shall contain lines of these forms:

"%da%d\n", <num1>, <num2>

"%da%d,%d\n", <num1>, <num2>, <num3>

"%dd%d\n", <num1>, <num2>

"%d,%dd%d\n", <num1>, <num2>, <num3>

"%dc%d\n", <num1>, <num2>

"%d,%dc%d\n", <num1>, <num2>, <num3>

"%dc%d,%d\n", <num1>, <num2>, <num3>

"%d,%dc%d,%d\n", <num1>, <num2>, <num3>, <num4>

These lines resemble ed subcommands to convert file1 into file2. The line numbers before the action letters shall pertain to file1; those after shall pertain to file2. Thus, by exchanging a for d and reading the line in reverse order, one can also determine how to convert file2 into file1. As in ed, identical pairs (where num1= num2) are abbreviated as a single number.

Following each of these lines, diff shall write to standard output all lines affected in the first file using the format:

"< %s", <line>

and all lines affected in the second file using the format:

"> %s", <line>

If there are lines affected in both file1 and file2 (as with the c subcommand), the changes are separated with a line consisting of three hyphens:

"---\n"

Diff -e Output Format

With the -e option, a script shall be produced that shall, when provided as input to ed, along with an appended w (write) command, convert file1 into file2. Only the a (append), c (change), d (delete), i (insert), and s (substitute) commands of ed shall be used in this script. Text lines, except those consisting of the single character period ( '.' ), shall be output as they appear in the file.

Diff -f Output Format

With the -f option, an alternative format of script shall be produced. It is similar to that produced by -e, with the following differences:

1.
It is expressed in reverse sequence; the output of -e orders changes from the end of the file to the beginning; the -f from beginning to end.

2.
The command form <lines> <command-letter> used by -e is reversed. For example, 10c with -e would be c10 with -f.

3.
The form used for ranges of line numbers is <space>-separated, rather than comma-separated.

Diff -c or -C Output Format

With the -c or -C option, the output format shall consist of affected lines along with surrounding lines of context. The affected lines shall show which ones need to be deleted or changed in file1, and those added from file2. With the -c option, three lines of context, if available, shall be written before and after the affected lines. With the -C option, the user can specify how many lines of context are written. The exact format follows.

The name and last modification time of each file shall be output in the following format:

"*** %s %s\n", file1, <file1 timestamp>
"--- %s %s\n", file2, <file2 timestamp>

Each <file> field shall be the pathname of the corresponding file being compared. The pathname written for standard input is unspecified.

In the POSIX locale, each <timestamp> field shall be equivalent to the output from the following command:

date "+%a %b %e %T %Y"

without the trailing <newline>, executed at the time of last modification of the corresponding file (or the current time, if the file is standard input).

Then, the following output formats shall be applied for every set of changes.

First, a line shall be written in the following format:

"***************\n"

Next, the range of lines in file1 shall be written in the following format if the range contains two or more lines:

"*** %d,%d ****\n", <beginning line number>, <ending line number>

and the following format otherwise:

"*** %d ****\n", <ending line number>

The ending line number of an empty range shall be the number of the preceding line, or 0 if the range is at the start of the file.

Next, the affected lines along with lines of context (unaffected lines) shall be written. Unaffected lines shall be written in the following format:

"  %s", <unaffected_line>

Deleted lines shall be written as:

"- %s", <deleted_line>

Changed lines shall be written as:

"! %s", <changed_line>

Next, the range of lines in file2 shall be written in the following format if the range contains two or more lines:

"--- %d,%d ----\n", <beginning line number>, <ending line number>

and the following format otherwise:

"--- %d ----\n", <ending line number>

Then, lines of context and changed lines shall be written as described in the previous formats. Lines added from file2 shall be written in the following format:

"+ %s", <added_line>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
No differences were found.
1
Differences were found.
>1
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

If lines at the end of a file are changed and other lines are added, diff output may show this as a delete and add, as a change, or as a change and add; diff is not expected to know which happened and users should not care about the difference in output as long as it clearly shows the differences between the files.

EXAMPLES

If dir1 is a directory containing a directory named x, dir2 is a directory containing a directory named x, dir1/x and dir2/x both contain files named date.out, and dir2/x contains a file named y, the command:

diff -r dir1 dir2

could produce output similar to:

Common subdirectories: dir1/x and dir2/x
Only in dir2/x: y
diff -r dir1/x/date.out dir2/x/date.out
1c1
< Mon Jul  2 13:12:16 PDT 1990
---
> Tue Jun 19 21:41:39 PDT 1990

RATIONALE

The -h option was omitted because it was insufficiently specified and does not add to applications portability.

Historical implementations employ algorithms that do not always produce a minimum list of differences; the current language about making every effort is the best this volume of IEEE Std 1003.1-2001 can do, as there is no metric that could be employed to judge the quality of implementations against any and all file contents. The statement "This list should be minimal'' clearly implies that implementations are not expected to provide the following output when comparing two 100-line files that differ in only one character on a single line:

1,100c1,100
all 100 lines from file1 preceded with "< "
---
all 100 lines from file2 preceded with "> "

The "Only in" messages required when the -r option is specified are not used by most historical implementations if the -e option is also specified. It is required here because it provides useful information that must be provided to update a target directory hierarchy to match a source hierarchy. The "Common subdirectories" messages are written by System V and 4.3 BSD when the -r option is specified. They are allowed here but are not required because they are reporting on something that is the same, not reporting a difference, and are not needed to update a target hierarchy.

The -c option, which writes output in a format using lines of context, has been included. The format is useful for a variety of reasons, among them being much improved readability and the ability to understand difference changes when the target file has line numbers that differ from another similar, but slightly different, copy. The patch utility is most valuable when working with difference listings using the context format. The BSD version of -c takes an optional argument specifying the amount of context. Rather than overloading -c and breaking the Utility Syntax Guidelines for diff, the standard developers decided to add a separate option for specifying a context diff with a specified amount of context ( -C). Also, the format for context diffs was extended slightly in 4.3 BSD to allow multiple changes that are within context lines from each other to be merged together. The output format contains an additional four asterisks after the range of affected lines in the first filename. This was to provide a flag for old programs (like old versions of patch) that only understand the old context format. The version of context described here does not require that multiple changes within context lines be merged, but it does not prohibit it either. The extension is upwards-compatible, so any vendors that wish to retain the old version of diff can do so by adding the extra four asterisks (that is, utilities that currently use diff and understand the new merged format will also understand the old unmerged format, but not vice versa).

The substitute command was added as an additional format for the -e option. This was added to provide implementations with a way to fix the classic "dot alone on a line" bug present in many versions of diff. Since many implementations have fixed this bug, the standard developers decided not to standardize broken behavior, but rather to provide the necessary tool for fixing the bug. One way to fix this bug is to output two periods whenever a lone period is needed, then terminate the append command with a period, and then use the substitute command to convert the two periods into one period.

The BSD-derived -r option was added to provide a mechanism for using diff to compare two file system trees. This behavior is useful, is standard practice on all BSD-derived systems, and is not easily reproducible with the find utility.

The requirement that diff not compare files in some circumstances, even though they have the same name, is based on the actual output of historical implementations. The message specified here is already in use when a directory is being compared to a non-directory. It is extended here to preclude the problems arising from running into FIFOs and other files that would cause diff to hang waiting for input with no indication to the user that diff was hung. In most common usage, diff -r should indicate differences in the file hierarchies, not the difference of contents of devices pointed to by the hierarchies.

Many early implementations of diff require seekable files. Since the System Interfaces volume of IEEE Std 1003.1-2001 supports named pipes, the standard developers decided that such a restriction was unreasonable. Note also that the allowed filename - almost always refers to a pipe.

No directory search order is specified for diff. The historical ordering is, in fact, not optimal, in that it prints out all of the differences at the current level, including the statements about all common subdirectories before recursing into those subdirectories.

The message:

"diff %s %s %s\n", <diff_options>, <filename1>, <filename2>

does not vary by locale because it is the representation of a command, not an English sentence.

FUTURE DIRECTIONS

None.

SEE ALSO

cmp , comm , ed , find

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


rmdel(1p)

RMDEL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rmdel - remove a delta from an SCCS file (DEVELOPMENT)

SYNOPSIS

rmdel -r SID file...

DESCRIPTION

The rmdel utility shall remove the delta specified by the SID from each named SCCS file. The delta to be removed shall be the most recent delta in its branch in the delta chain of each named SCCS file. In addition, the application shall ensure that the SID specified is not that of a version being edited for the purpose of making a delta; that is, if a p-file (see get ) exists for the named SCCS file, the SID specified shall not appear in any entry of the p-file.

Removal of a delta shall be restricted to:

1.
The user who made the delta

2.
The owner of the SCCS file

3.
The owner of the directory containing the SCCS file

OPTIONS

The rmdel utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-r SID
Specify the SCCS identification string ( SID) of the delta to be deleted.

OPERANDS

The following operand shall be supported:

file
A pathname of an existing SCCS file or a directory. If file is a directory, the rmdel utility shall behave as though each file in the directory were specified as a named file, except that non-SCCS files (last component of the pathname does not begin with s.) and unreadable files shall be silently ignored.

If exactly one file operand appears, and it is '-' , the standard input shall be read; each line of the standard input is taken to be the name of an SCCS file to be processed. Non-SCCS files and unreadable files shall be silently ignored.

STDIN

The standard input shall be a text file used only when the file operand is specified as '-' . Each line of the text file shall be interpreted as an SCCS pathname.

INPUT FILES

The SCCS files shall be files of unspecified format.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of rmdel:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The SCCS files shall be files of unspecified format. During processing of a file, a temporary x-file, as described in admin , may be created and deleted; a locking z-file, as described in get , may be created and deleted.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

admin , delta , get , prs

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


rmdir(1p)

RMDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rmdir - remove directories

SYNOPSIS

rmdir [-p] dir...

DESCRIPTION

The rmdir utility shall remove the directory entry specified by each dir operand.

For each dir operand, the rmdir utility shall perform actions equivalent to the rmdir() function called with the dir operand as its only argument.

Directories shall be processed in the order specified. If a directory and a subdirectory of that directory are specified in a single invocation of the rmdir utility, the application shall specify the subdirectory before the parent directory so that the parent directory will be empty when the rmdir utility tries to remove it.

OPTIONS

The rmdir utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-p
Remove all directories in a pathname. For each dir operand:
1.
The directory entry it names shall be removed.

2.
If the dir operand includes more than one pathname component, effects equivalent to the following command shall occur:

rmdir -p $(dirname dir)

OPERANDS

The following operand shall be supported:

dir
A pathname of an empty directory to be removed.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of rmdir:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Each directory entry specified by a dir operand was removed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The definition of an empty directory is one that contains, at most, directory entries for dot and dot-dot.

EXAMPLES

If a directory a in the current directory is empty except it contains a directory b and a/b is empty except it contains a directory c:

rmdir -p a/b/c

removes all three directories.

RATIONALE

On historical System V systems, the -p option also caused a message to be written to the standard output. The message indicated whether the whole path was removed or whether part of the path remained for some reason. The STDERR section requires this diagnostic when the entire path specified by a dir operand is not removed, but does not allow the status message reporting success to be written as a diagnostic.

The rmdir utility on System V also included a -s option that suppressed the informational message output by the -p option. This option has been omitted because the informational message is not specified by this volume of IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

rm , the System Interfaces volume of IEEE Std 1003.1-2001, remove(), rmdir(), unlink()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ulimit(1p)

ULIMIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ulimit - set or report file size limit

SYNOPSIS

ulimit [-f][blocks]

DESCRIPTION

The ulimit utility shall set or report the file-size writing limit imposed on files written by the shell and its child processes (files of any size may be read). Only a process with appropriate privileges can increase the limit.

OPTIONS

The ulimit utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-f
Set (or report, if no blocks operand is present), the file size limit in blocks. The -f option shall also be the default case.

OPERANDS

The following operand shall be supported:

blocks
The number of 512-byte blocks to use as the new file size limit.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ulimit:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be used when no blocks operand is present. If the current number of blocks is limited, the number of blocks in the current limit shall be written in the following format:

"%d\n", <number of 512-byte blocks>

If there is no current limit on the number of blocks, in the POSIX locale the following format shall be used:

"unlimited\n"

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
A request for a higher limit was rejected or an error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since ulimit affects the current shell execution environment, it is always provided as a shell regular built-in. If it is called in a separate utility execution environment, such as one of the following:

nohup ulimit -f 10000
env ulimit 10000

it does not affect the file size limit of the caller's environment.

Once a limit has been decreased by a process, it cannot be increased (unless appropriate privileges are involved), even back to the original system limit.

EXAMPLES

Set the file size limit to 51200 bytes:

ulimit -f 100

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, ulimit()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


crontab(1p)

CRONTAB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

crontab - schedule periodic background work

SYNOPSIS

crontab [file]

crontab [ -e | -l | -r ]

DESCRIPTION

The crontab utility shall create, replace, or edit a user's crontab entry; a crontab entry is a list of commands and the times at which they shall be executed. The new crontab entry can be input by specifying file or input from standard input if no file operand is specified, or by using an editor, if -e is specified.

Upon execution of a command from a crontab entry, the implementation shall supply a default environment, defining at least the following environment variables:

HOME
A pathname of the user's home directory.
LOGNAME
The user's login name.
PATH
A string representing a search path guaranteed to find all of the standard utilities.
SHELL
A pathname of the command interpreter. When crontab is invoked as specified by this volume of IEEE Std 1003.1-2001, the value shall be a pathname for sh.

The values of these variables when crontab is invoked as specified by this volume of IEEE Std 1003.1-2001 shall not affect the default values provided when the scheduled command is run.

If standard output and standard error are not redirected by commands executed from the crontab entry, any generated output or errors shall be mailed, via an implementation-defined method, to the user.

Users shall be permitted to use crontab if their names appear in the file /usr/lib/cron/cron.allow. If that file does not exist, the file /usr/lib/cron/cron.deny shall be checked to determine whether the user shall be denied access to crontab. If neither file exists, only a process with appropriate privileges shall be allowed to submit a job. If only cron.deny exists and is empty, global usage shall be permitted. The cron.allow and cron.deny files shall consist of one user name per line.

OPTIONS

The crontab utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-e
Edit a copy of the invoking user's crontab entry, or create an empty entry to edit if the crontab entry does not exist. When editing is complete, the entry shall be installed as the user's crontab entry.
-l
(The letter ell.) List the invoking user's crontab entry.
-r
Remove the invoking user's crontab entry.

OPERANDS

The following operand shall be supported:

file
The pathname of a file that contains specifications, in the format defined in the INPUT FILES section, for crontab entries.

STDIN

See the INPUT FILES section.

INPUT FILES

In the POSIX locale, the user or application shall ensure that a crontab entry is a text file consisting of lines of six fields each. The fields shall be separated by <blank>s. The first five fields shall be integer patterns that specify the following:

1.
Minute [0,59]

2.
Hour [0,23]

3.
Day of the month [1,31]

4.
Month of the year [1,12]

5.
Day of the week ([0,6] with 0=Sunday)

Each of these patterns can be either an asterisk (meaning all valid values), an element, or a list of elements separated by commas. An element shall be either a number or two numbers separated by a hyphen (meaning an inclusive range). The specification of days can be made by two fields (day of the month and day of the week). If month, day of month, and day of week are all asterisks, every day shall be matched. If either the month or day of month is specified as an element or list, but the day of week is an asterisk, the month and day of month fields shall specify the days that match. If both month and day of month are specified as an asterisk, but day of week is an element or list, then only the specified days of the week match. Finally, if either the month or day of month is specified as an element or list, and the day of week is also specified as an element or list, then any day matching either the month and day of month, or the day of week, shall be matched.

The sixth field of a line in a crontab entry is a string that shall be executed by sh at the specified times. A percent sign character in this field shall be translated to a <newline>. Any character preceded by a backslash (including the '%' ) shall cause that character to be treated literally. Only the first line (up to a '%' or end-of-line) of the command field shall be executed by the command interpreter. The other lines shall be made available to the command as standard input.

Blank lines and those whose first non- <blank> is '#' shall be ignored.

The text files /usr/lib/cron/cron.allow and /usr/lib/cron/cron.deny shall contain zero or more user names, one per line, of users who are, respectively, authorized or denied access to the service underlying the crontab utility.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of crontab:

EDITOR
Determine the editor to be invoked when the -e option is specified. The default editor shall be vi.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If the -l option is specified, the crontab entry shall be written to the standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

The user's crontab entry is not submitted, removed, edited, or listed.

The following sections are informative.

APPLICATION USAGE

The format of the crontab entry shown here is guaranteed only for the POSIX locale. Other cultures may be supported with substantially different interfaces, although implementations are encouraged to provide comparable levels of functionality.

The default settings of the HOME , LOGNAME , PATH , and SHELL variables that are given to the scheduled job are not affected by the settings of those variables when crontab is run; as stated, they are defaults. The text about "invoked as specified by this volume of IEEE Std 1003.1-2001" means that the implementation may provide extensions that allow these variables to be affected at runtime, but that the user has to take explicit action in order to access the extension, such as give a new option flag or modify the format of the crontab entry.

A typical user error is to type only crontab; this causes the system to wait for the new crontab entry on standard input. If end-of-file is typed (generally <control>-D), the crontab entry is replaced by an empty file. In this case, the user should type the interrupt character, which prevents the crontab entry from being replaced.

EXAMPLES

1.
Clean up core files every weekday morning at 3:15 am:

15 3 * * 1-5 find $HOME -name core 2>/dev/null | xargs rm -f

2.
Mail a birthday greeting:

0 12 14 2 * mailx john%Happy Birthday!%Time for lunch.

3.
As an example of specifying the two types of days:

0 0 1,15 * 1

would run a command on the first and fifteenth of each month, as well as on every Monday. To specify days by only one field, the other field should be set to '*' ; for example:

0 0 * * 1

would run a command only on Mondays.

RATIONALE

All references to a cron daemon and to cron files have been omitted. Although historical implementations have used this arrangement, there is no reason to limit future implementations.

This description of crontab is designed to support only users with normal privileges. The format of the input is based on the System V crontab; however, there is no requirement here that the actual system database used by the cron daemon (or a similar mechanism) use this format internally. For example, systems derived from BSD are likely to have an additional field appended that indicates the user identity to be used when the job is submitted.

The -e option was adopted from the SVID as a user convenience, although it does not exist in all historical implementations.

FUTURE DIRECTIONS

None.

SEE ALSO

at

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


kill(1p)

KILL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

kill - terminate or signal processes

SYNOPSIS

kill -s signal_name pid ...

kill -l [exit_status]

kill [-signal_name] pid ...

kill [-signal_number] pid ...

DESCRIPTION

The kill utility shall send a signal to the process or processes specified by each pid operand.

For each pid operand, the kill utility shall perform actions equivalent to the kill() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 called with the following arguments:

*
The value of the pid operand shall be used as the pid argument.

*
The sig argument is the value specified by the -s option, - signal_number option, or the - signal_name option, or by SIGTERM, if none of these options is specified.

OPTIONS

The kill utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that in the last two SYNOPSIS forms, the - signal_number and - signal_name options are usually more than a single character.

The following options shall be supported:

-l
(The letter ell.) Write all values of signal_name supported by the implementation, if no operand is given. If an exit_status operand is given and it is a value of the '?' shell special parameter (see Special Parameters and wait() ) corresponding to a process that was terminated by a signal, the signal_name corresponding to the signal that terminated the process shall be written. If an exit_status operand is given and it is the unsigned decimal integer value of a signal number, the signal_name (the symbolic constant name without the SIG prefix defined in the Base Definitions volume of IEEE Std 1003.1-2001) corresponding to that signal shall be written. Otherwise, the results are unspecified.
-s signal_name

Specify the signal to send, using one of the symbolic names defined in the <signal.h> header. Values of signal_name shall be recognized in a case-independent fashion, without the SIG prefix. In addition, the symbolic name 0 shall be recognized, representing the signal value zero. The corresponding signal shall be sent instead of SIGTERM.

-signal_name

Equivalent to -s signal_name.

-signal_number

Specify a non-negative decimal integer, signal_number, representing the signal to be used instead of SIGTERM, as the sig argument in the effective call to kill(). The correspondence between integer values and the sig value used is shown in the following table.

The effects of specifying any signal_number other than those listed in the table are undefined.

signal_number | sig Value
0 | 0
1 | SIGHUP
2 | SIGINT
3 | SIGQUIT
6 | SIGABRT
9 | SIGKILL
14 | SIGALRM
15 | SIGTERM

If the first argument is a negative integer, it shall be interpreted as a - signal_number option, not as a negative pid operand specifying a process group.

OPERANDS

The following operands shall be supported:

pid
One of the following:
1.
A decimal integer specifying a process or process group to be signaled. The process or processes selected by positive, negative, and zero values of the pid operand shall be as described for the kill() function. If process number 0 is specified, all processes in the current process group shall be signaled. For the effects of negative pid numbers, see the kill() function defined in the System Interfaces volume of IEEE Std 1003.1-2001. If the first pid operand is negative, it should be preceded by "--" to keep it from being interpreted as an option.

2.
A job control job ID (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.203, Job Control Job ID) that identifies a background process group to be signaled. The job control job ID notation is applicable only for invocations of kill in the current shell execution environment; see Shell Execution Environment .

exit_status
A decimal integer specifying a signal number or the exit status of a process terminated by a signal.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of kill:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

When the -l option is not specified, the standard output shall not be used.

When the -l option is specified, the symbolic name of each signal shall be written in the following format:

"%s%c", <signal_name>, <separator>

where the <signal_name> is in uppercase, without the SIG prefix, and the <separator> shall be either a <newline> or a <space>. For the last signal written, <separator> shall be a <newline>.

When both the -l option and exit_status operand are specified, the symbolic name of the corresponding signal shall be written in the following format:

"%s\n", <signal_name>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
At least one matching process was found for each pid operand, and the specified signal was successfully processed for at least one matching process.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Process numbers can be found by using ps.

The job control job ID notation is not required to work as expected when kill is operating in its own utility execution environment. In either of the following examples:

nohup kill %1 &
system("kill %1");

the kill operates in a different environment and does not share the shell's understanding of job numbers.

EXAMPLES

Any of the commands:

kill -9 100 -165
kill -s kill 100 -165
kill -s KILL 100 -165

sends the SIGKILL signal to the process whose process ID is 100 and to all processes whose process group ID is 165, assuming the sending process has permission to send that signal to the specified processes, and that they exist.

The System Interfaces volume of IEEE Std 1003.1-2001 and this volume of IEEE Std 1003.1-2001 do not require specific signal numbers for any signal_names. Even the - signal_number option provides symbolic (although numeric) names for signals. If a process is terminated by a signal, its exit status indicates the signal that killed it, but the exact values are not specified. The kill -l option, however, can be used to map decimal signal numbers and exit status values into the name of a signal. The following example reports the status of a terminated job:

job
stat=$?
if [ $stat -eq 0 ]
then
    echo job completed successfully.
elif [ $stat -gt 128 ]
then
    echo job terminated by signal SIG$(kill -l $stat).
else
    echo job terminated with error code $stat.
fi

To send the default signal to a process group (say 123), an application should use a command similar to one of the following:

kill -TERM -123
kill -- -123

RATIONALE

The -l option originated from the C shell, and is also implemented in the KornShell. The C shell output can consist of multiple output lines because the signal names do not always fit on a single line on some terminal screens. The KornShell output also included the implementation-defined signal numbers and was considered by the standard developers to be too difficult for scripts to parse conveniently. The specified output format is intended not only to accommodate the historical C shell output, but also to permit an entirely vertical or entirely horizontal listing on systems for which this is appropriate.

An early proposal invented the name SIGNULL as a signal_name for signal 0 (used by the System Interfaces volume of IEEE Std 1003.1-2001 to test for the existence of a process without sending it a signal). Since the signal_name 0 can be used in this case unambiguously, SIGNULL has been removed.

An early proposal also required symbolic signal_names to be recognized with or without the SIG prefix. Historical versions of kill have not written the SIG prefix for the -l option and have not recognized the SIG prefix on signal_names. Since neither applications portability nor ease-of-use would be improved by requiring this extension, it is no longer required.

To avoid an ambiguity of an initial negative number argument specifying either a signal number or a process group, IEEE Std 1003.1-2001 mandates that it is always considered the former by implementations that support the XSI option. It also requires that conforming applications always use the "--" options terminator argument when specifying a process group, unless an option is also specified.

The -s option was added in response to international interest in providing some form of kill that meets the Utility Syntax Guidelines.

The job control job ID notation is not required to work as expected when kill is operating in its own utility execution environment. In either of the following examples:

nohup kill %1 &
system("kill %1");

the kill operates in a different environment and does not understand how the shell has managed its job numbers.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , ps , wait() , the System Interfaces volume of IEEE Std 1003.1-2001, kill(), the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qrls(1p)

QRLS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qrls - release batch jobs

SYNOPSIS

qrls [-h hold_list] job_identifier ...

DESCRIPTION

A batch job might have one or more holds, which prevent the batch job from executing. A batch job from which all the holds have been removed becomes eligible for execution and is said to have been released. A batch job hold is removed by sending a request to the batch server that manages the batch job. The qrls utility is a user-accessible client of batch services that requests holds be removed from one or more batch jobs.

The qrls utility shall remove one or more holds from those batch jobs for which a batch job_identifier is presented to the utility.

The qrls utility shall remove holds from batch jobs in the order in which their batch job_identifiers are presented to the utility.

If the qrls utility fails to process a batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

The qrls utility shall remove holds on each batch job by sending a Release Job Request to the batch server that manages the batch job.

The qrls utility shall not exit until the holds have been removed from the batch job corresponding to each successfully processed batch job_identifier.

OPTIONS

The qrls utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported by the implementation:

-h hold_list
Define the types of holds to be removed from the batch job.

The qrls -h option shall accept a value for the hold_list option-argument that is a string of alphanumeric characters in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set).

The qrls utility shall accept a value for the hold_list option-argument that is a string of one or more of the characters 'u' , 's' , or 'o' , or the single character 'n' .

For each unique character in the hold_list option-argument, the qrls utility shall add a value to the Hold_Types attribute of the batch job as follows, each representing a different hold type:

u
USER
s
SYSTEM
o
OPERATOR

If any of these characters are duplicated in the hold_list option-argument, the duplicates shall be ignored.

An existing Hold_Types attribute can be cleared by the following hold type:

n
NO_HOLD

The qrls utility shall consider it an error if any hold type other than 'n' is combined with hold type 'n' .

Strictly conforming applications shall not repeat any of the characters 'u' , 's' , 'o' , or 'n' within the hold_list option-argument. The qrls utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters.

An implementation may define other hold types. The conformance document for an implementation shall describe any additional hold types, how they are specified, their internal behavior, and how they affect the behavior of the utility.

If the -h option is not presented to the qrls utility, the implementation shall remove the USER hold in the Hold_Types attribute.

OPERANDS

The qrls utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qrls:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qrls utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qrls utility waits to output the diagnostic message while attempting to locate the job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qrls utility allows users, operators, and administrators to remove holds from jobs.

The qrls utility does not support any job selection options or wildcard arguments. Users may acquire a list of jobs selected by attributes using the qselect utility. For example, a user could select all of their held jobs.

The -h option allows the user to specify the type of hold that is to be removed. This option allows for USER, SYSTEM, OPERATOR, and implementation-defined hold types. The batch server that manages the batch job will verify whether the user is authorized to remove the specified hold for the batch job. If more than one type of hold has been placed on the batch job, a user may wish to remove only some of them.

Mail is not required on release because the administrator has the tools and libraries to build this option if required.

The qrls utility is a new utility vis-a-vis existing practice; it has been defined in this volume of IEEE Std 1003.1-2001 as the natural complement to the qhold utility.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , qhold , qselect

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


bc(1p)

BC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bc - arbitrary-precision arithmetic language

SYNOPSIS

bc [-l] [file ...]

DESCRIPTION

The bc utility shall implement an arbitrary precision calculator. It shall take input from any files given, then read from the standard input. If the standard input and standard output to bc are attached to a terminal, the invocation of bc shall be considered to be interactive, causing behavioral constraints described in the following sections.

OPTIONS

The bc utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-l
(The letter ell.) Define the math functions and initialize scale to 20, instead of the default zero; see the EXTENDED DESCRIPTION section.

OPERANDS

The following operand shall be supported:

file
A pathname of a text file containing bc program statements. After all files have been read, bc shall read the standard input.

STDIN

See the INPUT FILES section.

INPUT FILES

Input files shall be text files containing a sequence of comments, statements, and function definitions that shall be executed as they are read.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of bc:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The output of the bc utility shall be controlled by the program read, and consist of zero or more lines containing the value of all executed expressions without assignments. The radix and precision of the output shall be controlled by the values of the obase and scale variables; see the EXTENDED DESCRIPTION section.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

Grammar

The grammar in this section and the lexical conventions in the following section shall together describe the syntax for bc programs. The general conventions for this style of grammar are described in Grammar Conventions . A valid program can be represented as the non-terminal symbol program in the grammar. This formal syntax shall take precedence over the text syntax description.

%token    EOF NEWLINE STRING LETTER NUMBER

%token    MUL_OP
/*        '*', '/', '%'                           */

%token    ASSIGN_OP
/*        '=', '+=', '-=', '*=', '/=', '%=', '^=' */

%token    REL_OP
/*        '==', '<=', '>=', '!=', '<', '>'        */

%token    INCR_DECR
/*        '++', '--'                              */

%token    Define    Break    Quit    Length
/*        'define', 'break', 'quit', 'length'     */

%token    Return    For    If    While    Sqrt
/*        'return', 'for', 'if', 'while', 'sqrt'  */

%token    Scale    Ibase    Obase    Auto
/*        'scale', 'ibase', 'obase', 'auto'       */

%start    program

%%

program              : EOF
                     | input_item program
                     ;

input_item           : semicolon_list NEWLINE
                     | function
                     ;

semicolon_list       : /* empty */
                     | statement
                     | semicolon_list ';' statement
                     | semicolon_list ';'
                     ;

statement_list       : /* empty */
                     | statement
                     | statement_list NEWLINE
                     | statement_list NEWLINE statement
                     | statement_list ';'
                     | statement_list ';' statement
                     ;

statement            : expression
                     | STRING
                     | Break
                     | Quit
                     | Return
                     | Return '(' return_expression ')'
                     | For '(' expression ';'
                           relational_expression ';'
                           expression ')' statement
                     | If '(' relational_expression ')' statement
                     | While '(' relational_expression ')' statement
                     | '{' statement_list '}'
                     ;

function             : Define LETTER '(' opt_parameter_list ')'
                           '{' NEWLINE opt_auto_define_list
                           statement_list '}'
                     ;

opt_parameter_list   : /* empty */
                     | parameter_list
                     ;

parameter_list       : LETTER
                     | define_list ',' LETTER
                     ;

opt_auto_define_list : /* empty */
                     | Auto define_list NEWLINE
                     | Auto define_list ';'
                     ;

define_list          : LETTER
                     | LETTER '[' ']'
                     | define_list ',' LETTER
                     | define_list ',' LETTER '[' ']'
                     ;

opt_argument_list    : /* empty */
                     | argument_list
                     ;

argument_list        : expression
                     | LETTER '[' ']' ',' argument_list
                     ;

relational_expression : expression
                     | expression REL_OP expression
                     ;

return_expression    : /* empty */
                     | expression
                     ;

expression           : named_expression
                     | NUMBER
                     | '(' expression ')'
                     | LETTER '(' opt_argument_list ')'
                     | '-' expression
                     | expression '+' expression
                     | expression '-' expression
                     | expression MUL_OP expression
                     | expression '^' expression
                     | INCR_DECR named_expression
                     | named_expression INCR_DECR
                     | named_expression ASSIGN_OP expression
                     | Length '(' expression ')'
                     | Sqrt '(' expression ')'
                     | Scale '(' expression ')'
                     ;

named_expression     : LETTER
                     | LETTER '[' expression ']'
                     | Scale
                     | Ibase
                     | Obase
                     ;

Lexical Conventions in bc

The lexical conventions for bc programs, with respect to the preceding grammar, shall be as follows:

1.
Except as noted, bc shall recognize the longest possible token or delimiter beginning at a given point.

2.
A comment shall consist of any characters beginning with the two adjacent characters "/*" and terminated by the next occurrence of the two adjacent characters "*/" . Comments shall have no effect except to delimit lexical tokens.

3.
The <newline> shall be recognized as the token NEWLINE.

4.
The token STRING shall represent a string constant; it shall consist of any characters beginning with the double-quote character ( ' )' and terminated by another occurrence of the double-quote character. The value of the string is the sequence of all characters between, but not including, the two double-quote characters. All characters shall be taken literally from the input, and there is no way to specify a string containing a double-quote character. The length of the value of each string shall be limited to {BC_STRING_MAX} bytes.

5.
A <blank> shall have no effect except as an ordinary character if it appears within a STRING token, or to delimit a lexical token other than STRING.

6.
The combination of a backslash character immediately followed by a <newline> shall have no effect other than to delimit lexical tokens with the following exceptions:
*
It shall be interpreted as the character sequence "\<newline>" in STRING tokens.

*
It shall be ignored as part of a multi-line NUMBER token.

7.
The token NUMBER shall represent a numeric constant. It shall be recognized by the following grammar:

NUMBER  : integer
        | '.' integer
        | integer '.'
        | integer '.' integer
        ;

integer : digit
        | integer digit
        ;

digit   : 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
        | 8 | 9 | A | B | C | D | E | F
        ;

8.
The value of a NUMBER token shall be interpreted as a numeral in the base specified by the value of the internal register ibase (described below). Each of the digit characters shall have the value from 0 to 15 in the order listed here, and the period character shall represent the radix point. The behavior is undefined if digits greater than or equal to the value of ibase appear in the token. However, note the exception for single-digit values being assigned to ibase and obase themselves, in Operations in bc .

9.
The following keywords shall be recognized as tokens:

auto
break
define

ibase
if
for

length
obase
quit

return
scale
sqrt

while

10.
Any of the following characters occurring anywhere except within a keyword shall be recognized as the token LETTER:

a b c d e f g h i j k l m n o p q r s t u v w x y z

11.
The following single-character and two-character sequences shall be recognized as the token ASSIGN_OP:

=   +=   -=   *=   /=   %=   ^=

12.
If an '=' character, as the beginning of a token, is followed by a '-' character with no intervening delimiter, the behavior is undefined.

13.
The following single-characters shall be recognized as the token MUL_OP:

*   /   %

14.
The following single-character and two-character sequences shall be recognized as the token REL_OP:

==   <=   >=   !=   <   >

15.
The following two-character sequences shall be recognized as the token INCR_DECR:

++   --

16.
The following single characters shall be recognized as tokens whose names are the character:

<newline>  (  )  ,  +  -  ;  [  ]  ^  {  }

17.
The token EOF is returned when the end of input is reached.

Operations in bc

There are three kinds of identifiers: ordinary identifiers, array identifiers, and function identifiers. All three types consist of single lowercase letters. Array identifiers shall be followed by square brackets ( "[]" ). An array subscript is required except in an argument or auto list. Arrays are singly dimensioned and can contain up to {BC_DIM_MAX} elements. Indexing shall begin at zero so an array is indexed from 0 to {BC_DIM_MAX}-1. Subscripts shall be truncated to integers. The application shall ensure that function identifiers are followed by parentheses, possibly enclosing arguments. The three types of identifiers do not conflict.

The following table summarizes the rules for precedence and associativity of all operators. Operators on the same line shall have the same precedence; rows are in order of decreasing precedence.

Table: Operators in bc
Operator | Associativity
++, -- | N/A
unary - | N/A
^ | Right to left
*, /, % | Left to right
+, binary - | Left to right
=, +=, -=, *=, /=, %=, ^= | Right to left
==, <=, >=, !=, <, > | None

Each expression or named expression has a scale, which is the number of decimal digits that shall be maintained as the fractional portion of the expression.

Named expressions are places where values are stored. Named expressions shall be valid on the left side of an assignment. The value of a named expression shall be the value stored in the place named. Simple identifiers and array elements are named expressions; they have an initial value of zero and an initial scale of zero.

The internal registers scale, ibase, and obase are all named expressions. The scale of an expression consisting of the name of one of these registers shall be zero; values assigned to any of these registers are truncated to integers. The scale register shall contain a global value used in computing the scale of expressions (as described below). The value of the register scale is limited to 0 <= scale <= {BC_SCALE_MAX} and shall have a default value of zero. The ibase and obase registers are the input and output number radix, respectively. The value of ibase shall be limited to:

2 <= ibase <= 16

The value of obase shall be limited to:

2 <= obase <= {BC_BASE_MAX}

When either ibase or obase is assigned a single digit value from the list in Lexical Conventions in bc , the value shall be assumed in hexadecimal. (For example, ibase=A sets to base ten, regardless of the current ibase value.) Otherwise, the behavior is undefined when digits greater than or equal to the value of ibase appear in the input. Both ibase and obase shall have initial values of 10.

Internal computations shall be conducted as if in decimal, regardless of the input and output bases, to the specified number of decimal digits. When an exact result is not achieved (for example, scale=0; 3.2/1), the result shall be truncated.

For all values of obase specified by this volume of IEEE Std 1003.1-2001, bc shall output numeric values by performing each of the following steps in order:

1.
If the value is less than zero, a hyphen ( '-' ) character shall be output.

2.
One of the following is output, depending on the numerical value:
*
If the absolute value of the numerical value is greater than or equal to one, the integer portion of the value shall be output as a series of digits appropriate to obase (as described below), most significant digit first. The most significant non-zero digit shall be output next, followed by each successively less significant digit.

*
If the absolute value of the numerical value is less than one but greater than zero and the scale of the numerical value is greater than zero, it is unspecified whether the character 0 is output.

*
If the numerical value is zero, the character 0 shall be output.

3.
If the scale of the value is greater than zero and the numeric value is not zero, a period character shall be output, followed by a series of digits appropriate to obase (as described below) representing the most significant portion of the fractional part of the value. If s represents the scale of the value being output, the number of digits output shall be s if obase is 10, less than or equal to s if obase is greater than 10, or greater than or equal to s if obase is less than 10. For obase values other than 10, this should be the number of digits needed to represent a precision of 10**s.

For obase values from 2 to 16, valid digits are the first obase of the single characters:

0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F

which represent the values zero to 15, inclusive, respectively.

For bases greater than 16, each digit shall be written as a separate multi-digit decimal number. Each digit except the most significant fractional digit shall be preceded by a single <space>. For bases from 17 to 100, bc shall write two-digit decimal numbers; for bases from 101 to 1000, three-digit decimal strings, and so on. For example, the decimal number 1024 in base 25 would be written as:

 01 15 24

and in base 125, as:

 008 024

Very large numbers shall be split across lines with 70 characters per line in the POSIX locale; other locales may split at different character boundaries. Lines that are continued shall end with a backslash ( '\' ).

A function call shall consist of a function name followed by parentheses containing a comma-separated list of expressions, which are the function arguments. A whole array passed as an argument shall be specified by the array name followed by empty square brackets. All function arguments shall be passed by value. As a result, changes made to the formal parameters shall have no effect on the actual arguments. If the function terminates by executing a return statement, the value of the function shall be the value of the expression in the parentheses of the return statement or shall be zero if no expression is provided or if there is no return statement.

The result of sqrt( expression) shall be the square root of the expression. The result shall be truncated in the least significant decimal place. The scale of the result shall be the scale of the expression or the value of scale, whichever is larger.

The result of length( expression) shall be the total number of significant decimal digits in the expression. The scale of the result shall be zero.

The result of scale( expression) shall be the scale of the expression. The scale of the result shall be zero.

A numeric constant shall be an expression. The scale shall be the number of digits that follow the radix point in the input representing the constant, or zero if no radix point appears.

The sequence ( expression ) shall be an expression with the same value and scale as expression. The parentheses can be used to alter the normal precedence.

The semantics of the unary and binary operators are as follows:

-expression

The result shall be the negative of the expression. The scale of the result shall be the scale of expression.

The unary increment and decrement operators shall not modify the scale of the named expression upon which they operate. The scale of the result shall be the scale of that named expression.

++named-expression

The named expression shall be incremented by one. The result shall be the value of the named expression after incrementing.

--named-expression

The named expression shall be decremented by one. The result shall be the value of the named expression after decrementing.

named-expression++

The named expression shall be incremented by one. The result shall be the value of the named expression before incrementing.

named-expression--

The named expression shall be decremented by one. The result shall be the value of the named expression before decrementing.

The exponentiation operator, circumflex ( '^' ), shall bind right to left.

expression^expression

The result shall be the first expression raised to the power of the second expression. If the second expression is not an integer, the behavior is undefined. If a is the scale of the left expression and b is the absolute value of the right expression, the scale of the result shall be:

if b >= 0 min(a * b, max(scale, a)) if b < 0 scale

The multiplicative operators ( '*' , '/' , '%' ) shall bind left to right.

expression*expression

The result shall be the product of the two expressions. If a and b are the scales of the two expressions, then the scale of the result shall be:

min(a+b,max(scale,a,b))
expression/expression

The result shall be the quotient of the two expressions. The scale of the result shall be the value of scale.

expression%expression

For expressions a and b, a% b shall be evaluated equivalent to the steps:

1.
Compute a/ b to current scale.

2.
Use the result to compute:

a - (a / b) * b

to scale:

max(scale + scale(b), scale(a))

The scale of the result shall be:

max(scale + scale(b), scale(a))

When scale is zero, the '%' operator is the mathematical remainder operator.

The additive operators ( '+' , '-' ) shall bind left to right.

expression+expression

The result shall be the sum of the two expressions. The scale of the result shall be the maximum of the scales of the expressions.

expression-expression

The result shall be the difference of the two expressions. The scale of the result shall be the maximum of the scales of the expressions.

The assignment operators ( '=' , "+=" , "-=" , "*=" , "/=" , "%=" , "^=" ) shall bind right to left.

named-expression=expression

This expression shall result in assigning the value of the expression on the right to the named expression on the left. The scale of both the named expression and the result shall be the scale of expression.

The compound assignment forms:

named-expression <operator>= expression

shall be equivalent to:

named-expression=named-expression <operator> expression

except that the named-expression shall be evaluated only once.

Unlike all other operators, the relational operators ( '<' , '>' , "<=" , ">=" , "==" , "!=" ) shall be only valid as the object of an if, while, or inside a for statement.

expression1<expression2

The relation shall be true if the value of expression1 is strictly less than the value of expression2.

expression1>expression2

The relation shall be true if the value of expression1 is strictly greater than the value of expression2.

expression1<=expression2

The relation shall be true if the value of expression1 is less than or equal to the value of expression2.

expression1>=expression2

The relation shall be true if the value of expression1 is greater than or equal to the value of expression2.

expression1==expression2

The relation shall be true if the values of expression1 and expression2 are equal.

expression1!=expression2

The relation shall be true if the values of expression1 and expression2 are unequal.

There are only two storage classes in bc: global and automatic (local). Only identifiers that are local to a function need be declared with the auto command. The arguments to a function shall be local to the function. All other identifiers are assumed to be global and available to all functions. All identifiers, global and local, have initial values of zero. Identifiers declared as auto shall be allocated on entry to the function and released on returning from the function. They therefore do not retain values between function calls. Auto arrays shall be specified by the array name followed by empty square brackets. On entry to a function, the old values of the names that appear as parameters and as automatic variables shall be pushed onto a stack. Until the function returns, reference to these names shall refer only to the new values.

References to any of these names from other functions that are called from this function also refer to the new value until one of those functions uses the same name for a local variable.

When a statement is an expression, unless the main operator is an assignment, execution of the statement shall write the value of the expression followed by a <newline>.

When a statement is a string, execution of the statement shall write the value of the string.

Statements separated by semicolons or <newline>s shall be executed sequentially. In an interactive invocation of bc, each time a <newline> is read that satisfies the grammatical production:

input_item : semicolon_list NEWLINE

the sequential list of statements making up the semicolon_list shall be executed immediately and any output produced by that execution shall be written without any delay due to buffering.

In an if statement ( if( relation) statement), the statement shall be executed if the relation is true.

The while statement ( while( relation) statement) implements a loop in which the relation is tested; each time the relation is true, the statement shall be executed and the relation retested. When the relation is false, execution shall resume after statement.

A for statement( for( expression; relation; expression) statement) shall be the same as:

first-expressionwhile (relation) {
    statement    last-expression}
The application shall ensure that all three expressions are present.

The break statement shall cause termination of a for or while statement.

The auto statement ( auto identifier [, identifier ] ...) shall cause the values of the identifiers to be pushed down. The identifiers can be ordinary identifiers or array identifiers. Array identifiers shall be specified by following the array name by empty square brackets. The application shall ensure that the auto statement is the first statement in a function definition.

A define statement:

define LETTER ( opt_parameter_list ) {
    opt_auto_define_list    statement_list}

defines a function named LETTER. If a function named LETTER was previously defined, the define statement shall replace the previous definition. The expression:

LETTER ( opt_argument_list )

shall invoke the function named LETTER. The behavior is undefined if the number of arguments in the invocation does not match the number of parameters in the definition. Functions shall be defined before they are invoked. A function shall be considered to be defined within its own body, so recursive calls are valid. The values of numeric constants within a function shall be interpreted in the base specified by the value of the ibase register when the function is invoked.

The return statements ( return and return( expression)) shall cause termination of a function, popping of its auto variables, and specification of the result of the function. The first form shall be equivalent to return(0). The value and scale of the result returned by the function shall be the value and scale of the expression returned.

The quit statement ( quit) shall stop execution of a bc program at the point where the statement occurs in the input, even if it occurs in a function definition, or in an if, for, or while statement.

The following functions shall be defined when the -l option is specified:

s( expression )

Sine of argument in radians.

c( expression )

Cosine of argument in radians.

a( expression )

Arctangent of argument.

l( expression )

Natural logarithm of argument.

e( expression )

Exponential function of argument.

j( expression, expression )

Bessel function of integer order.

The scale of the result returned by these functions shall be the value of the scale register at the time the function is invoked. The value of the scale register after these functions have completed their execution shall be the same value it had upon invocation. The behavior is undefined if any of these functions is invoked with an argument outside the domain of the mathematical function.

EXIT STATUS

The following exit values shall be returned:

0
All input files were processed successfully.
unspecified
An error occurred.

CONSEQUENCES OF ERRORS

If any file operand is specified and the named file cannot be accessed, bc shall write a diagnostic message to standard error and terminate without any further action.

In an interactive invocation of bc, the utility should print an error message and recover following any error in the input. In a non-interactive invocation of bc, invalid input causes undefined behavior.

The following sections are informative.

APPLICATION USAGE

Automatic variables in bc do not work in exactly the same way as in either C or PL/1.

For historical reasons, the exit status from bc cannot be relied upon to indicate that an error has occurred. Returning zero after an error is possible. Therefore, bc should be used primarily by interactive users (who can react to error messages) or by application programs that can somehow validate the answers returned as not including error messages.

The bc utility always uses the period ( '.' ) character to represent a radix point, regardless of any decimal-point character specified as part of the current locale. In languages like C or awk, the period character is used in program source, so it can be portable and unambiguous, while the locale-specific character is used in input and output. Because there is no distinction between source and input in bc, this arrangement would not be possible. Using the locale-specific character in bc's input would introduce ambiguities into the language; consider the following example in a locale with a comma as the decimal-point character:

define f(a,b) {
    ...
}
...

f(1,2,3)

Because of such ambiguities, the period character is used in input. Having input follow different conventions from output would be confusing in either pipeline usage or interactive usage, so the period is also used in output.

EXAMPLES

In the shell, the following assigns an approximation of the first ten digits of 'pi' to the variable x:

x=$(printf "%s\n" 'scale = 10; 104348/33215' | bc)

The following bc program prints the same approximation of 'pi' , with a label, to standard output:

scale = 10
"pi equals "
104348 / 33215

The following defines a function to compute an approximate value of the exponential function (note that such a function is predefined if the -l option is specified):

scale = 20
define e(x){
    auto a, b, c, i, s
    a = 1
    b = 1
    s = 1
    for (i = 1; 1 == 1; i++){
        a = a*x
        b = b*i
        c = a/b
        if (c == 0) {
             return(s)
        }
        s = s+c
    }
}

The following prints approximate values of the exponential function of the first ten integers:

for (i = 1; i <= 10; ++i) {
    e(i)
}

RATIONALE

The bc utility is implemented historically as a front-end processor for dc; dc was not selected to be part of this volume of IEEE Std 1003.1-2001 because bc was thought to have a more intuitive programmatic interface. Current implementations that implement bc using dc are expected to be compliant.

The exit status for error conditions has been left unspecified for several reasons:

*
The bc utility is used in both interactive and non-interactive situations. Different exit codes may be appropriate for the two uses.

*
It is unclear when a non-zero exit should be given; divide-by-zero, undefined functions, and syntax errors are all possibilities.

*
It is not clear what utility the exit status has.

*
In the 4.3 BSD, System V, and Ninth Edition implementations, bc works in conjunction with dc. The dc utility is the parent, bc is the child. This was done to cleanly terminate bc if dc aborted.

The decision to have bc exit upon encountering an inaccessible input file is based on the belief that bc file1 file2 is used most often when at least file1 contains data/function declarations/initializations. Having bc continue with prerequisite files missing is probably not useful. There is no implication in the CONSEQUENCES OF ERRORS section that bc must check all its files for accessibility before opening any of them.

There was considerable debate on the appropriateness of the language accepted by bc. Several reviewers preferred to see either a pure subset of the C language or some changes to make the language more compatible with C. While the bc language has some obvious similarities to C, it has never claimed to be compatible with any version of C. An interpreter for a subset of C might be a very worthwhile utility, and it could potentially make bc obsolete. However, no such utility is known in historical practice, and it was not within the scope of this volume of IEEE Std 1003.1-2001 to define such a language and utility. If and when they are defined, it may be appropriate to include them in a future version of IEEE Std 1003.1. This left the following alternatives:

1.
Exclude any calculator language from this volume of IEEE Std 1003.1-2001.

The consensus of the standard developers was that a simple programmatic calculator language is very useful for both applications and interactive users. The only arguments for excluding any calculator were that it would become obsolete if and when a C-compatible one emerged, or that the absence would encourage the development of such a C-compatible one. These arguments did not sufficiently address the needs of current application writers.

2.
Standardize the historical dc, possibly with minor modifications.

The consensus of the standard developers was that dc is a fundamentally less usable language and that that would be far too severe a penalty for avoiding the issue of being similar to but incompatible with C.

3.
Standardize the historical bc, possibly with minor modifications.

This was the approach taken. Most of the proponents of changing the language would not have been satisfied until most or all of the incompatibilities with C were resolved. Since most of the changes considered most desirable would break historical applications and require significant modification to historical implementations, almost no modifications were made. The one significant modification that was made was the replacement of the historical bc assignment operators "=+" , and so on, with the more modern "+=" , and so on. The older versions are considered to be fundamentally flawed because of the lexical ambiguity in uses like a=-1.

In order to permit implementations to deal with backwards-compatibility as they see fit, the behavior of this one ambiguous construct was made undefined. (At least three implementations have been known to support this change already, so the degree of change involved should not be great.)

The '%' operator is the mathematical remainder operator when scale is zero. The behavior of this operator for other values of scale is from historical implementations of bc, and has been maintained for the sake of historical applications despite its non-intuitive nature.

Historical implementations permit setting ibase and obase to a broader range of values. This includes values less than 2, which were not seen as sufficiently useful to standardize. These implementations do not interpret input properly for values of ibase that are greater than 16. This is because numeric constants are recognized syntactically, rather than lexically, as described in this volume of IEEE Std 1003.1-2001. They are built from lexical tokens of single hexadecimal digits and periods. Since <blank>s between tokens are not visible at the syntactic level, it is not possible to recognize the multi-digit "digits" used in the higher bases properly. The ability to recognize input in these bases was not considered useful enough to require modifying these implementations. Note that the recognition of numeric constants at the syntactic level is not a problem with conformance to this volume of IEEE Std 1003.1-2001, as it does not impact the behavior of conforming applications (and correct bc programs). Historical implementations also accept input with all of the digits '0' - '9' and 'A' - 'F' regardless of the value of ibase; since digits with value greater than or equal to ibase are not really appropriate, the behavior when they appear is undefined, except for the common case of:

ibase=8;
    /* Process in octal base. */
...
ibase=A
    /* Restore decimal base. */

In some historical implementations, if the expression to be written is an uninitialized array element, a leading <space> and/or up to four leading 0 characters may be output before the character zero. This behavior is considered a bug; it is unlikely that any currently conforming application relies on:

echo 'b[3]' | bc

returning 00000 rather than 0.

Exact calculation of the number of fractional digits to output for a given value in a base other than 10 can be computationally expensive. Historical implementations use a faster approximation, and this is permitted. Note that the requirements apply only to values of obase that this volume of IEEE Std 1003.1-2001 requires implementations to support (in particular, not to 1, 0, or negative bases, if an implementation supports them as an extension).

Historical implementations of bc did not allow array parameters to be passed as the last parameter to a function. New implementations are encouraged to remove this restriction even though it is not required by the grammar.

FUTURE DIRECTIONS

None.

SEE ALSO

Grammar Conventions , awk

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


bg(1p)

BG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bg - run jobs in the background

SYNOPSIS

bg [job_id ...]

DESCRIPTION

If job control is enabled (see the description of set -m), the bg utility shall resume suspended jobs from the current environment (see Shell Execution Environment ) by running them as background jobs. If the job specified by job_id is already a running background job, the bg utility shall have no effect and shall exit successfully.

Using bg to place a job into the background shall cause its process ID to become "known in the current shell execution environment", as if it had been started as an asynchronous list; see Asynchronous Lists .

OPTIONS

None.

OPERANDS

The following operand shall be supported:

job_id
Specify the job to be resumed as a background job. If no job_id operand is given, the most recently suspended job shall be used. The format of job_id is described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.203, Job Control Job ID.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of bg:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The output of bg shall consist of a line in the format:

"[%d] %s\n", <job-number>, <command>

where the fields are as follows:

<job-number>
A number that can be used to identify the job to the wait, fg, and kill utilities. Using these utilities, the job can be identified by prefixing the job number with '%' .
<command>
The associated command that was given to the shell.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If job control is disabled, the bg utility shall exit with an error and no job shall be placed in the background.

The following sections are informative.

APPLICATION USAGE

A job is generally suspended by typing the SUSP character (<control>-Z on most systems); see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface. At that point, bg can put the job into the background. This is most effective when the job is expecting no terminal input and its output has been redirected to non-terminal files. A background job can be forced to stop when it has terminal output by issuing the command:

stty tostop

A background job can be stopped with the command:

kill -s stop job ID

The bg utility does not work as expected when it is operating in its own utility execution environment because that environment has no suspended jobs. In the following examples:

... | xargs bg
(bg)

each bg operates in a different environment and does not share its parent shell's understanding of jobs. For this reason, bg is generally implemented as a shell regular built-in.

EXAMPLES

None.

RATIONALE

The extensions to the shell specified in this volume of IEEE Std 1003.1-2001 have mostly been based on features provided by the KornShell. The job control features provided by bg, fg, and jobs are also based on the KornShell. The standard developers examined the characteristics of the C shell versions of these utilities and found that differences exist. Despite widespread use of the C shell, the KornShell versions were selected for this volume of IEEE Std 1003.1-2001 to maintain a degree of uniformity with the rest of the KornShell features selected (such as the very popular command line editing features).

The bg utility is expected to wrap its output if the output exceeds the number of display columns.

FUTURE DIRECTIONS

None.

SEE ALSO

Asynchronous Lists , fg , kill() , jobs , wait()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ar(1p)

AR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ar - create and maintain library archives

SYNOPSIS

ar -d[-v] archive file ...

ar -m [-v] archive file ...

ar -m -a[-v] posname archive file ...

ar -m -b[-v] posname archive file ...

ar -m -i[-v] posname archive file ...

ar -p[-v][-s]archive [file ...]

ar -q[-cv] archive file ...

ar -r[-cuv] archive file ...

ar -r -a[-cuv] posname archive file ...

ar -r -b[-cuv] posname archive file ...

ar -r -i[-cuv] posname archive file ...

ar -t[-v][-s]archive [file ...]

ar -x[-v][-sCT]archive [file ...]

DESCRIPTION

The ar utility is part of the Software Development Utilities option.

The ar utility can be used to create and maintain groups of files combined into an archive. Once an archive has been created, new files can be added, and existing files in an archive can be extracted, deleted, or replaced. When an archive consists entirely of valid object files, the implementation shall format the archive so that it is usable as a library for link editing (see c99 and fort77). When some of the archived files are not valid object files, the suitability of the archive for library use is undefined. If an archive consists entirely of printable files, the entire archive shall be printable.

When ar creates an archive, it creates administrative information indicating whether a symbol table is present in the archive. When there is at least one object file that ar recognizes as such in the archive, an archive symbol table shall be created in the archive and maintained by ar; it is used by the link editor to search the archive. Whenever the ar utility is used to create or update the contents of such an archive, the symbol table shall be rebuilt. The -s option shall force the symbol table to be rebuilt.

All file operands can be pathnames. However, files within archives shall be named by a filename, which is the last component of the pathname used when the file was entered into the archive. The comparison of file operands to the names of files in archives shall be performed by comparing the last component of the operand to the name of the file in the archive.

It is unspecified whether multiple files in the archive may be identically named. In the case of such files, however, each file and posname operand shall match only the first file in the archive having a name that is the same as the last component of the operand.

OPTIONS

The ar utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Position new files in the archive after the file named by the posname operand.
-b
Position new files in the archive before the file named by the posname operand.
-c
Suppress the diagnostic message that is written to standard error by default when the archive archive is created.
-C
Prevent extracted files from replacing like-named files in the file system. This option is useful when -T is also used, to prevent truncated filenames from replacing files with the same prefix.
-d
Delete one or more files from archive.
-i
Position new files in the archive before the file in the archive named by the posname operand (equivalent to -b).
-m
Move the named files in the archive. The -a, -b, or -i options with the posname operand indicate the position; otherwise, move the names files in the archive to the end of the archive.
-p
Write the contents of the files in the archive named by file operands from archive to the standard output. If no file operands are specified, the contents of all files in the archive shall be written in the order of the archive.
-q
Append the named files to the end of the archive. In this case ar does not check whether the added files are already in the archive. This is useful to bypass the searching otherwise done when creating a large archive piece by piece.
-r
Replace or add files to archive. If the archive named by archive does not exist, a new archive shall be created and a diagnostic message shall be written to standard error (unless the -c option is specified). If no files are specified and the archive exists, the results are undefined. Files that replace existing files in the archive shall not change the order of the archive. Files that do not replace existing files in the archive shall be appended to the archive unless a -a, -b, or -i option specifies another position.
-s
Force the regeneration of the archive symbol table even if ar is not invoked with an option that modifies the archive contents. This option is useful to restore the archive symbol table after it has been stripped; see strip.
-t
Write a table of contents of archive to the standard output. The files specified by the file operands shall be included in the written list. If no file operands are specified, all files in archive shall be included in the order of the archive.
-T
Allow filename truncation of extracted files whose archive names are longer than the file system can support. By default, extracting a file with a name that is too long shall be an error; a diagnostic message shall be written and the file shall not be extracted.
-u
Update older files in the archive. When used with the -r option, files in the archive shall be replaced only if the corresponding file has a modification time that is at least as new as the modification time of the file in the archive.
-v
Give verbose output. When used with the option characters -d, -r, or -x, write a detailed file-by-file description of the archive creation and maintenance activity, as described in the STDOUT section.

When used with -p, write the name of the file in the archive to the standard output before writing the file in the archive itself to the standard output, as described in the STDOUT section.

When used with -t, include a long listing of information about the files in the archive, as described in the STDOUT section.

-x
Extract the files in the archive named by the file operands from archive. The contents of the archive shall not be changed. If no file operands are given, all files in the archive shall be extracted. The modification time of each file extracted shall be set to the time the file is extracted from the archive.

OPERANDS

The following operands shall be supported:

archive
A pathname of the archive.
file
A pathname. Only the last component shall be used when comparing against the names of files in the archive. If two or more file operands have the same last pathname component (basename), the results are unspecified. The implementation's archive format shall not truncate valid filenames of files added to or replaced in the archive.
posname
The name of a file in the archive, used for relative positioning; see options -m and -r.

STDIN

Not used.

INPUT FILES

The archive named by archive shall be a file in the format created by ar -r.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ar:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_TIME
Determine the format and content for date and time strings written by ar -tv.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TMPDIR
Determine the pathname that overrides the default directory for temporary files, if any.
TZ
Determine the timezone used to calculate date and time strings written by ar -tv. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If the -d option is used with the -v option, the standard output format shall be:

"d - %s\n", <file>

where file is the operand specified on the command line.

If the -p option is used with the -v option, ar shall precede the contents of each file with:

"\n<%s>\n\n", <file>

where file is the operand specified on the command line, if file operands were specified, and the name of the file in the archive if they were not.

If the -r option is used with the -v option:

*
If file is already in the archive, the standard output format shall be:

"r - %s\n", <file>

where <file> is the operand specified on the command line.

*
If file is not already in the archive, the standard output format shall be:

"a - %s\n", <file>

where <file> is the operand specified on the command line.

If the -t option is used, ar shall write the names of the files in the archive to the standard output in the format:

"%s\n", <file>

where file is the operand specified on the command line, if file operands were specified, or the name of the file in the archive if they were not.

If the -t option is used with the -v option, the standard output format shall be:

"%s %u/%u %u %s %d %d:%d %d %s\n", <member mode>, <user ID>,
    <group ID>, <number of bytes in member>,
    <abbreviated month>, <day-of-month>, <hour>,
    <minute>, <year>, <file>

where:

<file>
Shall be the operand specified on the command line, if file operands were specified, or the name of the file in the archive if they were not.
<member mode>

Shall be formatted the same as the <file mode> string defined in the STDOUT section of ls, except that the first character, the <entry type>, is not used; the string represents the file mode of the file in the archive at the time it was added to or replaced in the archive.

The following represent the last-modification time of a file when it was most recently added to or replaced in the archive:

<abbreviated month>

Equivalent to the format of the %b conversion specification format in date.

<day-of-month>

Equivalent to the format of the %e conversion specification format in date.

<hour>
Equivalent to the format of the %H conversion specification format in date.
<minute>
Equivalent to the format of the %M conversion specification format in date.
<year>
Equivalent to the format of the %Y conversion specification format in date.

When LC_TIME does not specify the POSIX locale, a different format and order of presentation of these fields relative to each other may be used in a format appropriate in the specified locale.

If the -x option is used with the -v option, the standard output format shall be:

"x - %s\n", <file>

where file is the operand specified on the command line, if file operands were specified, or the name of the file in the archive if they were not.

STDERR

The standard error shall be used only for diagnostic messages. The diagnostic message about creating a new archive when -c is not specified shall not modify the exit status.

OUTPUT FILES

Archives are files with unspecified formats.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The archive format is not described. It is recognized that there are several known ar formats, which are not compatible. The ar utility is included, however, to allow creation of archives that are intended for use only on one machine. The archive is specified as a file, and it can be moved as a file. This does allow an archive to be moved from one machine to another machine that uses the same implementation of ar.

Utilities such as pax (and its forebears tar and cpio) also provide portable "archives". This is a not a duplication; the ar utility is included to provide an interface primarily for make and the compilers, based on a historical model.

In historical implementations, the -q option (available on XSI-conforming systems) is known to execute quickly because ar does not check on whether the added members are already in the archive. This is useful to bypass the searching otherwise done when creating a large archive piece-by-piece. These remarks may but need not remain true for a brand new implementation of this utility; hence, these remarks have been moved into the RATIONALE.

BSD implementations historically required applications to provide the -s option whenever the archive was supposed to contain a symbol table. As in this volume of IEEE Std 1003.1-2001, System V historically creates or updates an archive symbol table whenever an object file is removed from, added to, or updated in the archive.

The OPERANDS section requires what might seem to be true without specifying it: the archive cannot truncate the filenames below {NAME_MAX}. Some historical implementations do so, however, causing unexpected results for the application. Therefore, this volume of IEEE Std 1003.1-2001 makes the requirement explicit to avoid misunderstandings.

According to the System V documentation, the options -dmpqrtx are not required to begin with a hyphen ( '-' ). This volume of IEEE Std 1003.1-2001 requires that a conforming application use the leading hyphen.

The archive format used by the 4.4 BSD implementation is documented in this RATIONALE as an example: A file created by ar begins with the "magic" string "!<arch>\n" . The rest of the archive is made up of objects, each of which is composed of a header for a file, a possible filename, and the file contents. The header is portable between machine architectures, and, if the file contents are printable, the archive is itself printable.

The header is made up of six ASCII fields, followed by a two-character trailer. The fields are the object name (16 characters), the file last modification time (12 characters), the user and group IDs (each 6 characters), the file mode (8 characters), and the file size (10 characters). All numeric fields are in decimal, except for the file mode, which is in octal.

The modification time is the file st_mtime field. The user and group IDs are the file st_uid and st_gid fields. The file mode is the file st_mode field. The file size is the file st_size field. The two-byte trailer is the string "`<newline>" .

Only the name field has any provision for overflow. If any filename is more than 16 characters in length or contains an embedded space, the string "#1/" followed by the ASCII length of the name is written in the name field. The file size (stored in the archive header) is incremented by the length of the name. The name is then written immediately following the archive header.

Any unused characters in any of these fields are written as <space>s. If any fields are their particular maximum number of characters in length, there is no separation between the fields.

Objects in the archive are always an even number of bytes long; files that are an odd number of bytes long are padded with a <newline>, although the size in the header does not reflect this.

The ar utility description requires that (when all its members are valid object files) ar produce an object code library, which the linkage editor can use to extract object modules. If the linkage editor needs a symbol table to permit random access to the archive, ar must provide it; however, ar does not require a symbol table.

The BSD -o option was omitted. It is a rare conforming application that uses ar to extract object code from a library with concern for its modification time, since this can only be of importance to make. Hence, since this functionality is not deemed important for applications portability, the modification time of the extracted files is set to the current time.

There is at least one known implementation (for a small computer) that can accommodate only object files for that system, disallowing mixed object and other files. The ability to handle any type of file is not only historical practice for most implementations, but is also a reasonable expectation.

Consideration was given to changing the output format of ar -tv to the same format as the output of ls -l. This would have made parsing the output of ar the same as that of ls. This was rejected in part because the current ar format is commonly used and changes would break historical usage. Second, ar gives the user ID and group ID in numeric format separated by a slash. Changing this to be the user name and group name would not be correct if the archive were moved to a machine that contained a different user database. Since ar cannot know whether the archive was generated on the same machine, it cannot tell what to report.

The text on the -ur option combination is historical practice-since one filename can easily represent two different files (for example, /a/foo and /b/foo), it is reasonable to replace the file in the archive even when the modification time in the archive is identical to that in the file system.

FUTURE DIRECTIONS

None.

SEE ALSO

c99 , date , fort77 , pax , strip the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers, <unistd.h> description of {POSIX_NO_TRUNC}

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


at(1p)

AT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

at - execute commands at a later time

SYNOPSIS

at [-m][-f file][-q queuename] -t time_arg

at [-m][-f file][-q queuename] timespec ...

at -r at_job_id ...

at -l -q queuename

at -l [at_job_id ...]

DESCRIPTION

The at utility shall read commands from standard input and group them together as an at-job, to be executed at a later time.

The at-job shall be executed in a separate invocation of the shell, running in a separate process group with no controlling terminal, except that the environment variables, current working directory, file creation mask, and other implementation-defined execution-time attributes in effect when the at utility is executed shall be retained and used when the at-job is executed.

When the at-job is submitted, the at_job_id and scheduled time shall be written to standard error. The at_job_id is an identifier that shall be a string consisting solely of alphanumeric characters and the period character. The at_job_id shall be assigned by the system when the job is scheduled such that it uniquely identifies a particular job.

User notification and the processing of the job's standard output and standard error are described under the -m option.

Users shall be permitted to use at if their name appears in the file /usr/lib/cron/at.allow. If that file does not exist, the file /usr/lib/cron/at.deny shall be checked to determine whether the user shall be denied access to at. If neither file exists, only a process with the appropriate privileges shall be allowed to submit a job. If only at.deny exists and is empty, global usage shall be permitted. The at.allow and at.deny files shall consist of one user name per line.

OPTIONS

The at utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-f file
Specify the pathname of a file to be used as the source of the at-job, instead of standard input.
-l
(The letter ell.) Report all jobs scheduled for the invoking user if no at_job_id operands are specified. If at_job_ids are specified, report only information for these jobs. The output shall be written to standard output.
-m
Send mail to the invoking user after the at-job has run, announcing its completion. Standard output and standard error produced by the at-job shall be mailed to the user as well, unless redirected elsewhere. Mail shall be sent even if the job produces no output.

If -m is not used, the job's standard output and standard error shall be provided to the user by means of mail, unless they are redirected elsewhere; if there is no such output to provide, the implementation need not notify the user of the job's completion.

-q queuename

Specify in which queue to schedule a job for submission. When used with the -l option, limit the search to that particular queue. By default, at-jobs shall be scheduled in queue a. In contrast, queue b shall be reserved for batch jobs; see batch. The meanings of all other queuenames are implementation-defined. If -q is specified along with either of the -t time_arg or timespec arguments, the results are unspecified.

-r
Remove the jobs with the specified at_job_id operands that were previously scheduled by the at utility.
-t time_arg
Submit the job to be run at the time specified by the time option-argument, which the application shall ensure has the format as specified by the touch -t time utility.

OPERANDS

The following operands shall be supported:

at_job_id
The name reported by a previous invocation of the at utility at the time the job was scheduled.
timespec
Submit the job to be run at the date and time specified. All of the timespec operands are interpreted as if they were separated by <space>s and concatenated, and shall be parsed as described in the grammar at the end of this section. The date and time shall be interpreted as being in the timezone of the user (as determined by the TZ variable), unless a timezone name appears as part of time, below.

In the POSIX locale, the following describes the three parts of the time specification string. All of the values from the LC_TIME categories in the POSIX locale shall be recognized in a case-insensitive manner.

time
The time can be specified as one, two, or four digits. One-digit and two-digit numbers shall be taken to be hours; four-digit numbers to be hours and minutes. The time can alternatively be specified as two numbers separated by a colon, meaning hour:minute. An AM/PM indication (one of the values from the am_pm keywords in the LC_TIME locale category) can follow the time; otherwise, a 24-hour clock time shall be understood. A timezone name can also follow to further qualify the time. The acceptable timezone names are implementation-defined, except that they shall be case-insensitive and the string utc is supported to indicate the time is in Coordinated Universal Time. In the POSIX locale, the time field can also be one of the following tokens:
midnight
Indicates the time 12:00 am (00:00).
noon
Indicates the time 12:00 pm.
now
Indicates the current day and time. Invoking at <now> shall submit an at-job for potentially immediate execution (that is, subject only to unspecified scheduling delays).

date
An optional date can be specified as either a month name (one of the values from the mon or abmon keywords in the LC_TIME locale category) followed by a day number (and possibly year number preceded by a comma), or a day of the week (one of the values from the day or abday keywords in the LC_TIME locale category). In the POSIX locale, two special days shall be recognized:
today
Indicates the current day.
tomorrow
Indicates the day following the current day.

If no date is given, today shall be assumed if the given time is greater than the current time, and tomorrow shall be assumed if it is less. If the given month is less than the current month (and no year is given), next year shall be assumed.

increment
The optional increment shall be a number preceded by a plus sign ( '+' ) and suffixed by one of the following: minutes, hours, days, weeks, months, or years. (The singular forms shall also be accepted.) The keyword next shall be equivalent to an increment number of +1. For example, the following are equivalent commands:

at 2pm + 1 week
at 2pm next week

The following grammar describes the precise format of timespec in the POSIX locale. The general conventions for this style of grammar are described in Grammar Conventions . This formal syntax shall take precedence over the preceding text syntax description. The longest possible token or delimiter shall be recognized at a given point. When used in a timespec, white space shall also delimit tokens.

%token hr24clock_hr_min
%token hr24clock_hour
/*
  An hr24clock_hr_min is a one, two, or four-digit number. A one-digit
  or two-digit number constitutes an hr24clock_hour. An hr24clock_hour
  may be any of the single digits [0,9], or may be double digits, ranging
  from [00,23]. If an hr24clock_hr_min is a four-digit number, the
  first two digits shall be a valid hr24clock_hour, while the last two
  represent the number of minutes, from [00,59].
*/

%token wallclock_hr_min
%token wallclock_hour
/*
  A wallclock_hr_min is a one, two-digit, or four-digit number.
  A one-digit or two-digit number constitutes a wallclock_hour.
  A wallclock_hour may be any of the single digits [1,9], or may
  be double digits, ranging from [01,12]. If a wallclock_hr_min
  is a four-digit number, the first two digits shall be a valid
  wallclock_hour, while the last two represent the number of
  minutes, from [00,59].
*/

%token minute
/*
  A minute is a one or two-digit number whose value can be [0,9]
  or [00,59].
*/

%token day_number
/*
  A day_number is a number in the range appropriate for the particular
  month and year specified by month_name and year_number, respectively.
  If no year_number is given, the current year is assumed if the given
  date and time are later this year. If no year_number is given and
  the date and time have already occurred this year and the month is
  not the current month, next year is the assumed year.
*/

%token year_number
/*
  A year_number is a four-digit number representing the year A.D., in
  which the at_job is to be run.
*/

%token inc_number
/*
  The inc_number is the number of times the succeeding increment
  period is to be added to the specified date and time.
*/

%token timezone_name
/*
  The name of an optional timezone suffix to the time field, in an
  implementation-defined format.
*/

%token month_name
/*
  One of the values from the mon or abmon keywords in the LC_TIME
  locale category.
*/

%token day_of_week
/*
  One of the values from the day or abday keywords in the LC_TIME
  locale category.
*/

%token am_pm
/*
  One of the values from the am_pm keyword in the LC_TIME locale
  category.
*/

%start timespec
%%
timespec    : time
            | time date
            | time increment
            | time date increment
            | nowspec
            ;

nowspec     : "now"
            | "now" increment
            ;

time        : hr24clock_hr_min
            | hr24clock_hr_min timezone_name
            | hr24clock_hour ":" minute
            | hr24clock_hour ":" minute timezone_name
            | wallclock_hr_min am_pm
            | wallclock_hr_min am_pm timezone_name
            | wallclock_hour ":" minute am_pm
            | wallclock_hour ":" minute am_pm timezone_name
            | "noon"
            | "midnight"
            ;

date        : month_name day_number
            | month_name day_number "," year_number
            | day_of_week
            | "today"
            | "tomorrow"
            ;

increment   : "+" inc_number inc_period
            | "next" inc_period
            ;

inc_period  : "minute" | "minutes"
            | "hour" | "hours"
            | "day" | "days"
            | "week" | "weeks"
            | "month" | "months"
            | "year" | "years"
            ;

STDIN

The standard input shall be a text file consisting of commands acceptable to the shell command language described in Shell Command Language . The standard input shall only be used if no -f file option is specified.

INPUT FILES

See the STDIN section.

The text files /usr/lib/cron/at.allow and /usr/lib/cron/at.deny shall contain zero or more user names, one per line, of users who are, respectively, authorized or denied access to the at and batch utilities.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of at:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
LC_TIME
Determine the format and contents for date and time strings written and accepted by at.
SHELL
Determine a name of a command interpreter to be used to invoke the at-job. If the variable is unset or null, sh shall be used. If it is set to a value other than a name for sh, the implementation shall do one of the following: use that shell; use sh; use the login shell from the user database; or any of the preceding accompanied by a warning diagnostic about which was chosen.
TZ
Determine the timezone. The job shall be submitted for execution at the time specified by timespec or -t time relative to the timezone specified by the TZ variable. If timespec specifies a timezone, it shall override TZ . If timespec does not specify a timezone and TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

When standard input is a terminal, prompts of unspecified format for each line of the user input described in the STDIN section may be written to standard output.

In the POSIX locale, the following shall be written to the standard output for each job when jobs are listed in response to the -l option:

"%s\t%s\n", at_job_id, <date>

where date shall be equivalent in format to the output of:

date +"%a %b %e %T %Y"

The date and time written shall be adjusted so that they appear in the timezone of the user (as determined by the TZ variable).

STDERR

In the POSIX locale, the following shall be written to standard error when a job has been successfully submitted:

"job %s at %s\n", at_job_id, <date>

where date has the same format as that described in the STDOUT section. Neither this, nor warning messages concerning the selection of the command interpreter, shall be considered a diagnostic that changes the exit status.

Diagnostic messages, if any, shall be written to standard error.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The at utility successfully submitted, removed, or listed a job or jobs.
>0
An error occurred.

CONSEQUENCES OF ERRORS

The job shall not be scheduled, removed, or listed.

The following sections are informative.

APPLICATION USAGE

The format of the at command line shown here is guaranteed only for the POSIX locale. Other cultures may be supported with substantially different interfaces, although implementations are encouraged to provide comparable levels of functionality.

Since the commands run in a separate shell invocation, running in a separate process group with no controlling terminal, open file descriptors, traps, and priority inherited from the invoking environment are lost.

Some implementations do not allow substitution of different shells using SHELL . System V systems, for example, have used the login shell value for the user in /etc/passwd. To select reliably another command interpreter, the user must include it as part of the script, such as:

$ at 1800
myshell myscript
EOT
job ... at ...
$

EXAMPLES

1.
This sequence can be used at a terminal:

at -m 0730 tomorrow
sort < file >outfile
EOT

2.
This sequence, which demonstrates redirecting standard error to a pipe, is useful in a command procedure (the sequence of output redirection specifications is significant):

at now + 1 hour <<!
diff file1 file2 2>&1 >outfile | mailx mygroup
!

3.
To have a job reschedule itself, at can be invoked from within the at-job. For example, this daily processing script named my.daily runs every day (although crontab is a more appropriate vehicle for such work):

# my.daily runs every day
daily processingat now tomorrow < my.daily

4.
The spacing of the three portions of the POSIX locale timespec is quite flexible as long as there are no ambiguities. Examples of various times and operand presentation include:

at 0815am Jan 24
at 8 :15amjan24
at now "+ 1day"
at 5 pm FRIday
at '17
    utc+
    30minutes'

RATIONALE

The at utility reads from standard input the commands to be executed at a later time. It may be useful to redirect standard output and standard error within the specified commands.

The -t time option was added as a new capability to support an internationalized way of specifying a time for execution of the submitted job.

Early proposals added a "jobname" concept as a way of giving submitted jobs names that are meaningful to the user submitting them. The historical, system-specified at_job_id gives no indication of what the job is. Upon further reflection, it was decided that the benefit of this was not worth the change in historical interface. The at functionality is useful in simple environments, but in large or complex situations, the functionality provided by the Batch Services option is more suitable.

The -q option historically has been an undocumented option, used mainly by the batch utility.

The System V -m option was added to provide a method for informing users that an at-job had completed. Otherwise, users are only informed when output to standard error or standard output are not redirected.

The behavior of at <now> was changed in an early proposal from being unspecified to submitting a job for potentially immediate execution. Historical BSD at implementations support this. Historical System V implementations give an error in that case, but a change to the System V versions should have no backwards-compatibility ramifications.

On BSD-based systems, a -u user option has allowed those with appropriate privileges to access the work of other users. Since this is primarily a system administration feature and is not universally implemented, it has been omitted. Similarly, a specification for the output format for a user with appropriate privileges viewing the queues of other users has been omitted.

The -f file option from System V is used instead of the BSD method of using the last operand as the pathname. The BSD method is ambiguous-does:

at 1200 friday

mean the same thing if there is a file named friday in the current directory?

The at_job_id is composed of a limited character set in historical practice, and it is mandated here to invalidate systems that might try using characters that require shell quoting or that could not be easily parsed by shell scripts.

The at utility varies between System V and BSD systems in the way timezones are used. On System V systems, the TZ variable affects the at-job submission times and the times displayed for the user. On BSD systems, TZ is not taken into account. The BSD behavior is easily achieved with the current specification. If the user wishes to have the timezone default to that of the system, they merely need to issue the at command immediately following an unsetting or null assignment to TZ . For example:

TZ= at noon ...

gives the desired BSD result.

While the yacc-like grammar specified in the OPERANDS section is lexically unambiguous with respect to the digit strings, a lexical analyzer would probably be written to look for and return digit strings in those cases. The parser could then check whether the digit string returned is a valid day_number, year_number, and so on, based on the context.

FUTURE DIRECTIONS

None.

SEE ALSO

batch , crontab

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cd(1p)

CD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cd - change the working directory

SYNOPSIS

cd [-L | -P] [directory]

cd -

DESCRIPTION

The cd utility shall change the working directory of the current shell execution environment (see Shell Execution Environment ) by executing the following steps in sequence. (In the following steps, the symbol curpath represents an intermediate value used to simplify the description of the algorithm used by cd. There is no requirement that curpath be made visible to the application.)

1.
If no directory operand is given and the HOME environment variable is empty or undefined, the default behavior is implementation-defined and no further steps shall be taken.

2.
If no directory operand is given and the HOME environment variable is set to a non-empty value, the cd utility shall behave as if the directory named in the HOME environment variable was specified as the directory operand.

3.
If the directory operand begins with a slash character, set curpath to the operand and proceed to step 7.

4.
If the first component of the directory operand is dot or dot-dot, proceed to step 6.

5.
Starting with the first pathname in the colon-separated pathnames of CDPATH (see the ENVIRONMENT VARIABLES section) if the pathname is non-null, test if the concatenation of that pathname, a slash character, and the directory operand names a directory. If the pathname is null, test if the concatenation of dot, a slash character, and the operand names a directory. In either case, if the resulting string names an existing directory, set curpath to that string and proceed to step 7. Otherwise, repeat this step with the next pathname in CDPATH until all pathnames have been tested.

6.
Set curpath to the string formed by the concatenation of the value of PWD , a slash character, and the operand.

7.
If the -P option is in effect, the cd utility shall perform actions equivalent to the chdir() function, called with curpath as the path argument. If these actions succeed, the PWD environment variable shall be set to an absolute pathname for the current working directory and shall not contain filename components that, in the context of pathname resolution, refer to a file of type symbolic link. If there is insufficient permission on the new directory, or on any parent of that directory, to determine the current working directory, the value of the PWD environment variable is unspecified. If the actions equivalent to chdir() fail for any reason, the cd utility shall display an appropriate error message and not alter the PWD environment variable. Whether the actions equivalent to chdir() succeed or fail, no further steps shall be taken.

8.
The curpath value shall then be converted to canonical form as follows, considering each component from beginning to end, in sequence:
a.
Dot components and any slashes that separate them from the next component shall be deleted.

b.
For each dot-dot component, if there is a preceding component and it is neither root nor dot-dot, the preceding component, all slashes separating the preceding component from dot-dot, dot-dot and all slashes separating dot-dot from the following component shall be deleted.

c.
An implementation may further simplify curpath by removing any trailing slash characters that are not also leading slashes, replacing multiple non-leading consecutive slashes with a single slash, and replacing three or more leading slashes with a single slash. If, as a result of this canonicalization, the curpath variable is null, no further steps shall be taken.

9.
The cd utility shall then perform actions equivalent to the chdir() function called with curpath as the path argument. If these actions failed for any reason, the cd utility shall display an appropriate error message and no further steps shall be taken. The PWD environment variable shall be set to curpath.

If, during the execution of the above steps, the PWD environment variable is changed, the OLDPWD environment variable shall also be changed to the value of the old working directory (that is the current working directory immediately prior to the call to cd).

OPTIONS

The cd utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-L
Handle the operand dot-dot logically; symbolic link components shall not be resolved before dot-dot components are processed (see steps 8. and 9. in the DESCRIPTION).
-P
Handle the operand dot-dot physically; symbolic link components shall be resolved before dot-dot components are processed (see step 7. in the DESCRIPTION).

If both -L and -P options are specified, the last of these options shall be used and all others ignored. If neither -L nor -P is specified, the operand shall be handled dot-dot logically; see the DESCRIPTION.

OPERANDS

The following operands shall be supported:

directory
An absolute or relative pathname of the directory that shall become the new working directory. The interpretation of a relative pathname by cd depends on the -L option and the CDPATH and PWD environment variables. If directory is an empty string, the results are unspecified.
-
When a hyphen is used as the operand, this shall be equivalent to the command:

cd "$OLDPWD" && pwd

which changes to the previous working directory and then writes its name.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cd:

CDPATH
A colon-separated list of pathnames that refer to directories. The cd utility shall use this list in its attempt to change the directory, as described in the DESCRIPTION. An empty string in place of a directory pathname represents the current directory. If CDPATH is not set, it shall be treated as if it were an empty string.
HOME
The name of the directory, used when no directory operand is specified.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
OLDPWD
A pathname of the previous working directory, used by cd -.
PWD
This variable shall be set as specified in the DESCRIPTION. If an application sets or unsets the value of PWD , the behavior of cd is unspecified.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If a non-empty directory name from CDPATH is used, or if cd - is used, an absolute pathname of the new working directory shall be written to the standard output as follows:

"%s\n", <new directory>

Otherwise, there shall be no output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The directory was successfully changed.
>0
An error occurred.

CONSEQUENCES OF ERRORS

The working directory shall remain unchanged.

The following sections are informative.

APPLICATION USAGE

Since cd affects the current shell execution environment, it is always provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:

(cd /tmp)
nohup cd
find . -exec cd {} \;

it does not affect the working directory of the caller's environment.

The user must have execute (search) permission in directory in order to change to it.

EXAMPLES

None.

RATIONALE

The use of the CDPATH was introduced in the System V shell. Its use is analogous to the use of the PATH variable in the shell. The BSD C shell used a shell parameter cdpath for this purpose.

A common extension when HOME is undefined is to get the login directory from the user database for the invoking user. This does not occur on System V implementations.

Some historical shells, such as the KornShell, took special actions when the directory name contained a dot-dot component, selecting the logical parent of the directory, rather than the actual parent directory; that is, it moved up one level toward the '/' in the pathname, remembering what the user typed, rather than performing the equivalent of:

chdir("..");

In such a shell, the following commands would not necessarily produce equivalent output for all directories:

cd .. && ls      ls ..

This behavior is now the default. It is not consistent with the definition of dot-dot in most historical practice; that is, while this behavior has been optionally available in the KornShell, other shells have historically not supported this functionality. The logical pathname is stored in the PWD environment variable when the cd utility completes and this value is used to construct the next directory name if cd is invoked with the -L option.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Execution Environment , pwd , the System Interfaces volume of IEEE Std 1003.1-2001, chdir()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dd(1p)

DD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dd - convert and copy a file

SYNOPSIS

dd [operand ...]

DESCRIPTION

The dd utility shall copy the specified input file to the specified output file with possible conversions using specific input and output block sizes. It shall read the input one block at a time, using the specified input block size; it shall then process the block of data actually returned, which could be smaller than the requested block size. It shall apply any conversions that have been specified and write the resulting data to the output in blocks of the specified output block size. If the bs= expr operand is specified and no conversions other than sync, noerror, or notrunc are requested, the data returned from each input block shall be written as a separate output block; if the read returns less than a full block and the sync conversion is not specified, the resulting output block shall be the same size as the input block. If the bs= expr operand is not specified, or a conversion other than sync, noerror, or notrunc is requested, the input shall be processed and collected into full-sized output blocks until the end of the input is reached.

The processing order shall be as follows:

1.
An input block is read.

2.
If the input block is shorter than the specified input block size and the sync conversion is specified, null bytes shall be appended to the input data up to the specified size. (If either block or unblock is also specified, <space>s shall be appended instead of null bytes.) The remaining conversions and output shall include the pad characters as if they had been read from the input.

3.
If the bs= expr operand is specified and no conversion other than sync or noerror is requested, the resulting data shall be written to the output as a single block, and the remaining steps are omitted.

4.
If the swab conversion is specified, each pair of input data bytes shall be swapped. If there is an odd number of bytes in the input block, the last byte in the input record shall not be swapped.

5.
Any remaining conversions ( block, unblock, lcase, and ucase) shall be performed. These conversions shall operate on the input data independently of the input blocking; an input or output fixed-length record may span block boundaries.

6.
The data resulting from input or conversion or both shall be aggregated into output blocks of the specified size. After the end of input is reached, any remaining output shall be written as a block without padding if conv= sync is not specified; thus, the final output block may be shorter than the output block size.

OPTIONS

None.

OPERANDS

All of the operands shall be processed before any input is read. The following operands shall be supported:

if=file
Specify the input pathname; the default is standard input.
of=file
Specify the output pathname; the default is standard output. If the seek= expr conversion is not also specified, the output file shall be truncated before the copy begins if an explicit of= file operand is specified, unless conv= notrunc is specified. If seek= expr is specified, but conv= notrunc is not, the effect of the copy shall be to preserve the blocks in the output file over which dd seeks, but no other portion of the output file shall be preserved. (If the size of the seek plus the size of the input file is less than the previous size of the output file, the output file shall be shortened by the copy.)
ibs=expr
Specify the input block size, in bytes, by expr (default is 512).
obs=expr
Specify the output block size, in bytes, by expr (default is 512).
bs=expr
Set both input and output block sizes to expr bytes, superseding ibs= and obs=. If no conversion other than sync, noerror, and notrunc is specified, each input block shall be copied to the output as a single block without aggregating short blocks.
cbs=expr
Specify the conversion block size for block and unblock in bytes by expr (default is zero). If cbs= is omitted or given a value of zero, using block or unblock produces unspecified results.

The application shall ensure that this operand is also specified if the conv= operand is specified with a value of ascii, ebcdic, or ibm. For a conv= operand with an ascii value, the input is handled as described for the unblock value, except that characters are converted to ASCII before any trailing <space>s are deleted. For conv= operands with ebcdic or ibm values, the input is handled as described for the block value except that the characters are converted to EBCDIC or IBM EBCDIC, respectively, after any trailing <space>s are added.

skip=n
Skip n input blocks (using the specified input block size) before starting to copy. On seekable files, the implementation shall read the blocks or seek past them; on non-seekable files, the blocks shall be read and the data shall be discarded.
seek=n
Skip n blocks (using the specified output block size) from the beginning of the output file before copying. On non-seekable files, existing blocks shall be read and space from the current end-of-file to the specified offset, if any, filled with null bytes; on seekable files, the implementation shall seek to the specified offset or read the blocks as described for non-seekable files.
count=n
Copy only n input blocks.
conv=value[,value ...]

Where values are comma-separated symbols from the following list:

ascii
Convert EBCDIC to ASCII; see ASCII to EBCDIC Conversion .
ebcdic
Convert ASCII to EBCDIC; see ASCII to EBCDIC Conversion .
ibm
Convert ASCII to a different EBCDIC set; see ASCII to IBM EBCDIC Conversion .

The ascii, ebcdic, and ibm values are mutually-exclusive.

block
Treat the input as a sequence of <newline>-terminated or end-of-file-terminated variable-length records independent of the input block boundaries. Each record shall be converted to a record with a fixed length specified by the conversion block size. Any <newline> shall be removed from the input line; <space>s shall be appended to lines that are shorter than their conversion block size to fill the block. Lines that are longer than the conversion block size shall be truncated to the largest number of characters that fit into that size; the number of truncated lines shall be reported (see the STDERR section).

The block and unblock values are mutually-exclusive.

unblock
Convert fixed-length records to variable length. Read a number of bytes equal to the conversion block size (or the number of bytes remaining in the input, if less than the conversion block size), delete all trailing <space>s, and append a <newline>.
lcase
Map uppercase characters specified by the LC_CTYPE keyword tolower to the corresponding lowercase character. Characters for which no mapping is specified shall not be modified by this conversion.

The lcase and ucase symbols are mutually-exclusive.

ucase
Map lowercase characters specified by the LC_CTYPE keyword toupper to the corresponding uppercase character. Characters for which no mapping is specified shall not be modified by this conversion.
swab
Swap every pair of input bytes.
noerror
Do not stop processing on an input error. When an input error occurs, a diagnostic message shall be written on standard error, followed by the current input and output block counts in the same format as used at completion (see the STDERR section). If the sync conversion is specified, the missing input shall be replaced with null bytes and processed normally; otherwise, the input block shall be omitted from the output.
notrunc
Do not truncate the output file. Preserve blocks in the output file not explicitly written by this invocation of the dd utility. (See also the preceding of= file operand.)
sync
Pad every input block to the size of the ibs= buffer, appending null bytes. (If either block or unblock is also specified, append <space>s, rather than null bytes.)

The behavior is unspecified if operands other than conv= are specified more than once.

For the bs=, cbs=, ibs=, and obs= operands, the application shall supply an expression specifying a size in bytes. The expression, expr, can be:

1.
A positive decimal number

2.
A positive decimal number followed by k, specifying multiplication by 1024

3.
A positive decimal number followed by b, specifying multiplication by 512

4.
Two or more positive decimal numbers (with or without k or b) separated by x, specifying the product of the indicated values

All of the operands are processed before any input is read.

The following two tables display the octal number character values used for the ascii and ebcdic conversions (first table) and for the ibm conversion (second table). In both tables, the ASCII values are the row and column headers and the EBCDIC values are found at their intersections. For example, ASCII 0012 (LF) is the second row, third column, yielding 0045 in EBCDIC. The inverted tables (for EBCDIC to ASCII conversion) are not shown, but are in one-to-one correspondence with these tables. The differences between the two tables are highlighted by small boxes drawn around five entries.

Table: ASCII to EBCDIC Conversion

Table: ASCII to IBM EBCDIC Conversion

STDIN

If no if= operand is specified, the standard input shall be used. See the INPUT FILES section.

INPUT FILES

The input file can be any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of dd:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the classification of characters as uppercase or lowercase, and the mapping of characters from one case to the other.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

For SIGINT, the dd utility shall interrupt its current processing, write status information to standard error, and exit as though terminated by SIGINT. It shall take the standard action for all other signals; see the ASYNCHRONOUS EVENTS section in Utility Description Defaults .

STDOUT

If no of= operand is specified, the standard output shall be used. The nature of the output depends on the operands selected.

STDERR

On completion, dd shall write the number of input and output blocks to standard error. In the POSIX locale the following formats shall be used:

"%u+%u records in\n", <number of whole input blocks>,
    <number of partial input blocks>

"%u+%u records out\n", <number of whole output blocks>,
    <number of partial output blocks>

A partial input block is one for which read() returned less than the input block size. A partial output block is one that was written with fewer bytes than specified by the output block size.

In addition, when there is at least one truncated block, the number of truncated blocks shall be written to standard error. In the POSIX locale, the format shall be:

"%u truncated %s\n", <number of truncated blocks>, "record" (if
    <number of truncated blocks> is one) "records" (otherwise)

Diagnostic messages may also be written to standard error.

OUTPUT FILES

If the of= operand is used, the output shall be the same as described in the STDOUT section.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The input file was copied successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If an input error is detected and the noerror conversion has not been specified, any partial output block shall be written to the output file, a diagnostic message shall be written, and the copy operation shall be discontinued. If some other error is detected, a diagnostic message shall be written and the copy operation shall be discontinued.

The following sections are informative.

APPLICATION USAGE

The input and output block size can be specified to take advantage of raw physical I/O.

There are many different versions of the EBCDIC codesets. The ASCII and EBCDIC conversions specified for the dd utility perform conversions for the version specified by the tables.

EXAMPLES

The following command:

dd if=/dev/rmt0h  of=/dev/rmt1h

copies from tape drive 0 to tape drive 1, using a common historical device naming convention.

The following command:

dd ibs=10  skip=1

strips the first 10 bytes from standard input.

This example reads an EBCDIC tape blocked ten 80-byte EBCDIC card images per block into the ASCII file x:

dd if=/dev/tape of=x ibs=800 cbs=80 conv=ascii,lcase

RATIONALE

The OPTIONS section is listed as "None" because there are no options recognized by historical dd utilities. Certainly, many of the operands could have been designed to use the Utility Syntax Guidelines, which would have resulted in the classic hyphenated option letters. In this version of this volume of IEEE Std 1003.1-2001, dd retains its curious JCL-like syntax due to the large number of applications that depend on the historical implementation.

A suggested implementation technique for conv= noerror, sync is to zero (or <space>-fill, if blocking or unblocking) the input buffer before each read and to write the contents of the input buffer to the output even after an error. In this manner, any data transferred to the input buffer before the error was detected is preserved. Another point is that a failed read on a regular file or a disk generally does not increment the file offset, and dd must then seek past the block on which the error occurred; otherwise, the input error occurs repetitively. When the input is a magnetic tape, however, the tape normally has passed the block containing the error when the error is reported, and thus no seek is necessary.

The default ibs= and obs= sizes are specified as 512 bytes because there are historical (largely portable) scripts that assume these values. If they were left unspecified, unusual results could occur if an implementation chose an odd block size.

Historical implementations of dd used creat() when processing of= file. This makes the seek= operand unusable except on special files. The conv= notrunc feature was added because more recent BSD-based implementations use open() (without O_TRUNC) instead of creat(), but they fail to delete output file contents after the data copied.

The w multiplier (historically meaning word), is used in System V to mean 2 and in 4.2 BSD to mean 4. Since word is inherently non-portable, its use is not supported by this volume of IEEE Std 1003.1-2001.

Standard EBCDIC does not have the characters '[' and ']' . The values used in the table are taken from a common print train that does contain them. Other than those characters, the print train values are not filled in, but appear to provide some of the motivation for the historical choice of translations reflected here.

The Standard EBCDIC table provides a 1:1 translation for all 256 bytes.

The IBM EBCDIC table does not provide such a translation. The marked cells in the tables differ in such a way that:

1.
EBCDIC 0112 ( 'cent' ) and 0152 (broken pipe) do not appear in the table.

2.
EBCDIC 0137 ( 'not' ) translates to/from ASCII 0236 ( '^' ). In the standard table, EBCDIC 0232 (no graphic) is used.

3.
EBCDIC 0241 ( '~' ) translates to/from ASCII 0176 ( '~' ). In the standard table, EBCDIC 0137 ( 'not' ) is used.

4.
0255 ( '[' ) and 0275 ( ']' ) appear twice, once in the same place as for the standard table and once in place of 0112 ( 'cent' ) and 0241 ( '~' ).

In net result: EBCDIC 0275 ( ']' ) displaced EBCDIC 0241 ( '~' ) in cell 0345.

That displaced EBCDIC 0137 ( 'not' ) in cell 0176.

That displaced EBCDIC 0232 (no graphic) in cell 0136.

That replaced EBCDIC 0152 (broken pipe) in cell 0313.

EBCDIC 0255 ( '[' ) replaced EBCDIC 0112 ( 'cent' ).

This translation, however, reflects historical practice that (ASCII) '~' and 'not' were often mapped to each other, as were '[' and 'cent' ; and ']' and (EBCDIC) '~' .

The cbs operand is required if any of the ascii, ebcdic, or ibm operands are specified. For the ascii operand, the input is handled as described for the unblock operand except that characters are converted to ASCII before the trailing <space>s are deleted. For the ebcdic and ibm operands, the input is handled as described for the block operand except that the characters are converted to EBCDIC or IBM EBCDIC after the trailing <space>s are added.

The block and unblock keywords are from historical BSD practice.

The consistent use of the word record in standard error messages matches most historical practice. An earlier version of System V used block, but this has been updated in more recent releases.

Early proposals only allowed two numbers separated by x to be used in a product when specifying bs=, cbs=, ibs=, and obs= sizes. This was changed to reflect the historical practice of allowing multiple numbers in the product as provided by Version 7 and all releases of System V and BSD.

A change to the swab conversion is required to match historical practice and is the result of IEEE PASC Interpretations 1003.2 #03 and #04, submitted for the ISO POSIX-2:1993 standard.

A change to the handling of SIGINT is required to match historical practice and is the result of IEEE PASC Interpretation 1003.2 #06 submitted for the ISO POSIX-2:1993 standard.

FUTURE DIRECTIONS

None.

SEE ALSO

Utility Description Defaults , sed , tr

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qsig(1p)

QSIG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qsig - signal batch jobs

SYNOPSIS

qsig [-s signal] job_identifier ...

DESCRIPTION

To signal a batch job is to send a signal to the session leader of the batch job. A batch job is signaled by sending a request to the batch server that manages the batch job. The qsig utility is a user-accessible batch client that requests the signaling of a batch job.

The qsig utility shall signal those batch jobs for which a batch job_identifier is presented to the utility. The qsig utility shall not signal any batch jobs whose batch job_identifiers are not presented to the utility.

The qsig utility shall signal batch jobs in the order in which the corresponding batch job_identifiers are presented to the utility. If the qsig utility fails to process a batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

The qsig utility shall signal batch jobs by sending a Signal Job Request to the batch server that manages the batch job.

For each successfully processed batch job_identifier, the qsig utility shall have received a completion reply to each Signal Job Request sent to a batch server at the time the utility exits.

OPTIONS

The qsig utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported by the implementation:

-s signal
Define the signal to be sent to the batch job.

The qsig utility shall accept a signal option-argument that is either a symbolic signal name or an unsigned integer signal number (see the POSIX.1-1990 standard, Section 3.3.1.1). The qsig utility shall accept signal names for which the SIG prefix has been omitted.

If the signal option-argument is a signal name, the qsig utility shall send that name.

If the signal option-argument is a number, the qsig utility shall send the signal value represented by the number.

If the -s option is not presented to the qsig utility, the utility shall send the signal SIGTERM to each signaled batch job.

OPERANDS

The qsig utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qsig:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.

ASYNCHRONOUS EVENTS

Default.

STDOUT

An implementation of the qsig utility may write informative messages to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qsig utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qsig utility waits to output the diagnostic message while attempting to locate the batch job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qsig utility allows users to signal batch jobs.

A user may be unable to signal a batch job with the kill utility of the operating system for a number of reasons. First, the process ID of the batch job may be unknown to the user. Second, the processes of the batch job may be on a remote node. However, by virtue of communication between batch nodes, the qsig utility can arrange for the signaling of a process.

Because a batch job that is not running cannot be signaled, and because the signal may not terminate the batch job, the qsig utility is not a substitute for the qdel utility.

The options of the qsig utility allow the user to specify the signal that is to be sent to the batch job.

The -s option allows users to specify a signal by name or by number, and thus override the default signal. The POSIX.1-1990 standard defines signals by both name and number.

The qsig utility is a new utility, vis-a-vis existing practice; it has been defined in this volume of IEEE Std 1003.1-2001 in response to user-perceived shortcomings in existing practice.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , kill() , qdel

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cp(1p)

CP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cp - copy files

SYNOPSIS

cp [-fip] source_file target_file

cp [-fip] source_file ... target

cp -R [-H | -L | -P][-fip] source_file ... target

cp -r [-H | -L | -P][-fip] source_file ... target

DESCRIPTION

The first synopsis form is denoted by two operands, neither of which are existing files of type directory. The cp utility shall copy the contents of source_file (or, if source_file is a file of type symbolic link, the contents of the file referenced by source_file) to the destination path named by target_file.

The second synopsis form is denoted by two or more operands where the -R or -r options are not specified and the first synopsis form is not applicable. It shall be an error if any source_file is a file of type directory, if target does not exist, or if target is a file of a type defined by the System Interfaces volume of IEEE Std 1003.1-2001, but is not a file of type directory. The cp utility shall copy the contents of each source_file (or, if source_file is a file of type symbolic link, the contents of the file referenced by source_file) to the destination path named by the concatenation of target, a slash character, and the last component of source_file.

The third and fourth synopsis forms are denoted by two or more operands where the -R or -r options are specified. The cp utility shall copy each file in the file hierarchy rooted in each source_file to a destination path named as follows:

*
If target exists and is a file of type directory, the name of the corresponding destination path for each file in the file hierarchy shall be the concatenation of target, a slash character, and the pathname of the file relative to the directory containing source_file.

*
If target does not exist and two operands are specified, the name of the corresponding destination path for source_file shall be target; the name of the corresponding destination path for all other files in the file hierarchy shall be the concatenation of target, a slash character, and the pathname of the file relative to source_file.

It shall be an error if target does not exist and more than two operands are specified, or if target exists and is a file of a type defined by the System Interfaces volume of IEEE Std 1003.1-2001, but is not a file of type directory.

In the following description, the term dest_file refers to the file named by the destination path. The term source_file refers to the file that is being copied, whether specified as an operand or a file in a file hierarchy rooted in a source_file operand. If source_file is a file of type symbolic link:

*
If neither the -R nor -r options were specified, cp shall take actions based on the type and contents of the file referenced by the symbolic link, and not by the symbolic link itself.

*
If the -R option was specified:
*
If none of the options -H, -L, nor -P were specified, it is unspecified which of -H, -L, or -P will be used as a default.

*
If the -H option was specified, cp shall take actions based on the type and contents of the file referenced by any symbolic link specified as a source_file operand.

*
If the -L option was specified, cp shall take actions based on the type and contents of the file referenced by any symbolic link specified as a source_file operand or any symbolic links encountered during traversal of a file hierarchy.

*
If the -P option was specified, cp shall copy any symbolic link specified as a source_file operand and any symbolic links encountered during traversal of a file hierarchy, and shall not follow any symbolic links.

*
If the -r option was specified, the behavior is implementation-defined.

For each source_file, the following steps shall be taken:

1.
If source_file references the same file as dest_file, cp may write a diagnostic message to standard error; it shall do nothing more with source_file and shall go on to any remaining files.

2.
If source_file is of type directory, the following steps shall be taken:
a.
If neither the -R or -r options were specified, cp shall write a diagnostic message to standard error, do nothing more with source_file, and go on to any remaining files.

b.
If source_file was not specified as an operand and source_file is dot or dot-dot, cp shall do nothing more with source_file and go on to any remaining files.

c.
If dest_file exists and it is a file type not specified by the System Interfaces volume of IEEE Std 1003.1-2001, the behavior is implementation-defined.

d.
If dest_file exists and it is not of type directory, cp shall write a diagnostic message to standard error, do nothing more with source_file or any files below source_file in the file hierarchy, and go on to any remaining files.

e.
If the directory dest_file does not exist, it shall be created with file permission bits set to the same value as those of source_file, modified by the file creation mask of the user if the -p option was not specified, and then bitwise-inclusively OR'ed with S_IRWXU. If dest_file cannot be created, cp shall write a diagnostic message to standard error, do nothing more with source_file, and go on to any remaining files. It is unspecified if cp attempts to copy files in the file hierarchy rooted in source_file.

f.
The files in the directory source_file shall be copied to the directory dest_file, taking the four steps (1 to 4) listed here with the files as source_files.

g.
If dest_file was created, its file permission bits shall be changed (if necessary) to be the same as those of source_file, modified by the file creation mask of the user if the -p option was not specified.

h.
The cp utility shall do nothing more with source_file and go on to any remaining files.

3.
If source_file is of type regular file, the following steps shall be taken:
a.
If dest_file exists, the following steps shall be taken:
i.
If the -i option is in effect, the cp utility shall write a prompt to the standard error and read a line from the standard input. If the response is not affirmative, cp shall do nothing more with source_file and go on to any remaining files.

ii.
A file descriptor for dest_file shall be obtained by performing actions equivalent to the open() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 called using dest_file as the path argument, and the bitwise-inclusive OR of O_WRONLY and O_TRUNC as the oflag argument.

iii.
If the attempt to obtain a file descriptor fails and the -f option is in effect, cp shall attempt to remove the file by performing actions equivalent to the unlink() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 called using dest_file as the path argument. If this attempt succeeds, cp shall continue with step 3b.

b.
If dest_file does not exist, a file descriptor shall be obtained by performing actions equivalent to the open() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 called using dest_file as the path argument, and the bitwise-inclusive OR of O_WRONLY and O_CREAT as the oflag argument. The file permission bits of source_file shall be the mode argument.

c.
If the attempt to obtain a file descriptor fails, cp shall write a diagnostic message to standard error, do nothing more with source_file, and go on to any remaining files.

d.
The contents of source_file shall be written to the file descriptor. Any write errors shall cause cp to write a diagnostic message to standard error and continue to step 3e.

e.
The file descriptor shall be closed.

f.
The cp utility shall do nothing more with source_file. If a write error occurred in step 3d, it is unspecified if cp continues with any remaining files. If no write error occurred in step 3d, cp shall go on to any remaining files.

4.
Otherwise, the following steps shall be taken:
a.
If the -r option was specified, the behavior is implementation-defined.

b.
If the -R option was specified, the following steps shall be taken:
i.
The dest_file shall be created with the same file type as source_file.

ii.
If source_file is a file of type FIFO, the file permission bits shall be the same as those of source_file, modified by the file creation mask of the user if the -p option was not specified. Otherwise, the permissions, owner ID, and group ID of dest_file are implementation-defined.

If this creation fails for any reason, cp shall write a diagnostic message to standard error, do nothing more with source_file, and go on to any remaining files.

iii.
If source_file is a file of type symbolic link, the pathname contained in dest_file shall be the same as the pathname contained in source_file.

If this fails for any reason, cp shall write a diagnostic message to standard error, do nothing more with source_file, and go on to any remaining files.

If the implementation provides additional or alternate access control mechanisms (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.4, File Access Permissions), their effect on copies of files is implementation-defined.

OPTIONS

The cp utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-f
If a file descriptor for a destination file cannot be obtained, as described in step 3.a.ii., attempt to unlink the destination file and proceed.
-H
Take actions based on the type and contents of the file referenced by any symbolic link specified as a source_file operand.
-i
Write a prompt to standard error before copying to any existing destination file. If the response from the standard input is affirmative, the copy shall be attempted; otherwise, it shall not.
-L
Take actions based on the type and contents of the file referenced by any symbolic link specified as a source_file operand or any symbolic links encountered during traversal of a file hierarchy.
-P
Take actions on any symbolic link specified as a source_file operand or any symbolic link encountered during traversal of a file hierarchy.
-p
Duplicate the following characteristics of each source file in the corresponding destination file:
1.
The time of last data modification and time of last access. If this duplication fails for any reason, cp shall write a diagnostic message to standard error.

2.
The user ID and group ID. If this duplication fails for any reason, it is unspecified whether cp writes a diagnostic message to standard error.

3.
The file permission bits and the S_ISUID and S_ISGID bits. Other, implementation-defined, bits may be duplicated as well. If this duplication fails for any reason, cp shall write a diagnostic message to standard error.

If the user ID or the group ID cannot be duplicated, the file permission bits S_ISUID and S_ISGID shall be cleared. If these bits are present in the source file but are not duplicated in the destination file, it is unspecified whether cp writes a diagnostic message to standard error.

The order in which the preceding characteristics are duplicated is unspecified. The dest_file shall not be deleted if these characteristics cannot be preserved.

-R
Copy file hierarchies.
-r
Copy file hierarchies. The treatment of special files is implementation-defined.

Specifying more than one of the mutually-exclusive options -H, -L, and -P shall not be considered an error. The last option specified shall determine the behavior of the utility.

OPERANDS

The following operands shall be supported:

source_file
A pathname of a file to be copied.
target_file
A pathname of an existing or nonexistent file, used for the output when a single file is copied.
target
A pathname of a directory to contain the copied files.

STDIN

The standard input shall be used to read an input line in response to each prompt specified in the STDERR section. Otherwise, the standard input shall not be used.

INPUT FILES

The input files specified as operands may be of any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cp:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.
LC_MESSAGES
Determine the locale for the processing of affirmative responses that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

A prompt shall be written to standard error under the conditions specified in the DESCRIPTION section. The prompt shall contain the destination pathname, but its format is otherwise unspecified. Otherwise, the standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output files may be of any type.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All files were copied successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If cp is prematurely terminated by a signal or error, files or file hierarchies may be only partially copied and files and directories may have incorrect permissions or access and modification times.

The following sections are informative.

APPLICATION USAGE

The difference between -R and -r is in the treatment by cp of file types other than regular and directory. The original -r flag, for historic reasons, does not handle special files any differently from regular files, but always reads the file and copies its contents. This has obvious problems in the presence of special file types; for example, character devices, FIFOs, and sockets. The -R option is intended to recreate the file hierarchy and the -r option supports historical practice. It was anticipated that a future version of this volume of IEEE Std 1003.1-2001 would deprecate the -r option, and for that reason, there has been no attempt to fix its behavior with respect to FIFOs or other file types where copying the file is clearly wrong. However, some implementations support -r with the same abilities as the -R defined in this volume of IEEE Std 1003.1-2001. To accommodate them as well as systems that do not, the differences between -r and -R are implementation-defined. Implementations may make them identical. The -r option is marked obsolescent.

The set-user-ID and set-group-ID bits are explicitly cleared when files are created. This is to prevent users from creating programs that are set-user-ID or set-group-ID to them when copying files or to make set-user-ID or set-group-ID files accessible to new groups of users. For example, if a file is set-user-ID and the copy has a different group ID than the source, a new group of users has execute permission to a set-user-ID program than did previously. In particular, this is a problem for superusers copying users' trees.

EXAMPLES

None.

RATIONALE

The -i option exists on BSD systems, giving applications and users a way to avoid accidentally removing files when copying. Although the 4.3 BSD version does not prompt if the standard input is not a terminal, the standard developers decided that use of -i is a request for interaction, so when the destination path exists, the utility takes instructions from whatever responds on standard input.

The exact format of the interactive prompts is unspecified. Only the general nature of the contents of prompts are specified because implementations may desire more descriptive prompts than those used on historical implementations. Therefore, an application using the -i option relies on the system to provide the most suitable dialog directly with the user, based on the behavior specified.

The -p option is historical practice on BSD systems, duplicating the time of last data modification and time of last access. This volume of IEEE Std 1003.1-2001 extends it to preserve the user and group IDs, as well as the file permissions. This requirement has obvious problems in that the directories are almost certainly modified after being copied. This volume of IEEE Std 1003.1-2001 requires that the modification times be preserved. The statement that the order in which the characteristics are duplicated is unspecified is to permit implementations to provide the maximum amount of security for the user. Implementations should take into account the obvious security issues involved in setting the owner, group, and mode in the wrong order or creating files with an owner, group, or mode different from the final value.

It is unspecified whether cp writes diagnostic messages when the user and group IDs cannot be set due to the widespread practice of users using -p to duplicate some portion of the file characteristics, indifferent to the duplication of others. Historic implementations only write diagnostic messages on errors other than [EPERM].

The -r option is historical practice on BSD and BSD-derived systems, copying file hierarchies as opposed to single files. This functionality is used heavily in historical applications, and its loss would significantly decrease consensus. The -R option was added as a close synonym to the -r option, selected for consistency with all other options in this volume of IEEE Std 1003.1-2001 that do recursive directory descent.

When a failure occurs during the copying of a file hierarchy, cp is required to attempt to copy files that are on the same level in the hierarchy or above the file where the failure occurred. It is unspecified if cp shall attempt to copy files below the file where the failure occurred (which cannot succeed in any case).

Permissions, owners, and groups of created special file types have been deliberately left as implementation-defined. This is to allow systems to satisfy special requirements (for example, allowing users to create character special devices, but requiring them to be owned by a certain group). In general, it is strongly suggested that the permissions, owner, and group be the same as if the user had run the historical mknod, ln, or other utility to create the file. It is also probable that additional privileges are required to create block, character, or other implementation-defined special file types.

Additionally, the -p option explicitly requires that all set-user-ID and set-group-ID permissions be discarded if any of the owner or group IDs cannot be set. This is to keep users from unintentionally giving away special privilege when copying programs.

When creating regular files, historical versions of cp use the mode of the source file as modified by the file mode creation mask. Other choices would have been to use the mode of the source file unmodified by the creation mask or to use the same mode as would be given to a new file created by the user (plus the execution bits of the source file) and then modify it by the file mode creation mask. In the absence of any strong reason to change historic practice, it was in large part retained.

When creating directories, historical versions of cp use the mode of the source directory, plus read, write, and search bits for the owner, as modified by the file mode creation mask. This is done so that cp can copy trees where the user has read permission, but the owner does not. A side effect is that if the file creation mask denies the owner permissions, cp fails. Also, once the copy is done, historical versions of cp set the permissions on the created directory to be the same as the source directory, unmodified by the file creation mask.

This behavior has been modified so that cp is always able to create the contents of the directory, regardless of the file creation mask. After the copy is done, the permissions are set to be the same as the source directory, as modified by the file creation mask. This latter change from historical behavior is to prevent users from accidentally creating directories with permissions beyond those they would normally set and for consistency with the behavior of cp in creating files.

It is not a requirement that cp detect attempts to copy a file to itself; however, implementations are strongly encouraged to do so. Historical implementations have detected the attempt in most cases.

There are two methods of copying subtrees in this volume of IEEE Std 1003.1-2001. The other method is described as part of the pax utility (see pax ). Both methods are historical practice. The cp utility provides a simpler, more intuitive interface, while pax offers a finer granularity of control. Each provides additional functionality to the other; in particular, pax maintains the hard-link structure of the hierarchy, while cp does not. It is the intention of the standard developers that the results be similar (using appropriate option combinations in both utilities). The results are not required to be identical; there seemed insufficient gain to applications to balance the difficulty of implementations having to guarantee that the results would be exactly identical.

The wording allowing cp to copy a directory to implementation-defined file types not specified by the System Interfaces volume of IEEE Std 1003.1-2001 is provided so that implementations supporting symbolic links are not required to prohibit copying directories to symbolic links. Other extensions to the System Interfaces volume of IEEE Std 1003.1-2001 file types may need to use this loophole as well.

FUTURE DIRECTIONS

The -r option may be removed; use -R instead.

SEE ALSO

mv , find , ln , pax , the System Interfaces volume of IEEE Std 1003.1-2001, open(), unlink()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


df(1p)

DF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

df - report free disk space

SYNOPSIS

df [-k][-P|-t][file...]

DESCRIPTION

The df utility shall write the amount of available space and file slots for file systems on which the invoking user has appropriate read access. File systems shall be specified by the file operands; when none are specified, information shall be written for all file systems. The format of the default output from df is unspecified, but all space figures are reported in 512-byte units, unless the -k option is specified. This output shall contain at least the file system names, amount of available space on each of these file systems, and the number of free file slots, or inodes, available; when -t is specified, the output shall contain the total allocated space as well.

OPTIONS

The df utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-k
Use 1024-byte units, instead of the default 512-byte units, when writing space figures.
-P
Produce output in the format described in the STDOUT section.
-t
Include total allocated-space figures in the output.

OPERANDS

The following operand shall be supported:

file
A pathname of a file within the hierarchy of the desired file system. If a file other than a FIFO, a regular file, a directory, or a special file representing the device containing the file system (for example, /dev/dsk/0s1) is specified, the results are unspecified. Otherwise, df shall write the amount of free space in the file system containing the specified file operand.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of df:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

When both the -k and -P options are specified, the following header line shall be written (in the POSIX locale):

"Filesystem 1024-blocks Used Available Capacity Mounted on\n"

When the -P option is specified without the -k option, the following header line shall be written (in the POSIX locale):

"Filesystem 512-blocks Used Available Capacity Mounted on\n"

The implementation may adjust the spacing of the header line and the individual data lines so that the information is presented in orderly columns.

The remaining output with -P shall consist of one line of information for each specified file system. These lines shall be formatted as follows:

"%s %d %d %d %d%% %s\n", <file system name>, <total space>,
    <space used>, <space free>, <percentage used>,
    <file system root>

In the following list, all quantities expressed in 512-byte units (1024-byte when -k is specified) shall be rounded up to the next higher unit. The fields are:

<file system name>

The name of the file system, in an implementation-defined format.

<total space>
The total size of the file system in 512-byte units. The exact meaning of this figure is implementation-defined, but should include <space used>, <space free>, plus any space reserved by the system not normally available to a user.
<space used>
The total amount of space allocated to existing files in the file system, in 512-byte units.
<space free>
The total amount of space available within the file system for the creation of new files by unprivileged users, in 512-byte units. When this figure is less than or equal to zero, it shall not be possible to create any new files on the file system without first deleting others, unless the process has appropriate privileges. The figure written may be less than zero.
<percentage used>

The percentage of the normally available space that is currently allocated to all files on the file system. This shall be calculated using the fraction:

<space used>/( <space used>+ <space free>)

expressed as a percentage. This percentage may be greater than 100 if <space free> is less than zero. The percentage value shall be expressed as a positive integer, with any fractional result causing it to be rounded to the next highest integer.

<file system root>

The directory below which the file system hierarchy appears.

The output format is unspecified when -t is used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

On most systems, the "name of the file system, in an implementation-defined format" is the special file on which the file system is mounted.

On large file systems, the calculation specified for percentage used can create huge rounding errors.

EXAMPLES

1.
The following example writes portable information about the /usr file system:

df -P /usr

2.
Assuming that /usr/src is part of the /usr file system, the following produces the same output as the previous example:

df -P /usr/src

RATIONALE

The behavior of df with the -P option is the default action of the 4.2 BSD df utility. The uppercase -P was selected to avoid collision with a known industry extension using -p.

Historical df implementations vary considerably in their default output. It was therefore necessary to describe the default output in a loose manner to accommodate all known historical implementations and to add a portable option ( -P) to provide information in a portable format.

The use of 512-byte units is historical practice and maintains compatibility with ls and other utilities in this volume of IEEE Std 1003.1-2001. This does not mandate that the file system itself be based on 512-byte blocks. The -k option was added as a compromise measure. It was agreed by the standard developers that 512 bytes was the best default unit because of its complete historical consistency on System V (versus the mixed 512/1024-byte usage on BSD systems), and that a -k option to switch to 1024-byte units was a good compromise. Users who prefer the more logical 1024-byte quantity can easily alias df to df -k without breaking many historical scripts relying on the 512-byte units.

It was suggested that df and the various related utilities be modified to access a BLOCKSIZE environment variable to achieve consistency and user acceptance. Since this is not historical practice on any system, it is left as a possible area for system extensions and will be re-evaluated in a future version if it is widely implemented.

FUTURE DIRECTIONS

None.

SEE ALSO

find

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ed(1p)

ED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ed - edit text

SYNOPSIS

ed [-p string][-s][file]

DESCRIPTION

The ed utility is a line-oriented text editor that uses two modes: command mode and input mode. In command mode the input characters shall be interpreted as commands, and in input mode they shall be interpreted as text. See the EXTENDED DESCRIPTION section.

OPTIONS

The ed utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-p string
Use string as the prompt string when in command mode. By default, there shall be no prompt string.
-s
Suppress the writing of byte counts by e, E, r, and w commands and of the '!' prompt after a !command.

OPERANDS

The following operand shall be supported:

file
If the file argument is given, ed shall simulate an e command on the file named by the pathname, file, before accepting commands from the standard input. If the file operand is '-' , the results are unspecified.

STDIN

The standard input shall be a text file consisting of commands, as described in the EXTENDED DESCRIPTION section.

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ed:

HOME
Determine the pathname of the user's home directory.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classes within regular expressions.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

The ed utility shall take the standard action for all signals (see the ASYNCHRONOUS EVENTS section in Utility Description Defaults ) with the following exceptions:

SIGINT
The ed utility shall interrupt its current activity, write the string "?\n" to standard output, and return to command mode (see the EXTENDED DESCRIPTION section).
SIGHUP
If the buffer is not empty and has changed since the last write, the ed utility shall attempt to write a copy of the buffer in a file. First, the file named ed.hup in the current directory shall be used; if that fails, the file named ed.hup in the directory named by the HOME environment variable shall be used. In any case, the ed utility shall exit without returning to command mode.
SIGQUIT
The ed utility shall ignore this event.

STDOUT

Various editing commands and the prompting feature (see -p) write to standard output, as described in the EXTENDED DESCRIPTION section.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output files shall be text files whose formats are dependent on the editing commands given.

EXTENDED DESCRIPTION

The ed utility shall operate on a copy of the file it is editing; changes made to the copy shall have no effect on the file until a w (write) command is given. The copy of the text is called the buffer.

Commands to ed have a simple and regular structure: zero, one, or two addresses followed by a single-character command, possibly followed by parameters to that command. These addresses specify one or more lines in the buffer. Every command that requires addresses has default addresses, so that the addresses very often can be omitted. If the -p option is specified, the prompt string shall be written to standard output before each command is read.

In general, only one command can appear on a line. Certain commands allow text to be input. This text is placed in the appropriate place in the buffer. While ed is accepting text, it is said to be in input mode. In this mode, no commands shall be recognized; all input is merely collected. Input mode is terminated by entering a line consisting of two characters: a period ( '.' ) followed by a <newline>. This line is not considered part of the input text.

Regular Expressions in ed

The ed utility shall support basic regular expressions, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions. Since regular expressions in ed are always matched against single lines (excluding the terminating <newline>s), never against any larger section of text, there is no way for a regular expression to match a <newline>.

A null RE shall be equivalent to the last RE encountered.

Regular expressions are used in addresses to specify lines, and in some commands (for example, the s substitute command) to specify portions of a line to be substituted.

Addresses in ed

Addressing in ed relates to the current line. Generally, the current line is the last line affected by a command. The current line number is the address of the current line. If the edit buffer is not empty, the initial value for the current line shall be the last line in the edit buffer; otherwise, zero.

Addresses shall be constructed as follows:

1.
The period character ( '.' ) shall address the current line.

2.
The dollar sign character ( '$' ) shall address the last line of the edit buffer.

3.
The positive decimal number n shall address the nth line of the edit buffer.

4.
The apostrophe-x character pair ( "'x" ) shall address the line marked with the mark name character x, which shall be a lowercase letter from the portable character set. It shall be an error if the character has not been set to mark a line or if the line that was marked is not currently present in the edit buffer.

5.
A BRE enclosed by slash characters ( '/' ) shall address the first line found by searching forwards from the line following the current line toward the end of the edit buffer and stopping at the first line for which the line excluding the terminating <newline> matches the BRE. The BRE consisting of a null BRE delimited by a pair of slash characters shall address the next line for which the line excluding the terminating <newline> matches the last BRE encountered. In addition, the second slash can be omitted at the end of a command line. Within the BRE, a backslash-slash pair ( "\/" ) shall represent a literal slash instead of the BRE delimiter. If necessary, the search shall wrap around to the beginning of the buffer and continue up to and including the current line, so that the entire buffer is searched.

6.
A BRE enclosed by question-mark characters ( '?' ) shall address the first line found by searching backwards from the line preceding the current line toward the beginning of the edit buffer and stopping at the first line for which the line excluding the terminating <newline> matches the BRE. The BRE consisting of a null BRE delimited by a pair of question-mark characters ( "??" ) shall address the previous line for which the line excluding the terminating <newline> matches the last BRE encountered. In addition, the second question-mark can be omitted at the end of a command line. Within the BRE, a backslash-question-mark pair ( "\?" ) shall represent a literal question mark instead of the BRE delimiter. If necessary, the search shall wrap around to the end of the buffer and continue up to and including the current line, so that the entire buffer is searched.

7.
A plus-sign ( '+' ) or hyphen character ( '-' ) followed by a decimal number shall address the current line plus or minus the number. A plus-sign or hyphen character not followed by a decimal number shall address the current line plus or minus 1.

Addresses can be followed by zero or more address offsets, optionally <blank>-separated. Address offsets are constructed as follows:

*
A plus-sign or hyphen character followed by a decimal number shall add or subtract, respectively, the indicated number of lines to or from the address. A plus-sign or hyphen character not followed by a decimal number shall add or subtract 1 to or from the address.

*
A decimal number shall add the indicated number of lines to the address.

It shall not be an error for an intermediate address value to be less than zero or greater than the last line in the edit buffer. It shall be an error for the final address value to be less than zero or greater than the last line in the edit buffer. It shall be an error if a search for a BRE fails to find a matching line.

Commands accept zero, one, or two addresses. If more than the required number of addresses are provided to a command that requires zero addresses, it shall be an error. Otherwise, if more than the required number of addresses are provided to a command, the addresses specified first shall be evaluated and then discarded until the maximum number of valid addresses remain, for the specified command.

Addresses shall be separated from each other by a comma ( ',' ) or semicolon character ( ';' ). In the case of a semicolon separator, the current line ( '.' ) shall be set to the first address, and only then will the second address be calculated. This feature can be used to determine the starting line for forwards and backwards searches; see rules 5. and 6.

Addresses can be omitted on either side of the comma or semicolon separator, in which case the resulting address pairs shall be as follows:
Specified | Resulting
, | 1 , $
, addr | 1 , addr
addr , | addr , addr
; | . ; $
; addr | . ; addr
addr ; | addr ; addr

Any <blank>s included between addresses, address separators, or address offsets shall be ignored.

Commands in ed

In the following list of ed commands, the default addresses are shown in parentheses. The number of addresses shown in the default shall be the number expected by the command. The parentheses are not part of the address; they show that the given addresses are the default.

It is generally invalid for more than one command to appear on a line. However, any command (except e, E, f, q, Q, r, w, and !) can be suffixed by the letter l, n, or p; in which case, except for the l, n, and p commands, the command shall be executed and then the new current line shall be written as described below under the l, n, and p commands. When an l, n, or p suffix is used with an l, n, or p command, the command shall write to standard output as described below, but it is unspecified whether the suffix writes the current line again in the requested format or whether the suffix has no effect. For example, the pl command (base p command with an l suffix) shall either write just the current line or write it twice-once as specified for p and once as specified for l. Also, the g, G, v, and V commands shall take a command as a parameter.

Each address component can be preceded by zero or more <blank>s. The command letter can be preceded by zero or more <blank>s. If a suffix letter ( l, n, or p) is given, the application shall ensure that it immediately follows the command.

The e, E, f, r, and w commands shall take an optional file parameter, separated from the command letter by one or more <blank>s.

If changes have been made in the buffer since the last w command that wrote the entire buffer, ed shall warn the user if an attempt is made to destroy the editor buffer via the e or q commands. The ed utility shall write the string:

"?\n"

(followed by an explanatory message if help mode has been enabled via the H command) to standard output and shall continue in command mode with the current line number unchanged. If the e or q command is repeated with no intervening command, it shall take effect.

If a terminal disconnect is detected:

*
If the buffer is not empty and has changed since the last write, the ed utility shall attempt to write a copy of the buffer to a file named ed.hup in the current directory. If this write fails, ed shall attempt to write a copy of the buffer to a filename ed.hup in the directory named by the HOME environment variable. If both these attempts fail, ed shall exit without saving the buffer.

*
The ed utility shall not write the file to the currently remembered pathname or return to command mode, and shall terminate with a non-zero exit status.

If an end-of-file is detected on standard input:

*
If the ed utility is in input mode, ed shall terminate input mode and return to command mode. It is unspecified if any partially entered lines (that is, input text without a terminating <newline>) are discarded from the input text.

*
If the ed utility is in command mode, it shall act as if a q command had been entered.

If the closing delimiter of an RE or of a replacement string (for example, '/' ) in a g, G, s, v, or V command would be the last character before a <newline>, that delimiter can be omitted, in which case the addressed line shall be written. For example, the following pairs of commands are equivalent:

s/s1/s2   s/s1/s2/p
g/s1      g/s1/p
?s1       ?s1?

If an invalid command is entered, ed shall write the string:

"?\n"

(followed by an explanatory message if help mode has been enabled via the H command) to standard output and shall continue in command mode with the current line number unchanged.

Append Command

Synopsis:

(.)a
<text>
.

The a command shall read the given text and append it after the addressed line; the current line number shall become the address of the last inserted line or, if there were none, the addressed line. Address 0 shall be valid for this command; it shall cause the appended text to be placed at the beginning of the buffer.

Change Command

Synopsis:

(.,.)c
<text>
.

The c command shall delete the addressed lines, then accept input text that replaces these lines; the current line shall be set to the address of the last line input; or, if there were none, at the line after the last line deleted; if the lines deleted were originally at the end of the buffer, the current line number shall be set to the address of the new last line; if no lines remain in the buffer, the current line number shall be set to zero. Address 0 shall be valid for this command; it shall be interpreted as if address 1 were specified.

Delete Command

Synopsis:

(.,.)d

The d command shall delete the addressed lines from the buffer. The address of the line after the last line deleted shall become the current line number; if the lines deleted were originally at the end of the buffer, the current line number shall be set to the address of the new last line; if no lines remain in the buffer, the current line number shall be set to zero.

Edit Command

Synopsis:

e [file]

The e command shall delete the entire contents of the buffer and then read in the file named by the pathname file. The current line number shall be set to the address of the last line of the buffer. If no pathname is given, the currently remembered pathname, if any, shall be used (see the f command). The number of bytes read shall be written to standard output, unless the -s option was specified, in the following format:

"%d\n", <number of bytes read>

The name file shall be remembered for possible use as a default pathname in subsequent e, E, r, and w commands. If file is replaced by '!' , the rest of the line shall be taken to be a shell command line whose output is to be read. Such a shell command line shall not be remembered as the current file. All marks shall be discarded upon the completion of a successful e command. If the buffer has changed since the last time the entire buffer was written, the user shall be warned, as described previously.

Edit Without Checking Command

Synopsis:

E [file]

The E command shall possess all properties and restrictions of the e command except that the editor shall not check to see whether any changes have been made to the buffer since the last w command.

Filename Command

Synopsis:

f [file]

If file is given, the f command shall change the currently remembered pathname to file; whether the name is changed or not, it shall then write the (possibly new) currently remembered pathname to the standard output in the following format:

"%s\n", <pathname>

The current line number shall be unchanged.

Global Command

Synopsis:

(1,$)g/RE/command list

In the g command, the first step shall be to mark every line for which the line excluding the terminating <newline> matches the given RE. Then, going sequentially from the beginning of the file to the end of the file, the given command list shall be executed for each marked line, with the current line number set to the address of that line. Any line modified by the command list shall be unmarked. When the g command completes, the current line number shall have the value assigned by the last command in the command list. If there were no matching lines, the current line number shall not be changed. A single command or the first of a list of commands shall appear on the same line as the global command. All lines of a multi-line list except the last line shall be ended with a backslash preceding the terminating <newline>; the a, i, and c commands and associated input are permitted. The '.' terminating input mode can be omitted if it would be the last line of the command list. An empty command list shall be equivalent to the p command. The use of the g, G, v, V, and ! commands in the command list produces undefined results. Any character other than <space> or <newline> can be used instead of a slash to delimit the RE. Within the RE, the RE delimiter itself can be used as a literal character if it is preceded by a backslash.

Interactive Global Command

Synopsis:

(1,$)G/RE/

In the G command, the first step shall be to mark every line for which the line excluding the terminating <newline> matches the given RE. Then, for every such line, that line shall be written, the current line number shall be set to the address of that line, and any one command (other than one of the a, c, i, g, G, v, and V commands) shall be read and executed. A <newline> shall act as a null command (causing no action to be taken on the current line); an '&' shall cause the re-execution of the most recent non-null command executed within the current invocation of G. Note that the commands input as part of the execution of the G command can address and affect any lines in the buffer. Any line modified by the command shall be unmarked. The final value of the current line number shall be the value set by the last command successfully executed. (Note that the last command successfully executed shall be the G command itself if a command fails or the null command is specified.) If there were no matching lines, the current line number shall not be changed. The G command can be terminated by a SIGINT signal. Any character other than <space> or <newline> can be used instead of a slash to delimit the RE and the replacement. Within the RE, the RE delimiter itself can be used as a literal character if it is preceded by a backslash.

Help Command

Synopsis:

h

The h command shall write a short message to standard output that explains the reason for the most recent '?' notification. The current line number shall be unchanged.

Help-Mode Command

Synopsis:

H

The H command shall cause ed to enter a mode in which help messages (see the h command) shall be written to standard output for all subsequent '?' notifications. The H command alternately shall turn this mode on and off; it is initially off. If the help-mode is being turned on, the H command also explains the previous '?' notification, if there was one. The current line number shall be unchanged.

Insert Command

Synopsis:

(.)i
<text>
.

The i command shall insert the given text before the addressed line; the current line is set to the last inserted line or, if there was none, to the addressed line. This command differs from the a command only in the placement of the input text. Address 0 shall be valid for this command; it shall be interpreted as if address 1 were specified.

Join Command

Synopsis:

(.,.+1)j

The j command shall join contiguous lines by removing the appropriate <newline>s. If exactly one address is given, this command shall do nothing. If lines are joined, the current line number shall be set to the address of the joined line; otherwise, the current line number shall be unchanged.

Mark Command

Synopsis:

(.)kx

The k command shall mark the addressed line with name x, which the application shall ensure is a lowercase letter from the portable character set. The address "'x" shall then refer to this line; the current line number shall be unchanged.

List Command

Synopsis:

(.,.)l

The l command shall write to standard output the addressed lines in a visually unambiguous form. The characters listed in the Base Definitions volume of IEEE Std 1003.1-2001, Table 5-1, Escape Sequences and Associated Actions ( '\\' , '\a' , '\b' , '\f' , '\r' , '\t' , '\v' ) shall be written as the corresponding escape sequence; the '\n' in that table is not applicable. Non-printable characters not in the table shall be written as one three-digit octal number (with a preceding backslash character) for each byte in the character (most significant byte first). If the size of a byte on the system is greater than nine bits, the format used for non-printable characters is implementation-defined.

Long lines shall be folded, with the point of folding indicated by <newline> preceded by a backslash; the length at which folding occurs is unspecified, but should be appropriate for the output device. The end of each line shall be marked with a '$' , and '$' characters within the text shall be written with a preceding backslash. An l command can be appended to any other command other than e, E, f, q, Q, r, w, or !. The current line number shall be set to the address of the last line written.

Move Command

Synopsis:

(.,.)maddress

The m command shall reposition the addressed lines after the line addressed by address. Address 0 shall be valid for address and cause the addressed lines to be moved to the beginning of the buffer. It shall be an error if address address falls within the range of moved lines. The current line number shall be set to the address of the last line moved.

Number Command

Synopsis:

(.,.)n

The n command shall write to standard output the addressed lines, preceding each line by its line number and a <tab>; the current line number shall be set to the address of the last line written. The n command can be appended to any command other than e, E, f, q, Q, r, w, or !.

Print Command

Synopsis:

(.,.)p

The p command shall write to standard output the addressed lines; the current line number shall be set to the address of the last line written. The p command can be appended to any command other than e, E, f, q, Q, r, w, or !.

Prompt Command

Synopsis:

P

The P command shall cause ed to prompt with an asterisk ( '*' ) (or string, if -p is specified) for all subsequent commands. The P command alternatively shall turn this mode on and off; it shall be initially on if the -p option is specified; otherwise, off. The current line number shall be unchanged.

Quit Command

Synopsis:

q

The q command shall cause ed to exit. If the buffer has changed since the last time the entire buffer was written, the user shall be warned, as described previously.

Quit Without Checking Command

Synopsis:

Q

The Q command shall cause ed to exit without checking whether changes have been made in the buffer since the last w command.

Read Command

Synopsis:

($)r [file]

The r command shall read in the file named by the pathname file and append it after the addressed line. If no file argument is given, the currently remembered pathname, if any, shall be used (see the e and f commands). The currently remembered pathname shall not be changed unless there is no remembered pathname. Address 0 shall be valid for r and shall cause the file to be read at the beginning of the buffer. If the read is successful, and -s was not specified, the number of bytes read shall be written to standard output in the following format:

"%d\n", <number of bytes read>

The current line number shall be set to the address of the last line read in. If file is replaced by '!' , the rest of the line shall be taken to be a shell command line whose output is to be read. Such a shell command line shall not be remembered as the current pathname.

Substitute Command

Synopsis:

(.,.)s/RE/replacement/flags

The s command shall search each addressed line for an occurrence of the specified RE and replace either the first or all (non-overlapped) matched strings with the replacement; see the following description of the g suffix. It is an error if the substitution fails on every addressed line. Any character other than <space> or <newline> can be used instead of a slash to delimit the RE and the replacement. Within the RE, the RE delimiter itself can be used as a literal character if it is preceded by a backslash. The current line shall be set to the address of the last line on which a substitution occurred.

An ampersand ( '&' ) appearing in the replacement shall be replaced by the string matching the RE on the current line. The special meaning of '&' in this context can be suppressed by preceding it by backslash. As a more general feature, the characters '\n' , where n is a digit, shall be replaced by the text matched by the corresponding back-reference expression. When the character '%' is the only character in the replacement, the replacement used in the most recent substitute command shall be used as the replacement in the current substitute command; if there was no previous substitute command, the use of '%' in this manner shall be an error. The '%' shall lose its special meaning when it is in a replacement string of more than one character or is preceded by a backslash. For each backslash ( '\' ) encountered in scanning replacement from beginning to end, the following character shall lose its special meaning (if any). It is unspecified what special meaning is given to any character other than '&' , '\' , '%' , or digits.

A line can be split by substituting a <newline> into it. The application shall ensure it escapes the <newline> in the replacement by preceding it by backslash. Such substitution cannot be done as part of a g or v command list. The current line number shall be set to the address of the last line on which a substitution is performed. If no substitution is performed, the current line number shall be unchanged. If a line is split, a substitution shall be considered to have been performed on each of the new lines for the purpose of determining the new current line number. A substitution shall be considered to have been performed even if the replacement string is identical to the string that it replaces.

The application shall ensure that the value of flags is zero or more of:

count
Substitute for the countth occurrence only of the RE found on each addressed line.
g
Globally substitute for all non-overlapping instances of the RE rather than just the first one. If both g and count are specified, the results are unspecified.
l
Write to standard output the final line in which a substitution was made. The line shall be written in the format specified for the l command.
n
Write to standard output the final line in which a substitution was made. The line shall be written in the format specified for the n command.
p
Write to standard output the final line in which a substitution was made. The line shall be written in the format specified for the p command.

Copy Command

Synopsis:

(.,.)taddress

The t command shall be equivalent to the m command, except that a copy of the addressed lines shall be placed after address address (which can be 0); the current line number shall be set to the address of the last line added.

Undo Command

Synopsis:

u

The u command shall nullify the effect of the most recent command that modified anything in the buffer, namely the most recent a, c, d, g, i, j, m, r, s, t, u, v, G, or V command. All changes made to the buffer by a g, G, v, or V global command shall be undone as a single change; if no changes were made by the global command (such as with g/RE/ p), the u command shall have no effect. The current line number shall be set to the value it had immediately before the command being undone started.

Global Non-Matched Command

Synopsis:

(1,$)v/RE/command list

This command shall be equivalent to the global command g except that the lines that are marked during the first step shall be those for which the line excluding the terminating <newline> does not match the RE.

Interactive Global Not-Matched Command

Synopsis:

(1,$)V/RE/

This command shall be equivalent to the interactive global command G except that the lines that are marked during the first step shall be those for which the line excluding the terminating <newline> does not match the RE.

Write Command

Synopsis:

(1,$)w [file]

The w command shall write the addressed lines into the file named by the pathname file. The command shall create the file, if it does not exist, or shall replace the contents of the existing file. The currently remembered pathname shall not be changed unless there is no remembered pathname. If no pathname is given, the currently remembered pathname, if any, shall be used (see the e and f commands); the current line number shall be unchanged. If the command is successful, the number of bytes written shall be written to standard output, unless the -s option was specified, in the following format:

"%d\n", <number of bytes written>

If file begins with '!' , the rest of the line shall be taken to be a shell command line whose standard input shall be the addressed lines. Such a shell command line shall not be remembered as the current pathname. This usage of the write command with '!' shall not be considered as a "last w command that wrote the entire buffer", as described previously; thus, this alone shall not prevent the warning to the user if an attempt is made to destroy the editor buffer via the e or q commands.

Line Number Command

Synopsis:

($)=

The line number of the addressed line shall be written to standard output in the following format:

"%d\n", <line number>

The current line number shall be unchanged by this command.

Shell Escape Command

Synopsis:

!command

The remainder of the line after the '!' shall be sent to the command interpreter to be interpreted as a shell command line. Within the text of that shell command line, the unescaped character '%' shall be replaced with the remembered pathname; if a '!' appears as the first character of the command, it shall be replaced with the text of the previous shell command executed via '!' . Thus, "!!" shall repeat the previous !command. If any replacements of '%' or '!' are performed, the modified line shall be written to the standard output before command is executed. The ! command shall write:

"!\n"

to standard output upon completion, unless the -s option is specified. The current line number shall be unchanged.

Null Command

Synopsis:

(.+1)

An address alone on a line shall cause the addressed line to be written. A <newline> alone shall be equivalent to "+1p" . The current line number shall be set to the address of the written line.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion without any file or command errors.
>0
An error occurred.

CONSEQUENCES OF ERRORS

When an error in the input script is encountered, or when an error is detected that is a consequence of the data (not) present in the file or due to an external condition such as a read or write error:

*
If the standard input is a terminal device file, all input shall be flushed, and a new command read.

*
If the standard input is a regular file, ed shall terminate with a non-zero exit status.

The following sections are informative.

APPLICATION USAGE

Because of the extremely terse nature of the default error messages, the prudent script writer begins the ed input commands with an H command, so that if any errors do occur at least some clue as to the cause is made available.

In previous versions, an obsolescent - option was described. This is no longer specified. Applications should use the -s option. Using - as a file operand now produces unspecified results. This allows implementations to continue to support the former required behavior.

EXAMPLES

None.

RATIONALE

The initial description of this utility was adapted from the SVID. It contains some features not found in Version 7 or BSD-derived systems. Some of the differences between the POSIX and BSD ed utilities include, but need not be limited to:

*
The BSD - option does not suppress the '!' prompt after a ! command.

*
BSD does not support the special meanings of the '%' and '!' characters within a ! command.

*
BSD does not support the addresses ';' and ',' .

*
BSD allows the command/suffix pairs pp, ll, and so on, which are unspecified in this volume of IEEE Std 1003.1-2001.

*
BSD does not support the '!' character part of the e, r, or w commands.

*
A failed g command in BSD sets the line number to the last line searched if there are no matches.

*
BSD does not default the command list to the p command.

*
BSD does not support the G, h, H, n, or V commands.

*
On BSD, if there is no inserted text, the insert command changes the current line to the referenced line -1; that is, the line before the specified line.

*
On BSD, the join command with only a single address changes the current line to that address.

*
BSD does not support the P command; moreover, in BSD it is synonymous with the p command.

*
BSD does not support the undo of the commands j, m, r, s, or t.

*
The Version 7 ed command W, and the BSD ed commands W, wq, and z are not present in this volume of IEEE Std 1003.1-2001.

The -s option was added to allow the functionality of the now withdrawn - option in a manner compatible with the Utility Syntax Guidelines.

In early proposals there was a limit, {ED_FILE_MAX}, that described the historical limitations of some ed utilities in their handling of large files; some of these have had problems with files larger than 100000 bytes. It was this limitation that prompted much of the desire to include a split command in this volume of IEEE Std 1003.1-2001. Since this limit was removed, this volume of IEEE Std 1003.1-2001 requires that implementations document the file size limits imposed by ed in the conformance document. The limit {ED_LINE_MAX} was also removed; therefore, the global limit {LINE_MAX} is used for input and output lines.

The manner in which the l command writes non-printable characters was changed to avoid the historical backspace-overstrike method. On video display terminals, the overstrike is ambiguous because most terminals simply replace overstruck characters, making the l format not useful for its intended purpose of unambiguously understanding the content of the line. The historical backslash escapes were also ambiguous. (The string "a\0011" could represent a line containing those six characters or a line containing the three characters 'a' , a byte with a binary value of 1, and a 1.) In the format required here, a backslash appearing in the line is written as "\\" so that the output is truly unambiguous. The method of marking the ends of lines was adopted from the ex editor and is required for any line ending in <space>s; the '$' is placed on all lines so that a real '$' at the end of a line cannot be misinterpreted.

Systems with bytes too large to fit into three octal digits must devise other means of displaying non-printable characters. Consideration was given to requiring that the number of octal digits be large enough to hold a byte, but this seemed to be too confusing for applications on the vast majority of systems where three digits are adequate. It would be theoretically possible for the application to use the getconf utility to find out the CHAR_BIT value and deal with such an algorithm; however, there is really no portable way that an application can use the octal values of the bytes across various coded character sets, so the additional specification was not worthwhile.

The description of how a NUL is written was removed. The NUL character cannot be in text files, and this volume of IEEE Std 1003.1-2001 should not dictate behavior in the case of undefined, erroneous input.

Unlike some of the other editing utilities, the filenames accepted by the E, e, R, and r commands are not patterns.

Early proposals stated that the -p option worked only when standard input was associated with a terminal device. This has been changed to conform to historical implementations, thereby allowing applications to interpose themselves between a user and the ed utility.

The form of the substitute command that uses the n suffix was limited in some historical documentation (where this was described incorrectly as "backreferencing"). This limit has been omitted because there is no reason why an editor processing lines of {LINE_MAX} length should have this restriction. The command s/x/X/2047 should be able to substitute the 2047th occurrence of 'x' on a line.

The use of printing commands with printing suffixes (such as pn, lp, and so on) was made unspecified because BSD-based systems allow this, whereas System V does not.

Some BSD-based systems exit immediately upon receipt of end-of-file if all of the lines in the file have been deleted. Since this volume of IEEE Std 1003.1-2001 refers to the q command in this instance, such behavior is not allowed.

Some historical implementations returned exit status zero even if command errors had occurred; this is not allowed by this volume of IEEE Std 1003.1-2001.

Some historical implementations contained a bug that allowed a single period to be entered in input mode as <backslash> <period> <newline>. This is not allowed by ed because there is no description of escaping any of the characters in input mode; backslashes are entered into the buffer exactly as typed. The typical method of entering a single period has been to precede it with another character and then use the substitute command to delete that character.

It is difficult under some modes of some versions of historical operating system terminal drivers to distinguish between an end-of-file condition and terminal disconnect. IEEE Std 1003.1-2001 does not require implementations to distinguish between the two situations, which permits historical implementations of the ed utility on historical platforms to conform. Implementations are encouraged to distinguish between the two, if possible, and take appropriate action on terminal disconnect.

Historically, ed accepted a zero address for the a and r commands in order to insert text at the start of the edit buffer. When the buffer was empty the command .= returned zero. IEEE Std 1003.1-2001 requires conformance to historical practice.

For consistency with the a and r commands and better user functionality, the i and c commands must also accept an address of 0, in which case 0i is treated as 1i and likewise for the c command.

All of the following are valid addresses:

+++
Three lines after the current line.
/pattern/-
One line before the next occurrence of pattern.
-2
Two lines before the current line.
3 ---- 2
Line one (note the intermediate negative address).
1 2 3
Line six.

Any number of addresses can be provided to commands taking addresses; for example, "1,2,3,4,5p" prints lines 4 and 5, because two is the greatest valid number of addresses accepted by the print command. This, in combination with the semicolon delimiter, permits users to create commands based on ordered patterns in the file. For example, the command "3;/foo/;+2p" will display the first line after line 3 that contains the pattern foo, plus the next two lines. Note that the address "3;" must still be evaluated before being discarded, because the search origin for the "/foo/" command depends on this.

Historically, ed disallowed address chains, as discussed above, consisting solely of comma or semicolon separators; for example, ",,," or ";;;" were considered an error. For consistency of address specification, this restriction is removed. The following table lists some of the address forms now possible:
Address | Addr1 | Addr2 | Status | Comment
7, | 7 | 7 | Historical |
7,5, | 5 | 5 | Historical |
7,5,9 | 5 | 9 | Historical |
7,9 | 7 | 9 | Historical |
7,+ | 7 | 8 | Historical |
, | 1 | $ | Historical |
,7 | 1 | 7 | Extension |
,, | $ | $ | Extension |
,; | $ | $ | Extension |
7; | 7 | 7 | Historical |
7;5; | 5 | 5 | Historical |
7;5;9 | 5 | 9 | Historical |
7;5,9 | 5 | 9 | Historical |
7;$;4 | $ | 4 | Historical | Valid, but erroneous.
7;9 | 7 | 9 | Historical |
7;+ | 7 | 8 | Historical |
; | . | $ | Historical |
;7 | . | 7 | Extension |
;; | $ | $ | Extension |
;, | $ | $ | Extension |

Historically, values could be added to addresses by including them after one or more <blank>s; for example, "3 - 5p" wrote the seventh line of the file, and "/foo/ 5" was the same as "5 /foo/" . However, only absolute values could be added; for example, "5 /foo/" was an error. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, ed accepted the '^' character as an address, in which case it was identical to the hyphen character. IEEE Std 1003.1-2001 does not require or prohibit this behavior.

FUTURE DIRECTIONS

None.

SEE ALSO

Utility Description Defaults , ex , sed , sh , vi

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


du(1p)

DU

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

du - estimate file space usage

SYNOPSIS

du [-a | -s][-kx][-H | -L][file ...]

DESCRIPTION

By default, the du utility shall write to standard output the size of the file space allocated to, and the size of the file space allocated to each subdirectory of, the file hierarchy rooted in each of the specified files. By default, when a symbolic link is encountered on the command line or in the file hierarchy, du shall count the size of the symbolic link (rather than the file referenced by the link), and shall not follow the link to another portion of the file hierarchy. The size of the file space allocated to a file of type directory shall be defined as the sum total of space allocated to all files in the file hierarchy rooted in the directory plus the space allocated to the directory itself.

When du cannot stat() files or stat() or read directories, it shall report an error condition and the final exit status is affected. Files with multiple links shall be counted and written for only one entry. The directory entry that is selected in the report is unspecified. By default, file sizes shall be written in 512-byte units, rounded up to the next 512-byte unit.

OPTIONS

The du utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
In addition to the default output, report the size of each file not of type directory in the file hierarchy rooted in the specified file. Regardless of the presence of the -a option, non-directories given as file operands shall always be listed.
-H
If a symbolic link is specified on the command line, du shall count the size of the file or file hierarchy referenced by the link.
-k
Write the files sizes in units of 1024 bytes, rather than the default 512-byte units.
-L
If a symbolic link is specified on the command line or encountered during the traversal of a file hierarchy, du shall count the size of the file or file hierarchy referenced by the link.
-s
Instead of the default output, report only the total sum for each of the specified files.
-x
When evaluating file sizes, evaluate only those files that have the same device as the file specified by the file operand.

Specifying more than one of the mutually-exclusive options -H and -L shall not be considered an error. The last option specified shall determine the behavior of the utility.

OPERANDS

The following operand shall be supported:

file
The pathname of a file whose size is to be written. If no file is specified, the current directory shall be used.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of du:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The output from du shall consist of the amount of space allocated to a file and the name of the file, in the following format:

"%d %s\n", <size>, <pathname>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The use of 512-byte units is historical practice and maintains compatibility with ls and other utilities in this volume of IEEE Std 1003.1-2001. This does not mandate that the file system itself be based on 512-byte blocks. The -k option was added as a compromise measure. It was agreed by the standard developers that 512 bytes was the best default unit because of its complete historical consistency on System V (versus the mixed 512/1024-byte usage on BSD systems), and that a -k option to switch to 1024-byte units was a good compromise. Users who prefer the 1024-byte quantity can easily alias du to du -k without breaking the many historical scripts relying on the 512-byte units.

The -b option was added to an early proposal to provide a resolution to the situation where System V and BSD systems give figures for file sizes in blocks, which is an implementation-defined concept. (In common usage, the block size is 512 bytes for System V and 1024 bytes for BSD systems.) However, -b was later deleted, since the default was eventually decided as 512-byte units.

Historical file systems provided no way to obtain exact figures for the space allocation given to files. There are two known areas of inaccuracies in historical file systems: cases of indirect blocks being used by the file system or sparse files yielding incorrectly high values. An indirect block is space used by the file system in the storage of the file, but that need not be counted in the space allocated to the file. A sparse file is one in which an lseek() call has been made to a position beyond the end of the file and data has subsequently been written at that point. A file system need not allocate all the intervening zero-filled blocks to such a file. It is up to the implementation to define exactly how accurate its methods are.

The -a and -s options were mutually-exclusive in the original version of du. The POSIX Shell and Utilities description is implied by the language in the SVID where -s is described as causing "only the grand total" to be reported. Some systems may produce output for -sa, but a Strictly Conforming POSIX Shell and Utilities Application cannot use that combination.

The -a and -s options were adopted from the SVID except that the System V behavior of not listing non-directories explicitly given as operands, unless the -a option is specified, was considered a bug; the BSD-based behavior (report for all operands) is mandated. The default behavior of du in the SVID with regard to reporting the failure to read files (it produces no messages) was considered counter-intuitive, and thus it was specified that the POSIX Shell and Utilities default behavior shall be to produce such messages. These messages can be turned off with shell redirection to achieve the System V behavior.

The -x option is historical practice on recent BSD systems. It has been adopted by this volume of IEEE Std 1003.1-2001 because there was no other historical method of limiting the du search to a single file hierarchy. This limitation of the search is necessary to make it possible to obtain file space usage information about a file system on which other file systems are mounted, without having to resort to a lengthy find and awk script.

FUTURE DIRECTIONS

None.

SEE ALSO

ls , the System Interfaces volume of IEEE Std 1003.1-2001, stat()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fc(1p)

FC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fc - process the command history list

SYNOPSIS

fc [-r][-e editor] [first[last]]

fc -l[-nr] [first[last]]

fc -s[old=new][first]

DESCRIPTION

The fc utility shall list, or shall edit and re-execute, commands previously entered to an interactive sh.

The command history list shall reference commands by number. The first number in the list is selected arbitrarily. The relationship of a number to its command shall not change except when the user logs in and no other process is accessing the list, at which time the system may reset the numbering to start the oldest retained command at another number (usually 1). When the number reaches an implementation-defined upper limit, which shall be no smaller than the value in HISTSIZE or 32767 (whichever is greater), the shell may wrap the numbers, starting the next command with a lower number (usually 1). However, despite this optional wrapping of numbers, fc shall maintain the time-ordering sequence of the commands. For example, if four commands in sequence are given the numbers 32766, 32767, 1 (wrapped), and 2 as they are executed, command 32767 is considered the command previous to 1, even though its number is higher.

When commands are edited (when the -l option is not specified), the resulting lines shall be entered at the end of the history list and then re-executed by sh. The fc command that caused the editing shall not be entered into the history list. If the editor returns a non-zero exit status, this shall suppress the entry into the history list and the command re-execution. Any command line variable assignments or redirection operators used with fc shall affect both the fc command itself as well as the command that results; for example:

fc -s -- -1 2>/dev/null

reinvokes the previous command, suppressing standard error for both fc and the previous command.

OPTIONS

The fc utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-e editor
Use the editor named by editor to edit the commands. The editor string is a utility name, subject to search via the PATH variable (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables). The value in the FCEDIT variable shall be used as a default when -e is not specified. If FCEDIT is null or unset, ed shall be used as the editor.
-l
(The letter ell.) List the commands rather than invoking an editor on them. The commands shall be written in the sequence indicated by the first and last operands, as affected by -r, with each command preceded by the command number.
-n
Suppress command numbers when listing with -l.
-r
Reverse the order of the commands listed (with -l) or edited (with neither -l nor -s).
-s
Re-execute the command without invoking an editor.

OPERANDS

The following operands shall be supported:

first, last
Select the commands to list or edit. The number of previous commands that can be accessed shall be determined by the value of the HISTSIZE variable. The value of first or last or both shall be one of the following:
[+]number
A positive number representing a command number; command numbers can be displayed with the -l option.
-number
A negative decimal number representing the command that was executed number of commands previously. For example, -1 is the immediately previous command.
string
A string indicating the most recently entered command that begins with that string. If the old= new operand is not also specified with -s, the string form of the first operand cannot contain an embedded equal sign.

When the synopsis form with -s is used:

*
If first is omitted, the previous command shall be used.

For the synopsis forms without -s:

*
If last is omitted, last shall default to the previous command when -l is specified; otherwise, it shall default to first.

*
If first and last are both omitted, the previous 16 commands shall be listed or the previous single command shall be edited (based on the -l option).

*
If first and last are both present, all of the commands from first to last shall be edited (without -l) or listed (with -l). Editing multiple commands shall be accomplished by presenting to the editor all of the commands at one time, each command starting on a new line. If first represents a newer command than last, the commands shall be listed or edited in reverse sequence, equivalent to using -r. For example, the following commands on the first line are equivalent to the corresponding commands on the second:

fc -r 10 20    fc    30 40
fc    20 10    fc -r 40 30

*
When a range of commands is used, it shall not be an error to specify first or last values that are not in the history list; fc shall substitute the value representing the oldest or newest command in the list, as appropriate. For example, if there are only ten commands in the history list, numbered 1 to 10:

fc -l
fc 1 99

shall list and edit, respectively, all ten commands.

old=new
Replace the first occurrence of string old in the commands to be re-executed by the string new.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of fc:

FCEDIT
This variable, when expanded by the shell, shall determine the default value for the -e editor option's editor option-argument. If FCEDIT is null or unset, ed shall be used as the editor.
HISTFILE
Determine a pathname naming a command history file. If the HISTFILE variable is not set, the shell may attempt to access or create a file .sh_history in the directory referred to by the HOME environment variable. If the shell cannot obtain both read and write access to, or create, the history file, it shall use an unspecified mechanism that allows the history to operate properly. (References to history "file" in this section shall be understood to mean this unspecified mechanism in such cases.) An implementation may choose to access this variable only when initializing the history file; this initialization shall occur when fc or sh first attempt to retrieve entries from, or add entries to, the file, as the result of commands issued by the user, the file named by the ENV variable, or implementation-defined system start-up files. In some historical shells, the history file is initialized just after the ENV file has been processed. Therefore, it is implementation-defined whether changes made to HISTFILE after the history file has been initialized are effective. Implementations may choose to disable the history list mechanism for users with appropriate privileges who do not set HISTFILE ; the specific circumstances under which this occurs are implementation-defined. If more than one instance of the shell is using the same history file, it is unspecified how updates to the history file from those shells interact. As entries are deleted from the history file, they shall be deleted oldest first. It is unspecified when history file entries are physically removed from the history file.
HISTSIZE
Determine a decimal number representing the limit to the number of previous commands that are accessible. If this variable is unset, an unspecified default greater than or equal to 128 shall be used. The maximum number of commands in the history list is unspecified, but shall be at least 128. An implementation may choose to access this variable only when initializing the history file, as described under HISTFILE . Therefore, it is unspecified whether changes made to HISTSIZE after the history file has been initialized are effective.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

When the -l option is used to list commands, the format of each command in the list shall be as follows:

"%d\t%s\n", <line number>, <command>

If both the -l and -n options are specified, the format of each command shall be:

"\t%s\n", <command>

If the <command> consists of more than one line, the lines after the first shall be displayed as:

"\t%s\n", <continued-command>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion of the listing.
>0
An error occurred.

Otherwise, the exit status shall be that of the commands executed by fc.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since editors sometimes use file descriptors as integral parts of their editing, redirecting their file descriptors as part of the fc command can produce unexpected results. For example, if vi is the FCEDIT editor, the command:

fc -s | more

does not work correctly on many systems.

Users on windowing systems may want to have separate history files for each window by setting HISTFILE as follows:

HISTFILE=$HOME/.sh_hist$$

EXAMPLES

None.

RATIONALE

This utility is based on the fc built-in of the KornShell.

An early proposal specified the -e option as [-e editor [ old = new ]], which is not historical practice. Historical practice in fc of either [-e editor ] or [-e - [ old = new ]] is acceptable, but not both together. To clarify this, a new option -s was introduced replacing the [-e -]. This resolves the conflict and makes fc conform to the Utility Syntax Guidelines.

HISTFILE
Some implementations of the KornShell check for the superuser and do not create a history file unless HISTFILE is set. This is done primarily to avoid creating unlinked files in the root file system when logging in during single-user mode. HISTFILE must be set for the superuser to have history.
HISTSIZE
Needed to limit the size of history files. It is the intent of the standard developers that when two shells share the same history file, commands that are entered in one shell shall be accessible by the other shell. Because of the difficulties of synchronization over a network, the exact nature of the interaction is unspecified.

The initialization process for the history file can be dependent on the system start-up files, in that they may contain commands that effectively preempt the settings the user has for HISTFILE and HISTSIZE . For example, function definition commands are recorded in the history file. If the system administrator includes function definitions in some system start-up file called before the ENV file, the history file is initialized before the user can influence its characteristics. In some historical shells, the history file is initialized just after the ENV file has been processed. Because of these situations, the text requires the initialization process to be implementation-defined.

Consideration was given to omitting the fc utility in favor of the command line editing feature in sh. For example, in vi editing mode, typing "<ESC> v" is equivalent to:

EDITOR=vi fc

However, the fc utility allows the user the flexibility to edit multiple commands simultaneously (such as fc 10 20) and to use editors other than those supported by sh for command line editing.

In the KornShell, the alias r (``re-do") is preset to fc -e - (equivalent to the POSIX fc -s). This is probably an easier command name to remember than fc (``fix command"), but it does not meet the Utility Syntax Guidelines. Renaming fc to hist or redo was considered, but since this description closely matches historical KornShell practice already, such a renaming was seen as gratuitous. Users are free to create aliases whenever odd historical names such as fc, awk, cat, grep, or yacc are standardized by POSIX.

Command numbers have no ordering effects; they are like serial numbers. The -r option and -number operand address the sequence of command execution, regardless of serial numbers. So, for example, if the command number wrapped back to 1 at some arbitrary point, there would be no ambiguity associated with traversing the wrap point. For example, if the command history were:

32766: echo 1
32767: echo 2
1: echo 3

the number -2 refers to command 32767 because it is the second previous command, regardless of serial number.

FUTURE DIRECTIONS

None.

SEE ALSO

sh

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fg(1p)

FG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fg - run jobs in the foreground

SYNOPSIS

fg [job_id]

DESCRIPTION

If job control is enabled (see the description of set -m), the fg utility shall move a background job from the current environment (see Shell Execution Environment ) into the foreground.

Using fg to place a job into the foreground shall remove its process ID from the list of those "known in the current shell execution environment''; see Asynchronous Lists .

OPTIONS

None.

OPERANDS

The following operand shall be supported:

job_id
Specify the job to be run as a foreground job. If no job_id operand is given, the job_id for the job that was most recently suspended, placed in the background, or run as a background job shall be used. The format of job_id is described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.203, Job Control Job ID.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of fg:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The fg utility shall write the command line of the job to standard output in the following format:

"%s\n", <command>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If job control is disabled, the fg utility shall exit with an error and no job shall be placed in the foreground.

The following sections are informative.

APPLICATION USAGE

The fg utility does not work as expected when it is operating in its own utility execution environment because that environment has no applicable jobs to manipulate. See the APPLICATION USAGE section for bg . For this reason, fg is generally implemented as a shell regular built-in.

EXAMPLES

None.

RATIONALE

The extensions to the shell specified in this volume of IEEE Std 1003.1-2001 have mostly been based on features provided by the KornShell. The job control features provided by bg, fg, and jobs are also based on the KornShell. The standard developers examined the characteristics of the C shell versions of these utilities and found that differences exist. Despite widespread use of the C shell, the KornShell versions were selected for this volume of IEEE Std 1003.1-2001 to maintain a degree of uniformity with the rest of the KornShell features selected (such as the very popular command line editing features).

FUTURE DIRECTIONS

None.

SEE ALSO

Asynchronous Lists , Shell Execution Environment , bg , kill() , jobs , wait()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ex(1p)

EX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ex - text editor

SYNOPSIS

ex [-rR][-s | -v][-c command][-t tagstring][-w size][file ...]

DESCRIPTION

The ex utility is a line-oriented text editor. There are two other modes of the editor-open and visual-in which screen-oriented editing is available. This is described more fully by the ex open and visual commands and in vi .

This section uses the term edit buffer to describe the current working text. No specific implementation is implied by this term. All editing changes are performed on the edit buffer, and no changes to it shall affect any file until an editor command writes the file.

Certain terminals do not have all the capabilities necessary to support the complete ex definition, such as the full-screen editing commands ( visual mode or open mode). When these commands cannot be supported on such terminals, this condition shall not produce an error message such as "not an editor command" or report a syntax error. The implementation may either accept the commands and produce results on the screen that are the result of an unsuccessful attempt to meet the requirements of this volume of IEEE Std 1003.1-2001 or report an error describing the terminal-related deficiency.

OPTIONS

The ex utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c command
Specify an initial command to be executed in the first edit buffer loaded from an existing file (see the EXTENDED DESCRIPTION section). Implementations may support more than a single -c option. In such implementations, the specified commands shall be executed in the order specified on the command line.
-r
Recover the named files (see the EXTENDED DESCRIPTION section). Recovery information for a file shall be saved during an editor or system crash (for example, when the editor is terminated by a signal which the editor can catch), or after the use of an ex preserve command.

A crash in this context is an unexpected failure of the system or utility that requires restarting the failed system or utility. A system crash implies that any utilities running at the time also crash. In the case of an editor or system crash, the number of changes to the edit buffer (since the most recent preserve command) that will be recovered is unspecified.

If no file operands are given and the -t option is not specified, all other options, the EXINIT variable, and any .exrc files shall be ignored; a list of all recoverable files available to the invoking user shall be written, and the editor shall exit normally without further action.

-R
Set readonly edit option.
-s
Prepare ex for batch use by taking the following actions:
*
Suppress writing prompts and informational (but not diagnostic) messages.

*
Ignore the value of TERM and any implementation default terminal type and assume the terminal is a type incapable of supporting open or visual modes; see the visual command and the description of vi .

*
Suppress the use of the EXINIT environment variable and the reading of any .exrc file; see the EXTENDED DESCRIPTION section.

*
Suppress autoindentation, ignoring the value of the autoindent edit option.

-t tagstring
Edit the file containing the specified tagstring; see ctags . The tags feature represented by -t tagstring and the tag command is optional. It shall be provided on any system that also provides a conforming implementation of ctags; otherwise, the use of -t produces undefined results. On any system, it shall be an error to specify more than a single -t option.
-v
Begin in visual mode (see vi ).
-w size
Set the value of the window editor option to size.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be edited.

STDIN

The standard input consists of a series of commands and input text, as described in the EXTENDED DESCRIPTION section. The implementation may limit each line of standard input to a length of {LINE_MAX}.

If the standard input is not a terminal device, it shall be as if the -s option had been specified.

If a read from the standard input returns an error, or if the editor detects an end-of-file condition from the standard input, it shall be equivalent to a SIGHUP asynchronous event.

INPUT FILES

Input files shall be text files or files that would be text files except for an incomplete last line that is not longer than {LINE_MAX}-1 bytes in length and contains no NUL characters. By default, any incomplete last line shall be treated as if it had a trailing <newline>. The editing of other forms of files may optionally be allowed by ex implementations.

The .exrc files and source files shall be text files consisting of ex commands; see the EXTENDED DESCRIPTION section.

By default, the editor shall read lines from the files to be edited without interpreting any of those lines as any form of editor command.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ex:

COLUMNS
Override the system-selected horizontal screen size. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables for valid values and results when it is unset or null.
EXINIT
Determine a list of ex commands that are executed on editor start-up. See the EXTENDED DESCRIPTION section for more details of the initialization phase.
HOME
Determine a pathname of a directory that shall be searched for an editor start-up file named .exrc; see the EXTENDED DESCRIPTION section.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the behavior of character classes within regular expressions, the classification of characters as uppercase or lowercase letters, the case conversion of letters, and the detection of word boundaries.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LINES
Override the system-selected vertical screen size, used as the number of lines in a screenful and the vertical screen size in visual mode. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables for valid values and results when it is unset or null.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the search path for the shell command specified in the ex editor commands !, shell, read, and write, and the open and visual mode command !; see the description of command search and execution in Command Search and Execution .
SHELL
Determine the preferred command line interpreter for use as the default value of the shell edit option.
TERM
Determine the name of the terminal type. If this variable is unset or null, an unspecified default terminal type shall be used.

ASYNCHRONOUS EVENTS

The following term is used in this and following sections to specify command and asynchronous event actions:

complete write

A complete write is a write of the entire contents of the edit buffer to a file of a type other than a terminal device, or the saving of the edit buffer caused by the user executing the ex preserve command. Writing the contents of the edit buffer to a temporary file that will be removed when the editor exits shall not be considered a complete write.

The following actions shall be taken upon receipt of signals:

SIGINT
If the standard input is not a terminal device, ex shall not write the file or return to command or text input mode, and shall exit with a non-zero exit status.

Otherwise, if executing an open or visual text input mode command, ex in receipt of SIGINT shall behave identically to its receipt of the <ESC> character.

Otherwise:

1.
If executing an ex text input mode command, all input lines that have been completely entered shall be resolved into the edit buffer, and any partially entered line shall be discarded.

2.
If there is a currently executing command, it shall be aborted and a message displayed. Unless otherwise specified by the ex or vi command descriptions, it is unspecified whether any lines modified by the executing command appear modified, or as they were before being modified by the executing command, in the buffer.

If the currently executing command was a motion command, its associated command shall be discarded.

3.
If in open or visual command mode, the terminal shall be alerted.

4.
The editor shall then return to command mode.

SIGCONT
The screen shall be refreshed if in open or visual mode.
SIGHUP
If the edit buffer has been modified since the last complete write, ex shall attempt to save the edit buffer so that it can be recovered later using the -r option or the ex recover command. The editor shall not write the file or return to command or text input mode, and shall terminate with a non-zero exit status.
SIGTERM
Refer to SIGHUP.

The action taken for all other signals is unspecified.

STDOUT

The standard output shall be used only for writing prompts to the user, for informational messages, and for writing lines from the file.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output from ex shall be text files.

EXTENDED DESCRIPTION

Only the ex mode of the editor is described in this section. See vi for additional editing capabilities available in ex.

When an error occurs, ex shall write a message. If the terminal supports a standout mode (such as inverse video), the message shall be written in standout mode. If the terminal does not support a standout mode, and the edit option errorbells is set, an alert action shall precede the error message.

By default, ex shall start in command mode, which shall be indicated by a : prompt; see the prompt command. Text input mode can be entered by the append, insert, or change commands; it can be exited (and command mode re-entered) by typing a period ( '.' ) alone at the beginning of a line.

Initialization in ex and vi

The following symbols are used in this and following sections to specify locations in the edit buffer:

alternate and current pathnames

Two pathnames, named current and alternate, are maintained by the editor. Any ex commands that take filenames as arguments shall set them as follows:

1.
If a file argument is specified to the ex edit, ex, or recover commands, or if an ex tag command replaces the contents of the edit buffer.
a.
If the command replaces the contents of the edit buffer, the current pathname shall be set to the file argument or the file indicated by the tag, and the alternate pathname shall be set to the previous value of the current pathname.

b.
Otherwise, the alternate pathname shall be set to the file argument.

2.
If a file argument is specified to the ex next command:
a.
If the command replaces the contents of the edit buffer, the current pathname shall be set to the first file argument, and the alternate pathname shall be set to the previous value of the current pathname.

3.
If a file argument is specified to the ex file command, the current pathname shall be set to the file argument, and the alternate pathname shall be set to the previous value of the current pathname.

4.
If a file argument is specified to the ex read and write commands (that is, when reading or writing a file, and not to the program named by the shell edit option), or a file argument is specified to the ex xit command:
a.
If the current pathname has no value, the current pathname shall be set to the file argument.

b.
Otherwise, the alternate pathname shall be set to the file argument.

If the alternate pathname is set to the previous value of the current pathname when the current pathname had no previous value, then the alternate pathname shall have no value as a result.

current line

The line of the edit buffer referenced by the cursor. Each command description specifies the current line after the command has been executed, as the current line value. When the edit buffer contains no lines, the current line shall be zero; see Addressing in ex .

current column

The current display line column occupied by the cursor. (The columns shall be numbered beginning at 1.) Each command description specifies the current column after the command has been executed, as the current column value. This column is an ideal column that is remembered over the lifetime of the editor. The actual display line column upon which the cursor rests may be different from the current column; see the cursor positioning discussion in Command Descriptions in vi .

set to non-<blank>

A description for a current column value, meaning that the current column shall be set to the last display line column on which is displayed any part of the first non- <blank> of the line. If the line has no non- <blank> non- <newline>s, the current column shall be set to the last display line column on which is displayed any part of the last non- <newline> in the line. If the line is empty, the current column shall be set to column position 1.

The length of lines in the edit buffer may be limited to {LINE_MAX} bytes. In open and visual mode, the length of lines in the edit buffer may be limited to the number of characters that will fit in the display. If either limit is exceeded during editing, an error message shall be written. If either limit is exceeded by a line read in from a file, an error message shall be written and the edit session may be terminated.

If the editor stops running due to any reason other than a user command, and the edit buffer has been modified since the last complete write, it shall be equivalent to a SIGHUP asynchronous event. If the system crashes, it shall be equivalent to a SIGHUP asynchronous event.

During initialization (before the first file is copied into the edit buffer or any user commands from the terminal are processed) the following shall occur:

1.
If the environment variable EXINIT is set, the editor shall execute the ex commands contained in that variable.

2.
If the EXINIT variable is not set, and all of the following are true:
a.
The HOME environment variable is not null and not empty.

b.
The file .exrc in the directory referred to by the HOME environment variable:
1.
Exists

2.
Is owned by the same user ID as the real user ID of the process or the process has appropriate privileges

3.
Is not writable by anyone other than the owner

the editor shall execute the ex commands contained in that file.

3.
If and only if all of the following are true:
a.
The current directory is not referred to by the HOME environment variable.

b.
A command in the EXINIT environment variable or a command in the .exrc file in the directory referred to by the HOME environment variable sets the editor option exrc.

c.
The .exrc file in the current directory:
1.
Exists

2.
Is owned by the same user ID as the real user ID of the process, or by one of a set of implementation-defined user IDs

3.
Is not writable by anyone other than the owner

the editor shall attempt to execute the ex commands contained in that file.

Lines in any .exrc file that are blank lines shall be ignored. If any .exrc file exists, but is not read for ownership or permission reasons, it shall be an error.

After the EXINIT variable and any .exrc files are processed, the first file specified by the user shall be edited, as follows:

1.
If the user specified the -t option, the effect shall be as if the ex tag command was entered with the specified argument, with the exception that if tag processing does not result in a file to edit, the effect shall be as described in step 3. below.

2.
Otherwise, if the user specified any command line file arguments, the effect shall be as if the ex edit command was entered with the first of those arguments as its file argument.

3.
Otherwise, the effect shall be as if the ex edit command was entered with a nonexistent filename as its file argument. It is unspecified whether this action shall set the current pathname. In an implementation where this action does not set the current pathname, any editor command using the current pathname shall fail until an editor command sets the current pathname.

If the -r option was specified, the first time a file in the initial argument list or a file specified by the -t option is edited, if recovery information has previously been saved about it, that information shall be recovered and the editor shall behave as if the contents of the edit buffer have already been modified. If there are multiple instances of the file to be recovered, the one most recently saved shall be recovered, and an informational message that there are previous versions of the file that can be recovered shall be written. If no recovery information about a file is available, an informational message to this effect shall be written, and the edit shall proceed as usual.

If the -c option was specified, the first time a file that already exists (including a file that might not exist but for which recovery information is available, when the -r option is specified) replaces or initializes the contents of the edit buffer, the current line shall be set to the last line of the edit buffer, the current column shall be set to non- <blank>, and the ex commands specified with the -c option shall be executed. In this case, the current line and current column shall not be set as described for the command associated with the replacement or initialization of the edit buffer contents. However, if the -t option or a tag command is associated with this action, the -c option commands shall be executed and then the movement to the tag shall be performed.

The current argument list shall initially be set to the filenames specified by the user on the command line. If no filenames are specified by the user, the current argument list shall be empty. If the -t option was specified, it is unspecified whether any filename resulting from tag processing shall be prepended to the current argument list. In the case where the filename is added as a prefix to the current argument list, the current argument list reference shall be set to that filename. In the case where the filename is not added as a prefix to the current argument list, the current argument list reference shall logically be located before the first of the filenames specified on the command line (for example, a subsequent ex next command shall edit the first filename from the command line). If the -t option was not specified, the current argument list reference shall be to the first of the filenames on the command line.

Addressing in ex

Addressing in ex relates to the current line and the current column; the address of a line is its 1-based line number, the address of a column is its 1-based count from the beginning of the line. Generally, the current line is the last line affected by a command. The current line number is the address of the current line. In each command description, the effect of the command on the current line number and the current column is described.

Addresses are constructed as follows:

1.
The character '.' (period) shall address the current line.

2.
The character '$' shall address the last line of the edit buffer.

3.
The positive decimal number n shall address the nth line of the edit buffer.

4.
The address "'x" refers to the line marked with the mark name character 'x' , which shall be a lowercase letter from the portable character set or one of the characters '`' or '" . It shall be an error if the line that was marked is not currently present in the edit buffer or the mark has not been set. Lines can be marked with the ex mark or k commands, or the vi m command.

5.
A regular expression enclosed by slashes ( '/' ) shall address the first line found by searching forwards from the line following the current line toward the end of the edit buffer and stopping at the first line for which the line excluding the terminating <newline> matches the regular expression. As stated in Regular Expressions in ex , an address consisting of a null regular expression delimited by slashes "//" shall address the next line for which the line excluding the terminating <newline> matches the last regular expression encountered. In addition, the second slash can be omitted at the end of a command line. If the wrapscan edit option is set, the search shall wrap around to the beginning of the edit buffer and continue up to and including the current line, so that the entire edit buffer is searched. Within the regular expression, the sequence "\/" shall represent a literal slash instead of the regular expression delimiter.

6.
A regular expression enclosed in question marks ( '?' ) shall address the first line found by searching backwards from the line preceding the current line toward the beginning of the edit buffer and stopping at the first line for which the line excluding the terminating <newline> matches the regular expression. An address consisting of a null regular expression delimited by question marks "??" shall address the previous line for which the line excluding the terminating <newline> matches the last regular expression encountered. In addition, the second question mark can be omitted at the end of a command line. If the wrapscan edit option is set, the search shall wrap around from the beginning of the edit buffer to the end of the edit buffer and continue up to and including the current line, so that the entire edit buffer is searched. Within the regular expression, the sequence "\?" shall represent a literal question mark instead of the RE delimiter.

7.
A plus sign ( '+' ) or a minus sign ( '-' ) followed by a decimal number shall address the current line plus or minus the number. A '+' or '-' not followed by a decimal number shall address the current line plus or minus 1.

Addresses can be followed by zero or more address offsets, optionally <blank>-separated. Address offsets are constructed as follows:

1.
A '+' or '-' immediately followed by a decimal number shall add (subtract) the indicated number of lines to (from) the address. A '+' or '-' not followed by a decimal number shall add (subtract) 1 to (from) the address.

2.
A decimal number shall add the indicated number of lines to the address.

It shall not be an error for an intermediate address value to be less than zero or greater than the last line in the edit buffer. It shall be an error for the final address value to be less than zero or greater than the last line in the edit buffer.

Commands take zero, one, or two addresses; see the descriptions of 1addr and 2addr in Command Descriptions in ex . If more than the required number of addresses are provided to a command that requires zero addresses, it shall be an error. Otherwise, if more than the required number of addresses are provided to a command, the addresses specified first shall be evaluated and then discarded until the maximum number of valid addresses remain.

Addresses shall be separated from each other by a comma ( ',' ) or a semicolon ( ';' ). If no address is specified before or after a comma or semicolon separator, it shall be as if the address of the current line was specified before or after the separator. In the case of a semicolon separator, the current line ( '.' ) shall be set to the first address, and only then will the next address be calculated. This feature can be used to determine the starting line for forwards and backwards searches (see rules 5. and 6.).

A percent sign ( '%' ) shall be equivalent to entering the two addresses "1,$" .

Any delimiting <blank>s between addresses, address separators, or address offsets shall be discarded.

Command Line Parsing in ex

The following symbol is used in this and following sections to describe parsing behavior:

escape
If a character is referred to as "backslash-escaped" or " <control>-V-escaped," it shall mean that the character acquired or lost a special meaning by virtue of being preceded, respectively, by a backslash or <control>-V character. Unless otherwise specified, the escaping character shall be discarded at that time and shall not be further considered for any purpose.

Command-line parsing shall be done in the following steps. For each step, characters already evaluated shall be ignored; that is, the phrase "leading character" refers to the next character that has not yet been evaluated.

1.
Leading colon characters shall be skipped.

2.
Leading <blank>s shall be skipped.

3.
If the leading character is a double-quote character, the characters up to and including the next non-backslash-escaped <newline> shall be discarded, and any subsequent characters shall be parsed as a separate command.

4.
Leading characters that can be interpreted as addresses shall be evaluated; see Addressing in ex .

5.
Leading <blank>s shall be skipped.

6.
If the next character is a vertical-line character or a <newline>:
a.
If the next character is a <newline>:
1.
If ex is in open or visual mode, the current line shall be set to the last address specified, if any.

2.
Otherwise, if the last command was terminated by a vertical-line character, no action shall be taken; for example, the command "||<newline>" shall execute two implied commands, not three.

3.
Otherwise, step 6.b. shall apply.

b.
Otherwise, the implied command shall be the print command. The last #, p, and l flags specified to any ex command shall be remembered and shall apply to this implied command. Executing the ex number, print, or list command shall set the remembered flags to #, nothing, and l, respectively, plus any other flags specified for that execution of the number, print, or list command.

If ex is not currently performing a global or v command, and no address or count is specified, the current line shall be incremented by 1 before the command is executed. If incrementing the current line would result in an address past the last line in the edit buffer, the command shall fail, and the increment shall not happen.

c.
The <newline> or vertical-line character shall be discarded and any subsequent characters shall be parsed as a separate command.

7.
The command name shall be comprised of the next character (if the character is not alphabetic), or the next character and any subsequent alphabetic characters (if the character is alphabetic), with the following exceptions:
a.
Commands that consist of any prefix of the characters in the command name delete, followed immediately by any of the characters 'l' , 'p' , '+' , '-' , or '#' shall be interpreted as a delete command, followed by a <blank>, followed by the characters that were not part of the prefix of the delete command. The maximum number of characters shall be matched to the command name delete; for example, "del" shall not be treated as "de" followed by the flag l.

b.
Commands that consist of the character 'k' , followed by a character that can be used as the name of a mark, shall be equivalent to the mark command followed by a <blank>, followed by the character that followed the 'k' .

c.
Commands that consist of the character 's' , followed by characters that could be interpreted as valid options to the s command, shall be the equivalent of the s command, without any pattern or replacement values, followed by a <blank>, followed by the characters after the 's' .

8.
The command name shall be matched against the possible command names, and a command name that contains a prefix matching the characters specified by the user shall be the executed command. In the case of commands where the characters specified by the user could be ambiguous, the executed command shall be as follows:
a append n next t t
c change p print u undo
ch change pr print un undo
e edit r read v v
m move re read w write
ma mark s s

Implementation extensions with names causing similar ambiguities shall not be checked for a match until all possible matches for commands specified by IEEE Std 1003.1-2001 have been checked.

9.
If the command is a ! command, or if the command is a read command followed by zero or more <blank>s and a !, or if the command is a write command followed by one or more <blank>s and a !, the rest of the command shall include all characters up to a non-backslash-escaped <newline>. The <newline> shall be discarded and any subsequent characters shall be parsed as a separate ex command.

10.
Otherwise, if the command is an edit, ex, or next command, or a visual command while in open or visual mode, the next part of the command shall be parsed as follows:
a.
Any '!' character immediately following the command shall be skipped and be part of the command.

b.
Any leading <blank>s shall be skipped and be part of the command.

c.
If the next character is a '+' , characters up to the first non-backslash-escaped <newline> or non-backslash-escaped <blank> shall be skipped and be part of the command.

d.
The rest of the command shall be determined by the steps specified in paragraph 12.

11.
Otherwise, if the command is a global, open, s, or v command, the next part of the command shall be parsed as follows:
a.
Any leading <blank>s shall be skipped and be part of the command.

b.
If the next character is not an alphanumeric, double-quote, <newline>, backslash, or vertical-line character:
1.
The next character shall be used as a command delimiter.

2.
If the command is a global, open, or v command, characters up to the first non-backslash-escaped <newline>, or first non-backslash-escaped delimiter character, shall be skipped and be part of the command.

3.
If the command is an s command, characters up to the first non-backslash-escaped <newline>, or second non-backslash-escaped delimiter character, shall be skipped and be part of the command.

c.
If the command is a global or v command, characters up to the first non-backslash-escaped <newline> shall be skipped and be part of the command.

d.
Otherwise, the rest of the command shall be determined by the steps specified in paragraph 12.

12.
Otherwise:
a.
If the command was a map, unmap, abbreviate, or unabbreviate command, characters up to the first non- <control>-V-escaped <newline>, vertical-line, or double-quote character shall be skipped and be part of the command.

b.
Otherwise, characters up to the first non-backslash-escaped <newline>, vertical-line, or double-quote character shall be skipped and be part of the command.

c.
If the command was an append, change, or insert command, and the step 12.b. ended at a vertical-line character, any subsequent characters, up to the next non-backslash-escaped <newline> shall be used as input text to the command.

d.
If the command was ended by a double-quote character, all subsequent characters, up to the next non-backslash-escaped <newline>, shall be discarded.

e.
The terminating <newline> or vertical-line character shall be discarded and any subsequent characters shall be parsed as a separate ex command.

Command arguments shall be parsed as described by the Synopsis and Description of each individual ex command. This parsing shall not be <blank>-sensitive, except for the ! argument, which must follow the command name without intervening <blank>s, and where it would otherwise be ambiguous. For example, count and flag arguments need not be <blank>-separated because "d22p" is not ambiguous, but file arguments to the ex next command must be separated by one or more <blank>s. Any <blank> in command arguments for the abbreviate, unabbreviate, map, and unmap commands can be <control>-V-escaped, in which case the <blank> shall not be used as an argument delimiter. Any <blank> in the command argument for any other command can be backslash-escaped, in which case that <blank> shall not be used as an argument delimiter.

Within command arguments for the abbreviate, unabbreviate, map, and unmap commands, any character can be <control>-V-escaped. All such escaped characters shall be treated literally and shall have no special meaning. Within command arguments for all other ex commands that are not regular expressions or replacement strings, any character that would otherwise have a special meaning can be backslash-escaped. Escaped characters shall be treated literally, without special meaning as shell expansion characters or '!' , '%' , and '#' expansion characters. See Regular Expressions in ex and Replacement Strings in ex for descriptions of command arguments that are regular expressions or replacement strings.

Non-backslash-escaped '%' characters appearing in file arguments to any ex command shall be replaced by the current pathname; unescaped '#' characters shall be replaced by the alternate pathname. It shall be an error if '%' or '#' characters appear unescaped in an argument and their corresponding values are not set.

Non-backslash-escaped '!' characters in the arguments to either the ex ! command or the open and visual mode ! command, or in the arguments to the ex read command, where the first non- <blank> after the command name is a '!' character, or in the arguments to the ex write command where the command name is followed by one or more <blank>s and the first non- <blank> after the command name is a '!' character, shall be replaced with the arguments to the last of those three commands as they appeared after all unescaped '%' , '#' , and '!' characters were replaced. It shall be an error if '!' characters appear unescaped in one of these commands and there has been no previous execution of one of these commands.

If an error occurs during the parsing or execution of an ex command:

*
An informational message to this effect shall be written. Execution of the ex command shall stop, and the cursor (for example, the current line and column) shall not be further modified.

*
If the ex command resulted from a map expansion, all characters from that map expansion shall be discarded, except as otherwise specified by the map command.

*
Otherwise, if the ex command resulted from the processing of an EXINIT environment variable, a .exrc file, a :source command, a -c option, or a + command specified to an ex edit, ex, next, or visual command, no further commands from the source of the commands shall be executed.

*
Otherwise, if the ex command resulted from the execution of a buffer or a global or v command, no further commands caused by the execution of the buffer or the global or v command shall be executed.

*
Otherwise, if the ex command was not terminated by a <newline>, all characters up to and including the next non-backslash-escaped <newline> shall be discarded.

Input Editing in ex

The following symbol is used in this and the following sections to specify command actions:

word
In the POSIX locale, a word consists of a maximal sequence of letters, digits, and underscores, delimited at both ends by characters other than letters, digits, or underscores, or by the beginning or end of a line or the edit buffer.

When accepting input characters from the user, in either ex command mode or ex text input mode, ex shall enable canonical mode input processing, as defined in the System Interfaces volume of IEEE Std 1003.1-2001.

If in ex text input mode:

1.
If the number edit option is set, ex shall prompt for input using the line number that would be assigned to the line if it is entered, in the format specified for the ex number command.

2.
If the autoindent edit option is set, ex shall prompt for input using autoindent characters, as described by the autoindent edit option. autoindent characters shall follow the line number, if any.

If in ex command mode:

1.
If the prompt edit option is set, input shall be prompted for using a single ':' character; otherwise, there shall be no prompt.

The input characters in the following sections shall have the following effects on the input line.

Scroll

Synopsis:

eof

See the description of the stty eof character in stty .

If in ex command mode: If the eof character is the first character entered on the line, the line shall be evaluated as if it contained two characters: a <control>-D and a <newline>.

Otherwise, the eof character shall have no special meaning.

If in ex text input mode: If the cursor follows an autoindent character, the autoindent characters in the line shall be modified so that a part of the next text input character will be displayed on the first column in the line after the previous shiftwidth edit option column boundary, and the user shall be prompted again for input for the same line.

Otherwise, if the cursor follows a '0' , which follows an autoindent character, and the '0' was the previous text input character, the '0' and all autoindent characters in the line shall be discarded, and the user shall be prompted again for input for the same line.

Otherwise, if the cursor follows a '^' , which follows an autoindent character, and the '^' was the previous text input character, the '^' and all autoindent characters in the line shall be discarded, and the user shall be prompted again for input for the same line. In addition, the autoindent level for the next input line shall be derived from the same line from which the autoindent level for the current input line was derived.

Otherwise, if there are no autoindent or text input characters in the line, the eof character shall be discarded.

Otherwise, the eof character shall have no special meaning.

<newline>

Synopsis:

<newline>

<control>-J

If in ex command mode: Cause the command line to be parsed; <control>-J shall be mapped to the <newline> for this purpose.

If in ex text input mode: Terminate the current line. If there are no characters other than autoindent characters on the line, all characters on the line shall be discarded.

Prompt for text input on a new line after the current line. If the autoindent edit option is set, an appropriate number of autoindent characters shall be added as a prefix to the line as described by the ex autoindent edit option.

<backslash>

Synopsis:

<backslash>

Allow the entry of a subsequent <newline> or <control>-J as a literal character, removing any special meaning that it may have to the editor during text input mode. The backslash character shall be retained and evaluated when the command line is parsed, or retained and included when the input text becomes part of the edit buffer.

<control>-V

Synopsis:

<control>-V

Allow the entry of any subsequent character as a literal character, removing any special meaning that it may have to the editor during text input mode. The <control>-V character shall be discarded before the command line is parsed or the input text becomes part of the edit buffer.

If the "literal next" functionality is performed by the underlying system, it is implementation-defined whether a character other than <control>-V performs this function.

<control>-W

Synopsis:

<control>-W

Discard the <control>-W, and the word previous to it in the input line, including any <blank>s following the word and preceding the <control>-W. If the "word erase" functionality is performed by the underlying system, it is implementation-defined whether a character other than <control>-W performs this function.

Command Descriptions in ex

The following symbols are used in this section to represent command modifiers. Some of these modifiers can be omitted, in which case the specified defaults shall be used.

1addr
A single line address, given in any of the forms described in Addressing in ex ; the default shall be the current line ( '.' ), unless otherwise specified.

If the line address is zero, it shall be an error, unless otherwise specified in the following command descriptions.

If the edit buffer is empty, and the address is specified with a command other than =, append, insert, open, put, read, or visual, or the address is not zero, it shall be an error.

2addr
Two addresses specifying an inclusive range of lines. If no addresses are specified, the default for 2addr shall be the current line only ( ".,." ), unless otherwise specified in the following command descriptions. If one address is specified, 2addr shall specify that line only, unless otherwise specified in the following command descriptions.

It shall be an error if the first address is greater than the second address.

If the edit buffer is empty, and the two addresses are specified with a command other than the !, write, wq, or xit commands, or either address is not zero, it shall be an error.

count
A positive decimal number. If count is specified, it shall be equivalent to specifying an additional address to the command, unless otherwise specified by the following command descriptions. The additional address shall be equal to the last address specified to the command (either explicitly or by default) plus count-1.

If this would result in an address greater than the last line of the edit buffer, it shall be corrected to equal the last line of the edit buffer.

flags
One or more of the characters '+' , '-' , '#' , 'p' , or 'l' (ell). The flag characters can be <blank>-separated, and in any order or combination. The characters '#' , 'p' , and 'l' shall cause lines to be written in the format specified by the print command with the specified flags.

The lines to be written are as follows:

1.
All edit buffer lines written during the execution of the ex &, ~, list, number, open, print, s, visual, and z commands shall be written as specified by flags.

2.
After the completion of an ex command with a flag as an argument, the current line shall be written as specified by flags, unless the current line was the last line written by the command.

The characters '+' and '-' cause the value of the current line after the execution of the ex command to be adjusted by the offset address as described in Addressing in ex . This adjustment shall occur before the current line is written as described in 2. above.

The default for flags shall be none.

buffer
One of a number of named areas for holding text. The named buffers are specified by the alphanumeric characters of the POSIX locale. There shall also be one "unnamed" buffer. When no buffer is specified for editor commands that use a buffer, the unnamed buffer shall be used. Commands that store text into buffers shall store the text as it was before the command took effect, and shall store text occurring earlier in the file before text occurring later in the file, regardless of how the text region was specified. Commands that store text into buffers shall store the text into the unnamed buffer as well as any specified buffer.

In ex commands, buffer names are specified as the name by itself. In open or visual mode commands the name is preceded by a double quote ( ' )' character.

If the specified buffer name is an uppercase character, and the buffer contents are to be modified, the buffer shall be appended to rather than being overwritten. If the buffer is not being modified, specifying the buffer name in lowercase and uppercase shall have identical results.

There shall also be buffers named by the numbers 1 through 9. In open and visual mode, if a region of text including characters from more than a single line is being modified by the vi c or d commands, the motion character associated with the c or d commands specifies that the buffer text shall be in line mode, or the commands %, `, /, ?, (, ), N, n, {, or } are used to define a region of text for the c or d commands, the contents of buffers 1 through 8 shall be moved into the buffer named by the next numerically greater value, the contents of buffer 9 shall be discarded, and the region of text shall be copied into buffer 1. This shall be in addition to copying the text into a user-specified buffer or unnamed buffer, or both. Numeric buffers can be specified as a source buffer for open and visual mode commands; however, specifying a numeric buffer as the write target of an open or visual mode command shall have unspecified results.

The text of each buffer shall have the characteristic of being in either line or character mode. Appending text to a non-empty buffer shall set the mode to match the characteristic of the text being appended. Appending text to a buffer shall cause the creation of at least one additional line in the buffer. All text stored into buffers by ex commands shall be in line mode. The ex commands that use buffers as the source of text specify individually how buffers of different modes are handled. Each open or visual mode command that uses buffers for any purpose specifies individually the mode of the text stored into the buffer and how buffers of different modes are handled.

file
Command text used to derive a pathname. The default shall be the current pathname, as defined previously, in which case, if no current pathname has yet been established it shall be an error, except where specifically noted in the individual command descriptions that follow. If the command text contains any of the characters '~' , '{' , '[' , '*' , '?' , '$' , '`' , '" , ' ,' and '\' , it shall be subjected to the process of "shell expansions", as described below; if more than a single pathname results and the command expects only one, it shall be an error.

The process of shell expansions in the editor shall be done as follows. The ex utility shall pass two arguments to the program named by the shell edit option; the first shall be -c, and the second shall be the string "echo" and the command text as a single argument. The standard output and standard error of that command shall replace the command text.

!
A character that can be appended to the command name to modify its operation, as detailed in the individual command descriptions. With the exception of the ex read, write, and ! commands, the '!' character shall only act as a modifier if there are no <blank>s between it and the command name.
remembered search direction

The vi commands N and n begin searching in a forwards or backwards direction in the edit buffer based on a remembered search direction, which is initially unset, and is set by the ex global, v, s, and tag commands, and the vi / and ? commands.

Abbreviate

Synopsis:

ab[breviate][lhs rhs]

If lhs and rhs are not specified, write the current list of abbreviations and do nothing more.

Implementations may restrict the set of characters accepted in lhs or rh, except that printable characters and <blank>s shall not be restricted. Additional restrictions shall be implementation-defined.

In both lhs and rhs, any character may be escaped with a <control>-V, in which case the character shall not be used to delimit lhs from rhs, and the escaping <control>-V shall be discarded.

In open and visual text input mode, if a non-word or <ESC> character that is not escaped by a <control>-V character is entered after a word character, a check shall be made for a set of characters matching lhs, in the text input entered during this command. If it is found, the effect shall be as if rhs was entered instead of lhs.

The set of characters that are checked is defined as follows:

1.
If there are no characters inserted before the word and non-word or <ESC> characters that triggered the check, the set of characters shall consist of the word character.

2.
If the character inserted before the word and non-word or <ESC> characters that triggered the check is a word character, the set of characters shall consist of the characters inserted immediately before the triggering characters that are word characters, plus the triggering word character.

3.
If the character inserted before the word and non-word or <ESC> characters that triggered the check is not a word character, the set of characters shall consist of the characters that were inserted before the triggering characters that are neither <blank>s nor word characters, plus the triggering word character.

It is unspecified whether the lhs argument entered for the ex abbreviate and unabbreviate commands is replaced in this fashion. Regardless of whether or not the replacement occurs, the effect of the command shall be as if the replacement had not occurred.

Current line: Unchanged.

Current column: Unchanged.

Append

Synopsis:

[1addr] a[ppend][!]

Enter ex text input mode; the input text shall be placed after the specified line. If line zero is specified, the text shall be placed at the beginning of the edit buffer.

This command shall be affected by the number and autoindent edit options; following the command name with '!' shall cause the autoindent edit option setting to be toggled for the duration of this command only.

Current line: Set to the last input line; if no lines were input, set to the specified line, or to the first line of the edit buffer if a line of zero was specified, or zero if the edit buffer is empty.

Current column: Set to non- <blank>.

Arguments

Synopsis:

ar[gs]

Write the current argument list, with the current argument-list entry, if any, between '[' and ']' characters.

Current line: Unchanged.

Current column: Unchanged.

Change

Synopsis:

[2addr] c[hange][!][count]

Enter ex text input mode; the input text shall replace the specified lines. The specified lines shall be copied into the unnamed buffer, which shall become a line mode buffer.

This command shall be affected by the number and autoindent edit options; following the command name with '!' shall cause the autoindent edit option setting to be toggled for the duration of this command only.

Current line: Set to the last input line; if no lines were input, set to the line before the first address, or to the first line of the edit buffer if there are no lines preceding the first address, or to zero if the edit buffer is empty.

Current column: Set to non- <blank>.

Change Directory

Synopsis:

chd[ir][!][directory]cd[!][directory]

Change the current working directory to directory.

If no directory argument is specified, and the HOME environment variable is set to a non-null and non-empty value, directory shall default to the value named in the HOME environment variable. If the HOME environment variable is empty or is undefined, the default value of directory is implementation-defined.

If no '!' is appended to the command name, and the edit buffer has been modified since the last complete write, and the current pathname does not begin with a '/' , it shall be an error.

Current line: Unchanged.

Current column: Unchanged.

Copy

Synopsis:

[2addr] co[py] 1addr [flags]
[2addr] t 1addr [flags]

Copy the specified lines after the specified destination line; line zero specifies that the lines shall be placed at the beginning of the edit buffer.

Current line: Set to the last line copied.

Current column: Set to non- <blank>.

Delete

Synopsis:

[2addr] d[elete][buffer][count][flags]

Delete the specified lines into a buffer (defaulting to the unnamed buffer), which shall become a line-mode buffer.

Flags can immediately follow the command name; see Command Line Parsing in ex .

Current line: Set to the line following the deleted lines, or to the last line in the edit buffer if that line is past the end of the edit buffer, or to zero if the edit buffer is empty.

Current column: Set to non- <blank>.

Edit

Synopsis:

e[dit][!][+command][file]ex[!][+command][file]

If no '!' is appended to the command name, and the edit buffer has been modified since the last complete write, it shall be an error.

If file is specified, replace the current contents of the edit buffer with the current contents of file, and set the current pathname to file. If file is not specified, replace the current contents of the edit buffer with the current contents of the file named by the current pathname. If for any reason the current contents of the file cannot be accessed, the edit buffer shall be empty.

The + command option shall be <blank>-delimited; <blank>s within + command can be escaped by preceding them with a backslash character. The + command shall be interpreted as an ex command immediately after the contents of the edit buffer have been replaced and the current line and column have been set.

If the edit buffer is empty:

Current line: Set to 0.

Current column: Set to 1.

Otherwise, if executed while in ex command mode or if the + command argument is specified:

Current line: Set to the last line of the edit buffer.

Current column: Set to non- <blank>.

Otherwise, if file is omitted or results in the current pathname:

Current line: Set to the first line of the edit buffer.

Current column: Set to non- <blank>.

Otherwise, if file is the same as the last file edited, the line and column shall be set as follows; if the file was previously edited, the line and column may be set as follows:

Current line: Set to the last value held when that file was last edited. If this value is not a valid line in the new edit buffer, set to the first line of the edit buffer.

Current column: If the current line was set to the last value held when the file was last edited, set to the last value held when the file was last edited. Otherwise, or if the last value is not a valid column in the new edit buffer, set to non- <blank>.

Otherwise:

Current line: Set to the first line of the edit buffer.

Current column: Set to non- <blank>.

File

Synopsis:

f[ile][file]

If a file argument is specified, the alternate pathname shall be set to the current pathname, and the current pathname shall be set to file.

Write an informational message. If the file has a current pathname, it shall be included in this message; otherwise, the message shall indicate that there is no current pathname. If the edit buffer contains lines, the current line number and the number of lines in the edit buffer shall be included in this message; otherwise, the message shall indicate that the edit buffer is empty. If the edit buffer has been modified since the last complete write, this fact shall be included in this message. If the readonly edit option is set, this fact shall be included in this message. The message may contain other unspecified information.

Current line: Unchanged.

Current column: Unchanged.

Global

Synopsis:

[2addr] g[lobal] /pattern/ [commands]
[2addr] v /pattern/ [commands]

The optional '!' character after the global command shall be the same as executing the v command.

If pattern is empty (for example, "//" ) or not specified, the last regular expression used in the editor command shall be used as the pattern. The pattern can be delimited by slashes (shown in the Synopsis), as well as any non-alphanumeric or non- <blank> other than backslash, vertical line, double quote, or <newline>.

If no lines are specified, the lines shall default to the entire file.

The global and v commands are logically two-pass operations. First, mark the lines within the specified lines for which the line excluding the terminating <newline> matches ( global) or does not match ( v or global!) the specified pattern. Second, execute the ex commands given by commands, with the current line ( '.' ) set to each marked line. If an error occurs during this process, or the contents of the edit buffer are replaced (for example, by the ex :edit command) an error message shall be written and no more commands resulting from the execution of this command shall be processed.

Multiple ex commands can be specified by entering multiple commands on a single line using a vertical line to delimit them, or one per line, by escaping each <newline> with a backslash.

If no commands are specified:

1.
If in ex command mode, it shall be as if the print command were specified.

2.
Otherwise, no command shall be executed.

For the append, change, and insert commands, the input text shall be included as part of the command, and the terminating period can be omitted if the command ends the list of commands. The open and visual commands can be specified as one of the commands, in which case each marked line shall cause the editor to enter open or visual mode. If open or visual mode is exited using the vi Q command, the current line shall be set to the next marked line, and open or visual mode reentered, until the list of marked lines is exhausted.

The global, v, and undo commands cannot be used in commands. Marked lines may be deleted by commands executed for lines occurring earlier in the file than the marked lines. In this case, no commands shall be executed for the deleted lines.

If the remembered search direction is not set, the global and v commands shall set it to forward.

The autoprint and autoindent edit options shall be inhibited for the duration of the g or v command.

Current line: If no commands executed, set to the last marked line. Otherwise, as specified for the executed ex commands.

Current column: If no commands are executed, set to non- <blank>; otherwise, as specified for the individual ex commands.

Insert

Synopsis:

[1addr] i[nsert][!]

Enter ex text input mode; the input text shall be placed before the specified line. If the line is zero or 1, the text shall be placed at the beginning of the edit buffer.

This command shall be affected by the number and autoindent edit options; following the command name with '!' shall cause the autoindent edit option setting to be toggled for the duration of this command only.

Current line: Set to the last input line; if no lines were input, set to the line before the specified line, or to the first line of the edit buffer if there are no lines preceding the specified line, or zero if the edit buffer is empty.

Current column: Set to non- <blank>.

Join

Synopsis:

[2addr] j[oin][!][count][flags]

If count is specified: If no address was specified, the join command shall behave as if 2addr were the current line and the current line plus count (.,. + count).

If one address was specified, the join command shall behave as if 2addr were the specified address and the specified address plus count ( addr, addr + count).

If two addresses were specified, the join command shall behave as if an additional address, equal to the last address plus count -1 ( addr1, addr2, addr2 + count -1), was specified.

If this would result in a second address greater than the last line of the edit buffer, it shall be corrected to be equal to the last line of the edit buffer.

If no count is specified: If no address was specified, the join command shall behave as if 2addr were the current line and the next line (.,. +1).

If one address was specified, the join command shall behave as if 2addr were the specified address and the next line ( addr, addr +1).

Join the text from the specified lines together into a single line, which shall replace the specified lines.

If a '!' character is appended to the command name, the join shall be without modification of any line, independent of the current locale.

Otherwise, in the POSIX locale, set the current line to the first of the specified lines, and then, for each subsequent line, proceed as follows:

1.
Discard leading <space>s from the line to be joined.

2.
If the line to be joined is now empty, delete it, and skip steps 3 through 5.

3.
If the current line ends in a <blank>, or the first character of the line to be joined is a ')' character, join the lines without further modification.

4.
If the last character of the current line is a '.' , join the lines with two <space>s between them.

5.
Otherwise, join the lines with a single <space> between them.

Current line: Set to the first line specified.

Current column: Set to non- <blank>.

List

Synopsis:

[2addr] l[ist][count][flags]

This command shall be equivalent to the ex command:

[2addr] p[rint][count] l[flags]

See Print .

Map

Synopsis:

map[!][lhs rhs]

If lhs and rhs are not specified:

1.
If '!' is specified, write the current list of text input mode maps.

2.
Otherwise, write the current list of command mode maps.

3.
Do nothing more.

Implementations may restrict the set of characters accepted in lhs or rhs, except that printable characters and <blank>s shall not be restricted. Additional restrictions shall be implementation-defined. In both lhs and rhs, any character can be escaped with a <control>-V, in which case the character shall not be used to delimit lhs from rhs, and the escaping <control>-V shall be discarded.

If the character '!' is appended to the map command name, the mapping shall be effective during open or visual text input mode rather than open or visual command mode. This allows lhs to have two different map definitions at the same time: one for command mode and one for text input mode.

For command mode mappings: When the lhs is entered as any part of a vi command in open or visual mode (but not as part of the arguments to the command), the action shall be as if the corresponding rhs had been entered.

If any character in the command, other than the first, is escaped using a <control>-V character, that character shall not be part of a match to an lhs.

It is unspecified whether implementations shall support map commands where the lhs is more than a single character in length, where the first character of the lhs is printable.

If lhs contains more than one character and the first character is '#' , followed by a sequence of digits corresponding to a numbered function key, then when this function key is typed it shall be mapped to rhs. Characters other than digits following a '#' character also represent the function key named by the characters in the lhs following the '#' and may be mapped to rhs. It is unspecified how function keys are named or what function keys are supported.

For text input mode mappings: When the lhs is entered as any part of text entered in open or visual text input modes, the action shall be as if the corresponding rhs had been entered.

If any character in the input text is escaped using a <control>-V character, that character shall not be part of a match to an lhs.

It is unspecified whether the lhs text entered for subsequent map or unmap commands is replaced with the rhs text for the purposes of the screen display; regardless of whether or not the display appears as if the corresponding rhs text was entered, the effect of the command shall be as if the lhs text was entered.

If only part of the lhs is entered, it is unspecified how long the editor will wait for additional, possibly matching characters before treating the already entered characters as not matching the lhs.

The rhs characters shall themselves be subject to remapping, unless otherwise specified by the remap edit option, except that if the characters in lhs occur as prefix characters in rhs, those characters shall not be remapped.

On block-mode terminals, the mapping need not occur immediately (for example, it may occur after the terminal transmits a group of characters to the system), but it shall achieve the same results as if it occurred immediately.

Current line: Unchanged.

Current column: Unchanged.

Mark

Synopsis:

[1addr] ma[rk] character
[1addr] k character

Implementations shall support character values of a single lowercase letter of the POSIX locale and the characters '`' and '" ; support of other characters is implementation-defined.

If executing the vi m command, set the specified mark to the current line and 1-based numbered character referenced by the current column, if any; otherwise, column position 1.

Otherwise, set the specified mark to the specified line and 1-based numbered first non- <blank> non- <newline> in the line, if any; otherwise, the last non- <newline> in the line, if any; otherwise, column position 1.

The mark shall remain associated with the line until the mark is reset or the line is deleted. If a deleted line is restored by a subsequent undo command, any marks previously associated with the line, which have not been reset, shall be restored as well. Any use of a mark not associated with a current line in the edit buffer shall be an error.

The marks ` and ' shall be set as described previously, immediately before the following events occur in the editor:

1.
The use of '$' as an ex address

2.
The use of a positive decimal number as an ex address

3.
The use of a search command as an ex address

4.
The use of a mark reference as an ex address

5.
The use of the following open and visual mode commands: <control>-], %, (, ), [, ], {, }

6.
The use of the following open and visual mode commands: ', G, H, L, M, z if the current line will change as a result of the command

7.
The use of the open and visual mode commands: /, ?, N, `, n if the current line or column will change as a result of the command

8.
The use of the ex mode commands: z, undo, global, v

For rules 1., 2., 3., and 4., the ` and ' marks shall not be set if the ex command is parsed as specified by rule 6.a. in Command Line Parsing in ex .

For rules 5., 6., and 7., the ` and ' marks shall not be set if the commands are used as motion commands in open and visual mode.

For rules 1., 2., 3., 4., 5., 6., 7., and 8., the ` and ' marks shall not be set if the command fails.

The ` and ' marks shall be set as described previously, each time the contents of the edit buffer are replaced (including the editing of the initial buffer), if in open or visual mode, or if in ex mode and the edit buffer is not empty, before any commands or movements (including commands or movements specified by the -c or -t options or the + command argument) are executed on the edit buffer. If in open or visual mode, the marks shall be set as if executing the vi m command; otherwise, as if executing the ex mark command.

When changing from ex mode to open or visual mode, if the ` and ' marks are not already set, the ` and ' marks shall be set as described previously.

Current line: Unchanged.

Current column: Unchanged.

Move

Synopsis:

[2addr] m[ove] 1addr [flags]

Move the specified lines after the specified destination line. A destination of line zero specifies that the lines shall be placed at the beginning of the edit buffer. It shall be an error if the destination line is within the range of lines to be moved.

Current line: Set to the last of the moved lines.

Current column: Set to non- <blank>.

Next

Synopsis:

n[ext][!][+command][file ...]

If no '!' is appended to the command name, and the edit buffer has been modified since the last complete write, it shall be an error, unless the file is successfully written as specified by the autowrite option.

If one or more files is specified:

1.
Set the argument list to the specified filenames.

2.
Set the current argument list reference to be the first entry in the argument list.

3.
Set the current pathname to the first filename specified.

Otherwise:

1.
It shall be an error if there are no more filenames in the argument list after the filename currently referenced.

2.
Set the current pathname and the current argument list reference to the filename after the filename currently referenced in the argument list.

Replace the contents of the edit buffer with the contents of the file named by the current pathname. If for any reason the contents of the file cannot be accessed, the edit buffer shall be empty.

This command shall be affected by the autowrite and writeany edit options.

The + command option shall be <blank>-delimited; <blank>s can be escaped by preceding them with a backslash character. The + command shall be interpreted as an ex command immediately after the contents of the edit buffer have been replaced and the current line and column have been set.

Current line: Set as described for the edit command.

Current column: Set as described for the edit command.

Number

Synopsis:

[2addr] nu[mber][count][flags]
[2addr] #[count][flags]

These commands shall be equivalent to the ex command:

[2addr] p[rint][count] #[flags]

See Print .

Open

Synopsis:

[1addr] o[pen] /pattern/ [flags]

This command need not be supported on block-mode terminals or terminals with insufficient capabilities. If standard input, standard output, or standard error are not terminal devices, the results are unspecified.

Enter open mode.

The trailing delimiter can be omitted from pattern at the end of the command line. If pattern is empty (for example, "//" ) or not specified, the last regular expression used in the editor shall be used as the pattern. The pattern can be delimited by slashes (shown in the Synopsis), as well as any alphanumeric, or non- <blank> other than backslash, vertical line, double quote, or <newline>.

Current line: Set to the specified line.

Current column: Set to non- <blank>.

Preserve

Synopsis:

pre[serve]

Save the edit buffer in a form that can later be recovered by using the -r option or by using the ex recover command. After the file has been preserved, a mail message shall be sent to the user. This message shall be readable by invoking the mailx utility. The message shall contain the name of the file, the time of preservation, and an ex command that could be used to recover the file. Additional information may be included in the mail message.

Current line: Unchanged.

Current column: Unchanged.

Print

Synopsis:

[2addr] p[rint][count][flags]

Write the addressed lines. The behavior is unspecified if the number of columns on the display is less than the number of columns required to write any single character in the lines being written.

Non-printable characters, except for the <tab>, shall be written as implementation-defined multi-character sequences.

If the # flag is specified or the number edit option is set, each line shall be preceded by its line number in the following format:

"%6d  ", <line number>

If the l flag is specified or the list edit option is set:

1.
The characters listed in the Base Definitions volume of IEEE Std 1003.1-2001, Table 5-1, Escape Sequences and Associated Actions shall be written as the corresponding escape sequence.

2.
Non-printable characters not in the Base Definitions volume of IEEE Std 1003.1-2001, Table 5-1, Escape Sequences and Associated Actions shall be written as one three-digit octal number (with a preceding backslash) for each byte in the character (most significant byte first). If the size of a byte on the system is greater than 9 bits, the format used for non-printable characters is implementation-defined.

3.
The end of each line shall be marked with a '$' , and literal '$' characters within the line shall be written with a preceding backslash.

Long lines shall be folded; the length at which folding occurs is unspecified, but should be appropriate for the output terminal, considering the number of columns of the terminal.

If a line is folded, and the l flag is not specified and the list edit option is not set, it is unspecified whether a multi-column character at the folding position is separated; it shall not be discarded.

Current line: Set to the last written line.

Current column: Unchanged if the current line is unchanged; otherwise, set to non- <blank>.

Put

Synopsis:

[1addr] pu[t][buffer]

Append text from the specified buffer (by default, the unnamed buffer) to the specified line; line zero specifies that the text shall be placed at the beginning of the edit buffer. Each portion of a line in the buffer shall become a new line in the edit buffer, regardless of the mode of the buffer.

Current line: Set to the last line entered into the edit buffer.

Current column: Set to non- <blank>.

Quit

Synopsis:

q[uit][!]

If no '!' is appended to the command name:

1.
If the edit buffer has been modified since the last complete write, it shall be an error.

2.
If there are filenames in the argument list after the filename currently referenced, and the last command was not a quit, wq, xit, or ZZ (see Exit ) command, it shall be an error.

Otherwise, terminate the editing session.

Read

Synopsis:

[1addr] r[ead][!][file]

If '!' is not the first non- <blank> to follow the command name, a copy of the specified file shall be appended into the edit buffer after the specified line; line zero specifies that the copy shall be placed at the beginning of the edit buffer. The number of lines and bytes read shall be written. If no file is named, the current pathname shall be the default. If there is no current pathname, then file shall become the current pathname. If there is no current pathname or file operand, it shall be an error. Specifying a file that is not of type regular shall have unspecified results.

Otherwise, if file is preceded by '!' , the rest of the line after the '!' shall have '%' , '#' , and '!' characters expanded as described in Command Line Parsing in ex .

The ex utility shall then pass two arguments to the program named by the shell edit option; the first shall be -c and the second shall be the expanded arguments to the read command as a single argument. The standard input of the program shall be set to the standard input of the ex program when it was invoked. The standard error and standard output of the program shall be appended into the edit buffer after the specified line.

Each line in the copied file or program output (as delimited by <newline>s or the end of the file or output if it is not immediately preceded by a <newline>), shall be a separate line in the edit buffer. Any occurrences of <carriage-return> and <newline> pairs in the output shall be treated as single <newline>s.

The special meaning of the '!' following the read command can be overridden by escaping it with a backslash character.

Current line: If no lines are added to the edit buffer, unchanged. Otherwise, if in open or visual mode, set to the first line entered into the edit buffer. Otherwise, set to the last line entered into the edit buffer.

Current column: Set to non- <blank>.

Recover

Synopsis:

rec[over][!] file

If no '!' is appended to the command name, and the edit buffer has been modified since the last complete write, it shall be an error.

If no file operand is specified, then the current pathname shall be used. If there is no current pathname or file operand, it shall be an error.

If no recovery information has previously been saved about file, the recover command shall behave identically to the edit command, and an informational message to this effect shall be written.

Otherwise, set the current pathname to file, and replace the current contents of the edit buffer with the recovered contents of file. If there are multiple instances of the file to be recovered, the one most recently saved shall be recovered, and an informational message that there are previous versions of the file that can be recovered shall be written. The editor shall behave as if the contents of the edit buffer have already been modified.

Current file: Set as described for the edit command.

Current column: Set as described for the edit command.

Rewind

Synopsis:

rew[ind][!]

If no '!' is appended to the command name, and the edit buffer has been modified since the last complete write, it shall be an error, unless the file is successfully written as specified by the autowrite option.

If the argument list is empty, it shall be an error.

The current argument list reference and the current pathname shall be set to the first filename in the argument list.

Replace the contents of the edit buffer with the contents of the file named by the current pathname. If for any reason the contents of the file cannot be accessed, the edit buffer shall be empty.

This command shall be affected by the autowrite and writeany edit options.

Current line: Set as described for the edit command.

Current column: Set as described for the edit command.

Set

Synopsis:

se[t][option[=[value]] ...][nooption ...][option? ...][all]

When no arguments are specified, write the value of the term edit option and those options whose values have been changed from the default settings; when the argument all is specified, write all of the option values.

Giving an option name followed by the character '?' shall cause the current value of that option to be written. The '?' can be separated from the option name by zero or more <blank>s. The '?' shall be necessary only for Boolean valued options. Boolean options can be given values by the form set option to turn them on or set no option to turn them off; string and numeric options can be assigned by the form set option= value. Any <blank>s in strings can be included as is by preceding each <blank> with an escaping backslash. More than one option can be set or listed by a single set command by specifying multiple arguments, each separated from the next by one or more <blank>s.

See Edit Options in ex for details about specific options.

Current line: Unchanged.

Current column: Unchanged.

Shell

Synopsis:

sh[ell]

Invoke the program named in the shell edit option with the single argument -i (interactive mode). Editing shall be resumed when the program exits.

Current line: Unchanged.

Current column: Unchanged.

Source

Synopsis:

so[urce] file

Read and execute ex commands from file. Lines in the file that are blank lines shall be ignored.

Current line: As specified for the individual ex commands.

Current column: As specified for the individual ex commands.

Substitute

Synopsis:

[2addr] s[ubstitute][/pattern/repl/[options][count][flags]]

[2addr] &[options][count][flags]]

[2addr] ~[options][count][flags]]

Replace the first instance of the pattern pattern by the string repl on each specified line. (See Regular Expressions in ex and Replacement Strings in ex .) Any non-alphabetic, non- <blank> delimiter other than '\' , '|' , double quote, or <newline> can be used instead of '/' . Backslash characters can be used to escape delimiters, backslash characters, and other special characters.

The trailing delimiter can be omitted from pattern or from repl at the end of the command line. If both pattern and repl are not specified or are empty (for example, "//" ), the last s command shall be repeated. If only pattern is not specified or is empty, the last regular expression used in the editor shall be used as the pattern. If only repl is not specified or is empty, the pattern shall be replaced by nothing. If the entire replacement pattern is '%' , the last replacement pattern to an s command shall be used.

Entering a <carriage-return> in repl (which requires an escaping backslash in ex mode and an escaping <control>-V in open or vi mode) shall split the line at that point, creating a new line in the edit buffer. The <carriage-return> shall be discarded.

If options includes the letter 'g' ( global), all non-overlapping instances of the pattern in the line shall be replaced.

If options includes the letter 'c' ( confirm), then before each substitution the line shall be written; the written line shall reflect all previous substitutions. On the following line, <space>s shall be written beneath the characters from the line that are before the pattern to be replaced, and '^' characters written beneath the characters included in the pattern to be replaced. The ex utility shall then wait for a response from the user. An affirmative response shall cause the substitution to be done, while any other input shall not make the substitution. An affirmative response shall consist of a line with the affirmative response (as defined by the current locale) at the beginning of the line. This line shall be subject to editing in the same way as the ex command line.

If interrupted (see the ASYNCHRONOUS EVENTS section), any modifications confirmed by the user shall be preserved in the edit buffer after the interrupt.

If the remembered search direction is not set, the s command shall set it to forward.

In the second Synopsis, the & command shall repeat the previous substitution, as if the & command were replaced by:

s/pattern/repl/

where pattern and repl are as specified in the previous s, &, or ~ command.

In the third Synopsis, the ~ command shall repeat the previous substitution, as if the '~' were replaced by:

s/pattern/repl/

where pattern shall be the last regular expression specified to the editor, and repl shall be from the previous substitution (including & and ~) command.

These commands shall be affected by the LC_MESSAGES environment variable.

Current line: Set to the last line in which a substitution occurred, or, unchanged if no substitution occurred.

Current column: Set to non- <blank>.

Suspend

Synopsis:

su[spend][!]st[op][!]

Allow control to return to the invoking process; ex shall suspend itself as if it had received the SIGTSTP signal. The suspension shall occur only if job control is enabled in the invoking shell (see the description of set -m).

These commands shall be affected by the autowrite and writeany edit options.

The current susp character (see stty ) shall be equivalent to the suspend command.

Tag

Synopsis:

ta[g][!] tagstring

The results are unspecified if the format of a tags file is not as specified by the ctags utility (see ctags ) description.

The tag command shall search for tagstring in the tag files referred to by the tag edit option, in the order they are specified, until a reference to tagstring is found. Files shall be searched from beginning to end. If no reference is found, it shall be an error and an error message to this effect shall be written. If the reference is not found, or if an error occurs while processing a file referred to in the tag edit option, it shall be an error, and an error message shall be written at the first occurrence of such an error.

Otherwise, if the tags file contained a pattern, the pattern shall be treated as a regular expression used in the editor; for example, for the purposes of the s command.

If the tagstring is in a file with a different name than the current pathname, set the current pathname to the name of that file, and replace the contents of the edit buffer with the contents of that file. In this case, if no '!' is appended to the command name, and the edit buffer has been modified since the last complete write, it shall be an error, unless the file is successfully written as specified by the autowrite option.

This command shall be affected by the autowrite, tag, taglength, and writeany edit options.

Current line: If the tags file contained a line number, set to that line number. If the line number is larger than the last line in the edit buffer, an error message shall be written and the current line shall be set as specified for the edit command.

If the tags file contained a pattern, set to the first occurrence of the pattern in the file. If no matching pattern is found, an error message shall be written and the current line shall be set as specified for the edit command.

Current column: If the tags file contained a line-number reference and that line-number was not larger than the last line in the edit buffer, or if the tags file contained a pattern and that pattern was found, set to non- <blank>. Otherwise, set as specified for the edit command.

Unabbreviate

Synopsis:

una[bbrev] lhs

If lhs is not an entry in the current list of abbreviations (see Abbreviate ), it shall be an error. Otherwise, delete lhs from the list of abbreviations.

Current line: Unchanged.

Current column: Unchanged.

Undo

Synopsis:

u[ndo]

Reverse the changes made by the last command that modified the contents of the edit buffer, including undo. For this purpose, the global, v, open, and visual commands, and commands resulting from buffer executions and mapped character expansions, are considered single commands.

If no action that can be undone preceded the undo command, it shall be an error.

If the undo command restores lines that were marked, the mark shall also be restored unless it was reset subsequent to the deletion of the lines.

Current line:

1.
If lines are added or changed in the file, set to the first line added or changed.

2.
Set to the line before the first line deleted, if it exists.

3.
Set to 1 if the edit buffer is not empty.

4.
Set to zero.

Current column: Set to non- <blank>.

Unmap

Synopsis:

unm[ap][!] lhs

If '!' is appended to the command name, and if lhs is not an entry in the list of text input mode map definitions, it shall be an error. Otherwise, delete lhs from the list of text input mode map definitions.

If no '!' is appended to the command name, and if lhs is not an entry in the list of command mode map definitions, it shall be an error. Otherwise, delete lhs from the list of command mode map definitions.

Current line: Unchanged.

Current column: Unchanged.

Version

Synopsis:

ve[rsion]

Write a message containing version information for the editor. The format of the message is unspecified.

Current line: Unchanged.

Current column: Unchanged.

Visual

Synopsis:

[1addr] vi[sual][type][count][flags]

If ex is currently in open or visual mode, the Synopsis and behavior of the visual command shall be the same as the edit command, as specified by Edit .

Otherwise, this command need not be supported on block-mode terminals or terminals with insufficient capabilities. If standard input, standard output, or standard error are not terminal devices, the results are unspecified.

If count is specified, the value of the window edit option shall be set to count (as described in window ). If the '^' type character was also specified, the window edit option shall be set before being used by the type character.

Enter visual mode. If type is not specified, it shall be as if a type of '+' was specified. The type shall cause the following effects:

+
Place the beginning of the specified line at the top of the display.
-
Place the end of the specified line at the bottom of the display.
.
Place the beginning of the specified line in the middle of the display.
^
If the specified line is less than or equal to the value of the window edit option, set the line to 1; otherwise, decrement the line by the value of the window edit option minus 1. Place the beginning of this line as close to the bottom of the displayed lines as possible, while still displaying the value of the window edit option number of lines.

Current line: Set to the specified line.

Current column: Set to non- <blank>.

Write

Synopsis:

[2addr] w[rite][!][>>][file]
[2addr] w[rite][!][file]
[2addr] wq[!][>>][file]

If no lines are specified, the lines shall default to the entire file.

The command wq shall be equivalent to a write command followed by a quit command; wq! shall be equivalent to write! followed by quit. In both cases, if the write command fails, the quit shall not be attempted.

If the command name is not followed by one or more <blank>s, or file is not preceded by a '!' character, the write shall be to a file.

1.
If the >> argument is specified, and the file already exists, the lines shall be appended to the file instead of replacing its contents. If the >> argument is specified, and the file does not already exist, it is unspecified whether the write shall proceed as if the >> argument had not been specified or if the write shall fail.

2.
If the readonly edit option is set (see readonly ), the write shall fail.

3.
If file is specified, and is not the current pathname, and the file exists, the write shall fail.

4.
If file is not specified, the current pathname shall be used. If there is no current pathname, the write command shall fail.

5.
If the current pathname is used, and the current pathname has been changed by the file or read commands, and the file exists, the write shall fail. If the write is successful, subsequent writes shall not fail for this reason (unless the current pathname is changed again).

6.
If the whole edit buffer is not being written, and the file to be written exists, the write shall fail.

For rules 1., 2., 4., and 5., the write can be forced by appending the character '!' to the command name.

For rules 2., 4., and 5., the write can be forced by setting the writeany edit option.

Additional, implementation-defined tests may cause the write to fail.

If the edit buffer is empty, a file without any contents shall be written.

An informational message shall be written noting the number of lines and bytes written.

Otherwise, if the command is followed by one or more <blank>s, and the file is preceded by '!' , the rest of the line after the '!' shall have '%' , '#' , and '!' characters expanded as described in Command Line Parsing in ex .

The ex utility shall then pass two arguments to the program named by the shell edit option; the first shall be -c and the second shall be the expanded arguments to the write command as a single argument. The specified lines shall be written to the standard input of the command. The standard error and standard output of the program, if any, shall be written as described for the print command. If the last character in that output is not a <newline>, a <newline> shall be written at the end of the output.

The special meaning of the '!' following the write command can be overridden by escaping it with a backslash character.

Current line: Unchanged.

Current column: Unchanged.

Write and Exit

Synopsis:

[2addr] x[it][!][file]

If the edit buffer has not been modified since the last complete write, xit shall be equivalent to the quit command, or if a '!' is appended to the command name, to quit!.

Otherwise, xit shall be equivalent to the wq command, or if a '!' is appended to the command name, to wq!.

Current line: Unchanged.

Current column: Unchanged.

Yank

Synopsis:

[2addr] ya[nk][buffer][count]

Copy the specified lines to the specified buffer (by default, the unnamed buffer), which shall become a line-mode buffer.

Current line: Unchanged.

Current column: Unchanged.

Adjust Window

Synopsis:

[1addr] z[!][type ...][count][flags]

If no line is specified, the current line shall be the default; if type is omitted as well, the current line value shall first be incremented by 1. If incrementing the current line would cause it to be greater than the last line in the edit buffer, it shall be an error.

If there are <blank>s between the type argument and the preceding z command name or optional '!' character, it shall be an error.

If count is specified, the value of the window edit option shall be set to count (as described in window ). If count is omitted, it shall default to 2 times the value of the scroll edit option, or if ! was specified, the number of lines in the display minus 1.

If type is omitted, then count lines starting with the specified line shall be written. Otherwise, count lines starting with the line specified by the type argument shall be written.

The type argument shall change the lines to be written. The possible values of type are as follows:

-
The specified line shall be decremented by the following value:

(((number of "-" characters) x count) -1)

If the calculation would result in a number less than 1, it shall be an error. Write lines from the edit buffer, starting at the new value of line, until count lines or the last line in the edit buffer has been written.

+
The specified line shall be incremented by the following value:

(((number of "+" characters) -1) x count) +1

If the calculation would result in a number greater than the last line in the edit buffer, it shall be an error. Write lines from the edit buffer, starting at the new value of line, until count lines or the last line in the edit buffer has been written.

=,.
If more than a single '.' or '=' is specified, it shall be an error. The following steps shall be taken:
1.
If count is zero, nothing shall be written.

2.
Write as many of the N lines before the current line in the edit buffer as exist. If count or '!' was specified, N shall be:

(count -1) /2

Otherwise, N shall be:

(count -3) /2

If N is a number less than 3, no lines shall be written.

3.
If '=' was specified as the type character, write a line consisting of the smaller of the number of columns in the display divided by two, or 40 '-' characters.

4.
Write the current line.

5.
Repeat step 3.

6.
Write as many of the N lines after the current line in the edit buffer as exist. N shall be defined as in step 2. If N is a number less than 3, no lines shall be written. If count is less than 3, no lines shall be written.

^
The specified line shall be decremented by the following value:

(((number of "^" characters) +1) x count) -1

If the calculation would result in a number less than 1, it shall be an error. Write lines from the edit buffer, starting at the new value of line, until count lines or the last line in the edit buffer has been written.

Current line: Set to the last line written, unless the type is =, in which case, set to the specified line.

Current column: Set to non- <blank>.

Escape

Synopsis:

! command
[addr]! command

The contents of the line after the '!' shall have '%' , '#' , and '!' characters expanded as described in Command Line Parsing in ex . If the expansion causes the text of the line to change, it shall be redisplayed, preceded by a single '!' character.

The ex utility shall execute the program named by the shell edit option. It shall pass two arguments to the program; the first shall be -c, and the second shall be the expanded arguments to the ! command as a single argument.

If no lines are specified, the standard input, standard output, and standard error of the program shall be set to the standard input, standard output, and standard error of the ex program when it was invoked. In addition, a warning message shall be written if the edit buffer has been modified since the last complete write, and the warn edit option is set.

If lines are specified, they shall be passed to the program as standard input, and the standard output and standard error of the program shall replace those lines in the edit buffer. Each line in the program output (as delimited by <newline>s or the end of the output if it is not immediately preceded by a <newline>), shall be a separate line in the edit buffer. Any occurrences of <carriage-return> and <newline> pairs in the output shall be treated as single <newline>s. The specified lines shall be copied into the unnamed buffer before they are replaced, and the unnamed buffer shall become a line-mode buffer.

If in ex mode, a single '!' character shall be written when the program completes.

This command shall be affected by the shell and warn edit options. If no lines are specified, this command shall be affected by the autowrite and writeany edit options. If lines are specified, this command shall be affected by the autoprint edit option.

Current line:

1.
If no lines are specified, unchanged.

2.
Otherwise, set to the last line read in, if any lines are read in.

3.
Otherwise, set to the line before the first line of the lines specified, if that line exists.

4.
Otherwise, set to the first line of the edit buffer if the edit buffer is not empty.

5.
Otherwise, set to zero.

Current column: If no lines are specified, unchanged. Otherwise, set to non- <blank>.

Shift Left

Synopsis:

[2addr] <[< ...][count][flags]

Shift the specified lines to the start of the line; the number of column positions to be shifted shall be the number of command characters times the value of the shiftwidth edit option. Only leading <blank>s shall be deleted or changed into other <blank>s in shifting; other characters shall not be affected.

Lines to be shifted shall be copied into the unnamed buffer, which shall become a line-mode buffer.

This command shall be affected by the autoprint edit option.

Current line: Set to the last line in the lines specified.

Current column: Set to non- <blank>.

Shift Right

Synopsis:

[2addr] >[> ...][count][flags]

Shift the specified lines away from the start of the line; the number of column positions to be shifted shall be the number of command characters times the value of the shiftwidth edit option. The shift shall be accomplished by adding <blank>s as a prefix to the line or changing leading <blank>s into other <blank>s. Empty lines shall not be changed.

Lines to be shifted shall be copied into the unnamed buffer, which shall become a line-mode buffer.

This command shall be affected by the autoprint edit option.

Current line: Set to the last line in the lines specified.

Current column: Set to non- <blank>.

<control>-D

Synopsis:

<control>-D

Write the next n lines, where n is the minimum of the values of the scroll edit option and the number of lines after the current line in the edit buffer. If the current line is the last line of the edit buffer it shall be an error.

Current line: Set to the last line written.

Current column: Set to non- <blank>.

Write Line Number

Synopsis:

[1addr] = [flags]

If line is not specified, it shall default to the last line in the edit buffer. Write the line number of the specified line.

Current line: Unchanged.

Current column: Unchanged.

Execute

Synopsis:

[2addr] @ buffer[2addr] * buffer

If no buffer is specified or is specified as '@' or '*' , the last buffer executed shall be used. If no previous buffer has been executed, it shall be an error.

For each line specified by the addresses, set the current line ( '.' ) to the specified line, and execute the contents of the named buffer (as they were at the time the @ command was executed) as ex commands. For each line of a line-mode buffer, and all but the last line of a character-mode buffer, the ex command parser shall behave as if the line was terminated by a <newline>.

If an error occurs during this process, or a line specified by the addresses does not exist when the current line would be set to it, or more than a single line was specified by the addresses, and the contents of the edit buffer are replaced (for example, by the ex :edit command) an error message shall be written, and no more commands resulting from the execution of this command shall be processed.

Current line: As specified for the individual ex commands.

Current column: As specified for the individual ex commands.

Regular Expressions in ex

The ex utility shall support regular expressions that are a superset of the basic regular expressions described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions. A null regular expression ( "//" ) shall be equivalent to the last regular expression encountered.

Regular expressions can be used in addresses to specify lines and, in some commands (for example, the substitute command), to specify portions of a line to be substituted.

The following constructs can be used to enhance the basic regular expressions:

\<
Match the beginning of a word. (See the definition of word at the beginning of Command Descriptions in ex .)
\>
Match the end of a word.
~
Match the replacement part of the last substitute command. The tilde ( '~' ) character can be escaped in a regular expression to become a normal character with no special meaning. The backslash shall be discarded.

When the editor option magic is not set, the only characters with special meanings shall be '^' at the beginning of a pattern, '$' at the end of a pattern, and '\' . The characters '.' , '*' , '[' , and '~' shall be treated as ordinary characters unless preceded by a '\' ; when preceded by a '\' they shall regain their special meaning, or in the case of backslash, be handled as a single backslash. Backslashes used to escape other characters shall be discarded.

Replacement Strings in ex

The character '&' ( '\&' if the editor option magic is not set) in the replacement string shall stand for the text matched by the pattern to be replaced. The character '~' ( '\~' if magic is not set) shall be replaced by the replacement part of the previous substitute command. The sequence '\n' , where n is an integer, shall be replaced by the text matched by the pattern enclosed in the nth set of parentheses '\(' and '\)' .

The strings '\l' , '\u' , '\L' , and '\U' can be used to modify the case of elements in the replacement string (using the '\&' or "\" digit) notation. The string '\l' ( '\u' ) shall cause the character that follows to be converted to lowercase (uppercase). The string '\L' ( '\U' ) shall cause all characters subsequent to it to be converted to lowercase (uppercase) as they are inserted by the substitution until the string '\e' or '\E' , or the end of the replacement string, is encountered.

Otherwise, any character following a backslash shall be treated as that literal character, and the escaping backslash shall be discarded.

An example of case conversion with the s command is as follows:

:p
The cat sat on the mat.
:s/\<.at\>/\u&/gp
The Cat Sat on the Mat.
:s/S\(.*\)M/S\U\1\eM/p
The Cat SAT ON THE Mat.

Edit Options in ex

The ex utility has a number of options that modify its behavior. These options have default settings, which can be changed using the set command.

Options are Boolean unless otherwise specified.

autoindent, ai

[Default unset]

If autoindent is set, each line in input mode shall be indented (using first as many <tab>s as possible, as determined by the editor option tabstop, and then using <space>s) to align with another line, as follows:

1.
If in open or visual mode and the text input is part of a line-oriented command (see the EXTENDED DESCRIPTION in vi ), align to the first column.

2.
Otherwise, if in open or visual mode, indentation for each line shall be set as follows:
a.
If a line was previously inserted as part of this command, it shall be set to the indentation of the last inserted line by default, or as otherwise specified for the <control>-D character in Input Mode Commands in vi .

b.
Otherwise, it shall be set to the indentation of the previous current line, if any; otherwise, to the first column.

3.
For the ex a, i, and c commands, indentation for each line shall be set as follows:
a.
If a line was previously inserted as part of this command, it shall be set to the indentation of the last inserted line by default, or as otherwise specified for the eof character in Scroll .

b.
Otherwise, if the command is the ex a command, it shall be set to the line appended after, if any; otherwise to the first column.

c.
Otherwise, if the command is the ex i command, it shall be set to the line inserted before, if any; otherwise to the first column.

d.
Otherwise, if the command is the ex c command, it shall be set to the indentation of the line replaced.

autoprint, ap

[Default set]

If autoprint is set, the current line shall be written after each ex command that modifies the contents of the current edit buffer, and after each tag command for which the tag search pattern was found or tag line number was valid, unless:

1.
The command was executed while in open or visual mode.

2.
The command was executed as part of a global or v command or @ buffer execution.

3.
The command was the form of the read command that reads a file into the edit buffer.

4.
The command was the append, change, or insert command.

5.
The command was not terminated by a <newline>.

6.
The current line shall be written by a flag specified to the command; for example, delete # shall write the current line as specified for the flag modifier to the delete command, and not as specified by the autoprint edit option.

autowrite, aw

[Default unset]

If autowrite is set, and the edit buffer has been modified since it was last completely written to any file, the contents of the edit buffer shall be written as if the ex write command had been specified without arguments, before each command affected by the autowrite edit option is executed. Appending the character '!' to the command name of any of the ex commands except '!' shall prevent the write. If the write fails, it shall be an error and the command shall not be executed.

beautify, bf

[Default unset]

If beautify is set, all non-printable characters, other than <tab>s, <newline>s, and <form-feed>s, shall be discarded from text read in from files.

directory, dir

[Default implementation-defined]

The value of this option specifies the directory in which the editor buffer is to be placed. If this directory is not writable by the user, the editor shall quit.

edcompatible, ed

[Default unset]

Causes the presence of g and c suffixes on substitute commands to be remembered, and toggled by repeating the suffixes.

errorbells, eb

[Default unset]

If the editor is in ex mode, and the terminal does not support a standout mode (such as inverse video), and errorbells is set, error messages shall be preceded by alerting the terminal.

exrc

[Default unset]

If exrc is set, ex shall access any .exrc file in the current directory, as described in Initialization in ex and vi . If exrc is not set, ex shall ignore any .exrc file in the current directory during initialization, unless the current directory is that named by the HOME environment variable.

ignorecase, ic

[Default unset]

If ignorecase is set, characters that have uppercase and lowercase representations shall have those representations considered as equivalent for purposes of regular expression comparison.

The ignorecase edit option shall affect all remembered regular expressions; for example, unsetting the ignorecase edit option shall cause a subsequent vi n command to search for the last basic regular expression in a case-sensitive fashion.

list

[Default unset]

If list is set, edit buffer lines written while in ex command mode shall be written as specified for the print command with the l flag specified. In open or visual mode, each edit buffer line shall be displayed as specified for the ex print command with the l flag specified. In open or visual text input mode, when the cursor does not rest on any character in the line, it shall rest on the '$' marking the end of the line.

magic

[Default set]

If magic is set, modify the interpretation of characters in regular expressions and substitution replacement strings (see Regular Expressions in ex and Replacement Strings in ex ).

mesg

[Default set]

If mesg is set, the permission for others to use the write or talk commands to write to the terminal shall be turned on while in open or visual mode. The shell-level command mesg n shall take precedence over any setting of the ex mesg option; that is, if mesg y was issued before the editor started (or in a shell escape), such as:

:!mesg y

the mesg option in ex shall suppress incoming messages, but the mesg option shall not enable incoming messages if mesg n was issued.

number, nu

[Default unset]

If number is set, edit buffer lines written while in ex command mode shall be written with line numbers, in the format specified by the print command with the # flag specified. In ex text input mode, each line shall be preceded by the line number it will have in the file.

In open or visual mode, each edit buffer line shall be displayed with a preceding line number, in the format specified by the ex print command with the # flag specified. This line number shall not be considered part of the line for the purposes of evaluating the current column; that is, column position 1 shall be the first column position after the format specified by the print command.

paragraphs, para

[Default in the POSIX locale IPLPPPQPP LIpplpipbp]

The paragraphs edit option shall define additional paragraph boundaries for the open and visual mode commands. The paragraphs edit option can be set to a character string consisting of zero or more character pairs. It shall be an error to set it to an odd number of characters.

prompt

[Default set]

If prompt is set, ex command mode input shall be prompted for with a colon ( ':' ); when unset, no prompt shall be written.

readonly

[Default see text]

If the readonly edit option is set, read-only mode shall be enabled (see Write ). The readonly edit option shall be initialized to set if either of the following conditions are true:

*
The command-line option -R was specified.

*
Performing actions equivalent to the access() function called with the following arguments indicates that the file lacks write permission:
1.
The current pathname is used as the path argument.

2.
The constant W_OK is used as the amode argument.

The readonly edit option may be initialized to set for other, implementation-defined reasons. The readonly edit option shall not be initialized to unset based on any special privileges of the user or process. The readonly edit option shall be reinitialized each time that the contents of the edit buffer are replaced (for example, by an edit or next command) unless the user has explicitly set it, in which case it shall remain set until the user explicitly unsets it. Once unset, it shall again be reinitialized each time that the contents of the edit buffer are replaced.

redraw

[Default unset]

The editor simulates an intelligent terminal on a dumb terminal. (Since this is likely to require a large amount of output to the terminal, it is useful only at high transmission speeds.)

remap

[Default set]

If remap is set, map translation shall allow for maps defined in terms of other maps; translation shall continue until a final product is obtained. If unset, only a one-step translation shall be done.

report

[Default 5]

The value of this report edit option specifies what number of lines being added, copied, deleted, or modified in the edit buffer will cause an informational message to be written to the user. The following conditions shall cause an informational message. The message shall contain the number of lines added, copied, deleted, or modified, but is otherwise unspecified.

*
An ex or vi editor command, other than open, undo, or visual, that modifies at least the value of the report edit option number of lines, and which is not part of an ex global or v command, or ex or vi buffer execution, shall cause an informational message to be written.

*
An ex yank or vi y or Y command, that copies at least the value of the report edit option plus 1 number of lines, and which is not part of an ex global or v command, or ex or vi buffer execution, shall cause an informational message to be written.

*
An ex global, v, open, undo, or visual command or ex or vi buffer execution, that adds or deletes a total of at least the value of the report edit option number of lines, and which is not part of an ex global or v command, or ex or vi buffer execution, shall cause an informational message to be written. (For example, if 3 lines were added and 8 lines deleted during an ex visual command, 5 would be the number compared against the report edit option after the command completed.)

scroll, scr

[Default (number of lines in the display -1)/2]

The value of the scroll edit option shall determine the number of lines scrolled by the ex <control>-D and z commands. For the vi <control>-D and <control>-U commands, it shall be the initial number of lines to scroll when no previous <control>-D or <control>-U command has been executed.

sections

[Default in the POSIX locale NHSHH HUnhsh]

The sections edit option shall define additional section boundaries for the open and visual mode commands. The sections edit option can be set to a character string consisting of zero or more character pairs; it shall be an error to set it to an odd number of characters.

shell, sh

[Default from the environment variable SHELL ]

The value of this option shall be a string. The default shall be taken from the SHELL environment variable. If the SHELL environment variable is null or empty, the sh (see sh ) utility shall be the default.

shiftwidth, sw

[Default 8]

The value of this option shall give the width in columns of an indentation level used during autoindentation and by the shift commands ( < and >).

showmatch, sm

[Default unset]

The functionality described for the showmatch edit option need not be supported on block-mode terminals or terminals with insufficient capabilities.

If showmatch is set, in open or visual mode, when a ')' or '}' is typed, if the matching '(' or '{' is currently visible on the display, the matching '(' or '{' shall be flagged moving the cursor to its location for an unspecified amount of time.

showmode

[Default unset]

If showmode is set, in open or visual mode, the current mode that the editor is in shall be displayed on the last line of the display. Command mode and text input mode shall be differentiated; other unspecified modes and implementation-defined information may be displayed.

slowopen

[Default unset]

If slowopen is set during open and visual text input modes, the editor shall not update portions of the display other than those display line columns that display the characters entered by the user (see Input Mode Commands in vi ).

tabstop, ts

[Default 8]

The value of this edit option shall specify the column boundary used by a <tab> in the display (see autoprint, ap and Input Mode Commands in vi ).

taglength, tl

[Default zero]

The value of this edit option shall specify the maximum number of characters that are considered significant in the user-specified tag name and in the tag name from the tags file. If the value is zero, all characters in both tag names shall be significant.

tags

[Default see text]

The value of this edit option shall be a string of <blank>-delimited pathnames of files used by the tag command. The default value is unspecified.

term

[Default from the environment variable TERM ]

The value of this edit option shall be a string. The default shall be taken from the TERM variable in the environment. If the TERM environment variable is empty or null, the default is unspecified. The editor shall use the value of this edit option to determine the type of the display device.

The results are unspecified if the user changes the value of the term edit option after editor initialization.

terse

[Default unset]

If terse is set, error messages may be less verbose. However, except for this caveat, error messages are unspecified. Furthermore, not all error messages need change for different settings of this option.

warn

[Default set]

If warn is set, and the contents of the edit buffer have been modified since they were last completely written, the editor shall write a warning message before certain ! commands (see Escape ).

window

[Default see text]

A value used in open and visual mode, by the <control>-B and <control>-F commands, and, in visual mode, to specify the number of lines displayed when the screen is repainted.

If the -w command-line option is not specified, the default value shall be set to the value of the LINES environment variable. If the LINES environment variable is empty or null, the default shall be the number of lines in the display minus 1.

Setting the window edit option to zero or to a value greater than the number of lines in the display minus 1 (either explicitly or based on the -w option or the LINES environment variable) shall cause the window edit option to be set to the number of lines in the display minus 1.

The baud rate of the terminal line may change the default in an implementation-defined manner.

wrapmargin, wm

[Default 0]

If the value of this edit option is zero, it shall have no effect.

If not in the POSIX locale, the effect of this edit option is implementation-defined.

Otherwise, it shall specify a number of columns from the ending margin of the terminal.

During open and visual text input modes, for each character for which any part of the character is displayed in a column that is less than wrapmargin columns from the ending margin of the display line, the editor shall behave as follows:

1.
If the character triggering this event is a <blank>, it, and all immediately preceding <blank>s on the current line entered during the execution of the current text input command, shall be discarded, and the editor shall behave as if the user had entered a single <newline> instead. In addition, if the next user-entered character is a <space>, it shall be discarded as well.

2.
Otherwise, if there are one or more <blank>s on the current line immediately preceding the last group of inserted non- <blank>s which was entered during the execution of the current text input command, the <blank>s shall be replaced as if the user had entered a single <newline> instead.

If the autoindent edit option is set, and the events described in 1. or 2. are performed, any <blank>s at or after the cursor in the current line shall be discarded.

The ending margin shall be determined by the system or overridden by the user, as described for COLUMNS in the ENVIRONMENT VARIABLES section and the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

wrapscan, ws

[Default set]

If wrapscan is set, searches (the ex / or ? addresses, or open and visual mode /, ?, N, and n commands) shall wrap around the beginning or end of the edit buffer; when unset, searches shall stop at the beginning or end of the edit buffer.

writeany, wa

[Default unset]

If writeany is set, some of the checks performed when executing the ex write commands shall be inhibited, as described in editor option autowrite.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

When any error is encountered and the standard input is not a terminal device file, ex shall not write the file or return to command or text input mode, and shall terminate with a non-zero exit status.

Otherwise, when an unrecoverable error is encountered, it shall be equivalent to a SIGHUP asynchronous event.

Otherwise, when an error is encountered, the editor shall behave as specified in Command Line Parsing in ex .

The following sections are informative.

APPLICATION USAGE

If a SIGSEGV signal is received while ex is saving a file, the file might not be successfully saved.

The next command can accept more than one file, so usage such as:

next `ls [abc]*`

is valid; it would not be valid for the edit or read commands, for example, because they expect only one file and unspecified results occur.

EXAMPLES

None.

RATIONALE

The ex/ vi specification is based on the historical practice found in the 4 BSD and System V implementations of ex and vi. A freely redistributable implementation of ex/ vi, which is tracking IEEE Std 1003.1-2001 fairly closely, and demonstrates the intended changes between historical implementations and IEEE Std 1003.1-2001, may be obtained by anonymous FTP from:

ftp://ftp.rdg.opengroup.org/pub/mirrors/nvi

A restricted editor (both the historical red utility and modifications to ex) were considered and rejected for inclusion. Neither option provided the level of security that users might expect.

It is recognized that ex visual mode and related features would be difficult, if not impossible, to implement satisfactorily on a block-mode terminal, or a terminal without any form of cursor addressing; thus, it is not a mandatory requirement that such features should work on all terminals. It is the intention, however, that an ex implementation should provide the full set of capabilities on all terminals capable of supporting them.

Options

The -c replacement for + command was inspired by the -e option of sed. Historically, all such commands (see edit and next as well) were executed from the last line of the edit buffer. This meant, for example, that "+/pattern" would fail unless the wrapscan option was set. IEEE Std 1003.1-2001 requires conformance to historical practice. Historically, some implementations restricted the ex commands that could be listed as part of the command line arguments. For consistency, IEEE Std 1003.1-2001 does not permit these restrictions.

In historical implementations of the editor, the -R option (and the readonly edit option) only prevented overwriting of files; appending to files was still permitted, mapping loosely into the csh noclobber variable. Some implementations, however, have not followed this semantic, and readonly does not permit appending either. IEEE Std 1003.1-2001 follows the latter practice, believing that it is a more obvious and intuitive meaning of readonly.

The -s option suppresses all interactive user feedback and is useful for editing scripts in batch jobs. The list of specific effects is historical practice. The terminal type "incapable of supporting open and visual modes" has historically been named "dumb".

The -t option was required because the ctags utility appears in IEEE Std 1003.1-2001 and the option is available in all historical implementations of ex.

Historically, the ex and vi utilities accepted a -x option, which did encryption based on the algorithm found in the historical crypt utility. The -x option for encryption, and the associated crypt utility, were omitted because the algorithm used was not specifiable and the export control laws of some nations make it difficult to export cryptographic technology. In addition, it did not historically provide the level of security that users might expect.

Standard Input

An end-of-file condition is not equivalent to an end-of-file character. A common end-of-file character, <control>-D, is historically an ex command.

There was no maximum line length in historical implementations of ex. Specifically, as it was parsed in chunks, the addresses had a different maximum length than the filenames. Further, the maximum line buffer size was declared as BUFSIZ, which was different lengths on different systems. This version selected the value of {LINE_MAX} to impose a reasonable restriction on portable usage of ex and to aid test suite writers in their development of realistic tests that exercise this limit.

Input Files

It was an explicit decision by the standard developers that a <newline> be added to any file lacking one. It was believed that this feature of ex and vi was relied on by users in order to make text files lacking a trailing <newline> more portable. It is recognized that this will require a user-specified option or extension for implementations that permit ex and vi to edit files of type other than text if such files are not otherwise identified by the system. It was agreed that the ability to edit files of arbitrary type can be useful, but it was not considered necessary to mandate that an ex or vi implementation be required to handle files other than text files.

The paragraph in the INPUT FILES section, "By default, ...", is intended to close a long-standing security problem in ex and vi; that of the "modeline" or "modelines" edit option. This feature allows any line in the first or last five lines of the file containing the strings "ex:" or "vi:" (and, apparently, "ei:" or "vx:" ) to be a line containing editor commands, and ex interprets all the text up to the next ':' or <newline> as a command. Consider the consequences, for example, of an unsuspecting user using ex or vi as the editor when replying to a mail message in which a line such as:

ex:! rm -rf :

appeared in the signature lines. The standard developers believed strongly that an editor should not by default interpret any lines of a file. Vendors are strongly urged to delete this feature from their implementations of ex and vi.

Asynchronous Events

The intention of the phrase "complete write" is that the entire edit buffer be written to stable storage. The note regarding temporary files is intended for implementations that use temporary files to back edit buffers unnamed by the user.

Historically, SIGQUIT was ignored by ex, but was the equivalent of the Q command in visual mode; that is, it exited visual mode and entered ex mode. IEEE Std 1003.1-2001 permits, but does not require, this behavior. Historically, SIGINT was often used by vi users to terminate text input mode ( <control>-C is often easier to enter than <ESC>). Some implementations of vi alerted the terminal on this event, and some did not. IEEE Std 1003.1-2001 requires that SIGINT behave identically to <ESC>, and that the terminal not be alerted.

Historically, suspending the ex editor during text input mode was similar to SIGINT, as completed lines were retained, but any partial line discarded, and the editor returned to command mode. IEEE Std 1003.1-2001 is silent on this issue; implementations are encouraged to follow historical practice, where possible.

Historically, the vi editor did not treat SIGTSTP as an asynchronous event, and it was therefore impossible to suspend the editor in visual text input mode. There are two major reasons for this. The first is that SIGTSTP is a broadcast signal on UNIX systems, and the chain of events where the shell execs an application that then execs vi usually caused confusion for the terminal state if SIGTSTP was delivered to the process group in the default manner. The second was that most implementations of the UNIX curses package are not reentrant, and the receipt of SIGTSTP at the wrong time will cause them to crash. IEEE Std 1003.1-2001 is silent on this issue; implementations are encouraged to treat suspension as an asynchronous event if possible.

Historically, modifications to the edit buffer made before SIGINT interrupted an operation were retained; that is, anywhere from zero to all of the lines to be modified might have been modified by the time the SIGINT arrived. These changes were not discarded by the arrival of SIGINT. IEEE Std 1003.1-2001 permits this behavior, noting that the undo command is required to be able to undo these partially completed commands.

The action taken for signals other than SIGINT, SIGCONT, SIGHUP, and SIGTERM is unspecified because some implementations attempt to save the edit buffer in a useful state when other signals are received.

Standard Error

For ex/ vi, diagnostic messages are those messages reported as a result of a failed attempt to invoke ex or vi, such as invalid options or insufficient resources, or an abnormal termination condition. Diagnostic messages should not be confused with the error messages generated by inappropriate or illegal user commands.

Initialization in ex and vi

If an ex command (other than cd, chdir, or source) has a filename argument, one or both of the alternate and current pathnames will be set. Informally, they are set as follows:

1.
If the ex command is one that replaces the contents of the edit buffer, and it succeeds, the current pathname will be set to the filename argument (the first filename argument in the case of the next command) and the alternate pathname will be set to the previous current pathname, if there was one.

2.
In the case of the file read/write forms of the read and write commands, if there is no current pathname, the current pathname will be set to the filename argument.

3.
Otherwise, the alternate pathname will be set to the filename argument.

For example, :edit foo and :recover foo, when successful, set the current pathname, and, if there was a previous current pathname, the alternate pathname. The commands :write, !command, and :edit set neither the current or alternate pathnames. If the :edit foo command were to fail for some reason, the alternate pathname would be set. The read and write commands set the alternate pathname to their file argument, unless the current pathname is not set, in which case they set the current pathname to their file arguments. The alternate pathname was not historically set by the :source command. IEEE Std 1003.1-2001 requires conformance to historical practice. Implementations adding commands that take filenames as arguments are encouraged to set the alternate pathname as described here.

Historically, ex and vi read the .exrc file in the $HOME directory twice, if the editor was executed in the $HOME directory. IEEE Std 1003.1-2001 prohibits this behavior.

Historically, the 4 BSD ex and vi read the $HOME and local .exrc files if they were owned by the real ID of the user, or the sourceany option was set, regardless of other considerations. This was a security problem because it is possible to put normal UNIX system commands inside a .exrc file. IEEE Std 1003.1-2001 does not specify the sourceany option, and historical implementations are encouraged to delete it.

The .exrc files must be owned by the real ID of the user, and not writable by anyone other than the owner. The appropriate privileges exception is intended to permit users to acquire special privileges, but continue to use the .exrc files in their home directories.

System V Release 3.2 and later vi implementations added the option [no]exrc. The behavior is that local .exrc files are read-only if the exrc option is set. The default for the exrc option was off, so by default, local .exrc files were not read. The problem this was intended to solve was that System V permitted users to give away files, so there is no possible ownership or writeability test to ensure that the file is safe. This is still a security problem on systems where users can give away files, but there is nothing additional that IEEE Std 1003.1-2001 can do. The implementation-defined exception is intended to permit groups to have local .exrc files that are shared by users, by creating pseudo-users to own the shared files.

IEEE Std 1003.1-2001 does not mention system-wide ex and vi start-up files. While they exist in several implementations of ex and vi, they are not present in any implementations considered historical practice by IEEE Std 1003.1-2001. Implementations that have such files should use them only if they are owned by the real user ID or an appropriate user (for example, root on UNIX systems) and if they are not writable by any user other than their owner. System-wide start-up files should be read before the EXINIT variable, $HOME/.exrc, or local .exrc files are evaluated.

Historically, any ex command could be entered in the EXINIT variable or the .exrc file, although ones requiring that the edit buffer already contain lines of text generally caused historical implementations of the editor to drop core. IEEE Std 1003.1-2001 requires that any ex command be permitted in the EXINIT variable and .exrc files, for simplicity of specification and consistency, although many of them will obviously fail under many circumstances.

The initialization of the contents of the edit buffer uses the phrase "the effect shall be" with regard to various ex commands. The intent of this phrase is that edit buffer contents loaded during the initialization phase not be lost; that is, loading the edit buffer should fail if the .exrc file read in the contents of a file and did not subsequently write the edit buffer. An additional intent of this phrase is to specify that the initial current line and column is set as specified for the individual ex commands.

Historically, the -t option behaved as if the tag search were a + command; that is, it was executed from the last line of the file specified by the tag. This resulted in the search failing if the pattern was a forward search pattern and the wrapscan edit option was not set. IEEE Std 1003.1-2001 does not permit this behavior, requiring that the search for the tag pattern be performed on the entire file, and, if not found, that the current line be set to a more reasonable location in the file.

Historically, the empty edit buffer presented for editing when a file was not specified by the user was unnamed. This is permitted by IEEE Std 1003.1-2001; however, implementations are encouraged to provide users a temporary filename for this buffer because it permits them the use of ex commands that use the current pathname during temporary edit sessions.

Historically, the file specified using the -t option was not part of the current argument list. This practice is permitted by IEEE Std 1003.1-2001; however, implementations are encouraged to include its name in the current argument list for consistency.

Historically, the -c command was generally not executed until a file that already exists was edited. IEEE Std 1003.1-2001 requires conformance to this historical practice. Commands that could cause the -c command to be executed include the ex commands edit, next, recover, rewind, and tag, and the vi commands <control>-^ and <control>-]. Historically, reading a file into an edit buffer did not cause the -c command to be executed (even though it might set the current pathname) with the exception that it did cause the -c command to be executed if: the editor was in ex mode, the edit buffer had no current pathname, the edit buffer was empty, and no read commands had yet been attempted. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, the -r option was the same as a normal edit session if there was no recovery information available for the file. This allowed users to enter:

vi -r *.c

and recover whatever files were recoverable. In some implementations, recovery was attempted only on the first file named, and the file was not entered into the argument list; in others, recovery was attempted for each file named. In addition, some historical implementations ignored -r if -t was specified or did not support command line file arguments with the -t option. For consistency and simplicity of specification, IEEE Std 1003.1-2001 disallows these special cases, and requires that recovery be attempted the first time each file is edited.

Historically, vi initialized the ` and ' marks, but ex did not. This meant that if the first command in ex mode was visual or if an ex command was executed first (for example, vi +10 file), vi was entered without the marks being initialized. Because the standard developers believed the marks to be generally useful, and for consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that they always be initialized if in open or visual mode, or if in ex mode and the edit buffer is not empty. Not initializing it in ex mode if the edit buffer is empty is historical practice; however, it has always been possible to set (and use) marks in empty edit buffers in open and visual mode edit sessions.

Addressing

Historically, ex and vi accepted the additional addressing forms '\/' and '\?' . They were equivalent to "//" and "??" , respectively. They are not required by IEEE Std 1003.1-2001, mostly because nobody can remember whether they ever did anything different historically.

Historically, ex and vi permitted an address of zero for several commands, and permitted the % address in empty files for others. For consistency, IEEE Std 1003.1-2001 requires support for the former in the few commands where it makes sense, and disallows it otherwise. In addition, because IEEE Std 1003.1-2001 requires that % be logically equivalent to "1,$" , it is also supported where it makes sense and disallowed otherwise.

Historically, the % address could not be followed by further addresses. For consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that additional addresses be supported.

All of the following are valid addresses:

+++
Three lines after the current line.
/re/-
One line before the next occurrence of re.
-2
Two lines before the current line.
3 ---- 2
Line one (note intermediate negative address).
1 2 3
Line six.

Any number of addresses can be provided to commands taking addresses; for example, "1,2,3,4,5p" prints lines 4 and 5, because two is the greatest valid number of addresses accepted by the print command. This, in combination with the semicolon delimiter, permits users to create commands based on ordered patterns in the file. For example, the command 3;/foo/;+2print will display the first line after line 3 that contains the pattern foo, plus the next two lines. Note that the address 3; must be evaluated before being discarded because the search origin for the /foo/ command depends on this.

Historically, values could be added to addresses by including them after one or more <blank>s; for example, 3 - 5p wrote the seventh line of the file, and /foo/ 5 was the same as /foo/+5. However, only absolute values could be added; for example, 5 /foo/ was an error. IEEE Std 1003.1-2001 requires conformance to historical practice. Address offsets are separately specified from addresses because they could historically be provided to visual mode search commands.

Historically, any missing addresses defaulted to the current line. This was true for leading and trailing comma-delimited addresses, and for trailing semicolon-delimited addresses. For consistency, IEEE Std 1003.1-2001 requires it for leading semicolon addresses as well.

Historically, ex and vi accepted the '^' character as both an address and as a flag offset for commands. In both cases it was identical to the '-' character. IEEE Std 1003.1-2001 does not require or prohibit this behavior.

Historically, the enhancements to basic regular expressions could be used in addressing; for example, '~' , '\<' , and '\>' . IEEE Std 1003.1-2001 requires conformance to historical practice; that is, that regular expression usage be consistent, and that regular expression enhancements be supported wherever regular expressions are used.

Command Line Parsing in ex

Historical ex command parsing was even more complex than that described here. IEEE Std 1003.1-2001 requires the subset of the command parsing that the standard developers believed was documented and that users could reasonably be expected to use in a portable fashion, and that was historically consistent between implementations. (The discarded functionality is obscure, at best.) Historical implementations will require changes in order to comply with IEEE Std 1003.1-2001; however, users are not expected to notice any of these changes. Most of the complexity in ex parsing is to handle three special termination cases:

1.
The !, global, v, and the filter versions of the read and write commands are delimited by <newline>s (they can contain vertical-line characters that are usually shell pipes).

2.
The ex, edit, next, and visual in open and visual mode commands all take ex commands, optionally containing vertical-line characters, as their first arguments.

3.
The s command takes a regular expression as its first argument, and uses the delimiting characters to delimit the command.

Historically, vertical-line characters in the + command argument of the ex, edit, next, vi, and visual commands, and in the pattern and replacement parts of the s command, did not delimit the command, and in the filter cases for read and write, and the !, global, and v commands, they did not delimit the command at all. For example, the following commands are all valid:

:edit +25 | s/abc/ABC/ file.c
:s/ | /PIPE/
:read !spell % | columnate
:global/pattern/p | l
:s/a/b/ | s/c/d | set

Historically, empty or <blank> filled lines in .exrc files and sourced files (as well as EXINIT variables and ex command scripts) were treated as default commands; that is, print commands. IEEE Std 1003.1-2001 specifically requires that they be ignored when encountered in .exrc and sourced files to eliminate a common source of new user error.

Historically, ex commands with multiple adjacent (or <blank>-separated) vertical lines were handled oddly when executed from ex mode. For example, the command ||| <carriage-return>, when the cursor was on line 1, displayed lines 2, 3, and 5 of the file. In addition, the command | would only display the line after the next line, instead of the next two lines. The former worked more logically when executed from vi mode, and displayed lines 2, 3, and 4. IEEE Std 1003.1-2001 requires the vi behavior; that is, a single default command and line number increment for each command separator, and trailing <newline>s after vertical-line separators are discarded.

Historically, ex permitted a single extra colon as a leading command character; for example, :g/pattern/:p was a valid command. IEEE Std 1003.1-2001 generalizes this to require that any number of leading colon characters be stripped.

Historically, any prefix of the delete command could be followed without intervening <blank>s by a flag character because in the command d p, p is interpreted as the buffer p. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the k command could be followed by the mark name without intervening <blank>s. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the s command could be immediately followed by flag and option characters; for example, s/e/E/|s|sgc3p was a valid command. However, flag characters could not stand alone; for example, the commands sp and s l would fail, while the command sgp and s gl would succeed. (Obviously, the '#' flag character was used as a delimiter character if it followed the command.) Another issue was that option characters had to precede flag characters even when the command was fully specified; for example, the command s/e/E/pg would fail, while the command s/e/E/gp would succeed. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the first command name that had a prefix matching the input from the user was the executed command; for example, ve, ver, and vers all executed the version command. Commands were in a specific order, however, so that a matched append, not abbreviate. IEEE Std 1003.1-2001 requires conformance to historical practice. The restriction on command search order for implementations with extensions is to avoid the addition of commands such that the historical prefixes would fail to work portably.

Historical implementations of ex and vi did not correctly handle multiple ex commands, separated by vertical-line characters, that entered or exited visual mode or the editor. Because implementations of vi exist that do not exhibit this failure mode, IEEE Std 1003.1-2001 does not permit it.

The requirement that alphabetic command names consist of all following alphabetic characters up to the next non-alphabetic character means that alphabetic command names must be separated from their arguments by one or more non-alphabetic characters, normally a <blank> or '!' character, except as specified for the exceptions, the delete, k, and s commands.

Historically, the repeated execution of the ex default print commands ( <control>-D, eof, <newline>, <carriage-return>) erased any prompting character and displayed the next lines without scrolling the terminal; that is, immediately below any previously displayed lines. This provided a cleaner presentation of the lines in the file for the user. IEEE Std 1003.1-2001 does not require this behavior because it may be impossible in some situations; however, implementations are strongly encouraged to provide this semantic if possible.

Historically, it was possible to change files in the middle of a command, and have the rest of the command executed in the new file; for example:

:edit +25 file.c | s/abc/ABC/ | 1

was a valid command, and the substitution was attempted in the newly edited file. IEEE Std 1003.1-2001 requires conformance to historical practice. The following commands are examples that exercise the ex parser:

echo 'foo | bar' > file1; echo 'foo/bar' > file2;
vi
:edit +1 | s/|/PIPE/ | w file1 | e file2 | 1 | s/\//SLASH/ | wq

Historically, there was no protection in editor implementations to avoid ex global, v, @, or * commands changing edit buffers during execution of their associated commands. Because this would almost invariably result in catastrophic failure of the editor, and implementations exist that do exhibit these problems, IEEE Std 1003.1-2001 requires that changing the edit buffer during a global or v command, or during a @ or * command for which there will be more than a single execution, be an error. Implementations supporting multiple edit buffers simultaneously are strongly encouraged to apply the same semantics to switching between buffers as well.

The ex command quoting required by IEEE Std 1003.1-2001 is a superset of the quoting in historical implementations of the editor. For example, it was not historically possible to escape a <blank> in a filename; for example, :edit foo\\\ bar would report that too many filenames had been entered for the edit command, and there was no method of escaping a <blank> in the first argument of an edit, ex, next, or visual command at all. IEEE Std 1003.1-2001 extends historical practice, requiring that quoting behavior be made consistent across all ex commands, except for the map, unmap, abbreviate, and unabbreviate commands, which historically used <control>-V instead of backslashes for quoting. For those four commands, IEEE Std 1003.1-2001 requires conformance to historical practice.

Backslash quoting in ex is non-intuitive. Backslash escapes are ignored unless they escape a special character; for example, when performing file argument expansion, the string "\\%" is equivalent to '\%' , not "\<current pathname>". This can be confusing for users because backslash is usually one of the characters that causes shell expansion to be performed, and therefore shell quoting rules must be taken into consideration. Generally, quoting characters are only considered if they escape a special character, and a quoting character must be provided for each layer of parsing for which the character is special. As another example, only a single backslash is necessary for the '\l' sequence in substitute replacement patterns, because the character 'l' is not special to any parsing layer above it.

<control>-V quoting in ex is slightly different from backslash quoting. In the four commands where <control>-V quoting applies ( abbreviate, unabbreviate, map, and unmap), any character may be escaped by a <control>-V whether it would have a special meaning or not. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historical implementations of the editor did not require delimiters within character classes to be escaped; for example, the command :s/[/]// on the string "xxx/yyy" would delete the '/' from the string. IEEE Std 1003.1-2001 disallows this historical practice for consistency and because it places a large burden on implementations by requiring that knowledge of regular expressions be built into the editor parser.

Historically, quoting <newline>s in ex commands was handled inconsistently. In most cases, the <newline> always terminated the command, regardless of any preceding escape character, because backslash characters did not escape <newline>s for most ex commands. However, some ex commands (for example, s, map, and abbreviation) permitted <newline>s to be escaped (although in the case of map and abbreviation, <control>-V characters escaped them instead of backslashes). This was true in not only the command line, but also .exrc and sourced files. For example, the command:

map = foo<control-V><newline>bar

would succeed, although it was sometimes difficult to get the <control>-V and the inserted <newline> passed to the ex parser. For consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that it be possible to escape <newline>s in ex commands at all times, using backslashes for most ex commands, and using <control>-V characters for the map and abbreviation commands. For example, the command print <newline> list is required to be parsed as the single command print <newline> list. While this differs from historical practice, IEEE Std 1003.1-2001 developers believed it unlikely that any script or user depended on the historical behavior.

Historically, an error in a command specified using the -c option did not cause the rest of the -c commands to be discarded. IEEE Std 1003.1-2001 disallows this for consistency with mapped keys, the @, global, source, and v commands, the EXINIT environment variable, and the .exrc files.

Input Editing in ex

One of the common uses of the historical ex editor is over slow network connections. Editors that run in canonical mode can require far less traffic to and from, and far less processing on, the host machine, as well as more easily supporting block-mode terminals. For these reasons, IEEE Std 1003.1-2001 requires that ex be implemented using canonical mode input processing, as was done historically.

IEEE Std 1003.1-2001 does not require the historical 4 BSD input editing characters "word erase" or "literal next". For this reason, it is unspecified how they are handled by ex, although they must have the required effect. Implementations that resolve them after the line has been ended using a <newline> or <control>-M character, and implementations that rely on the underlying system terminal support for this processing, are both conforming. Implementations are strongly urged to use the underlying system functionality, if at all possible, for compatibility with other system text input interfaces.

Historically, when the eof character was used to decrement the autoindent level, the cursor moved to display the new end of the autoindent characters, but did not move the cursor to a new line, nor did it erase the <control>-D character from the line. IEEE Std 1003.1-2001 does not specify that the cursor remain on the same line or that the rest of the line is erased; however, implementations are strongly encouraged to provide the best possible user interface; that is, the cursor should remain on the same line, and any <control>-D character on the line should be erased.

IEEE Std 1003.1-2001 does not require the historical 4 BSD input editing character "reprint", traditionally <control>-R, which redisplayed the current input from the user. For this reason, and because the functionality cannot be implemented after the line has been terminated by the user, IEEE Std 1003.1-2001 makes no requirements about this functionality. Implementations are strongly urged to make this historical functionality available, if possible.

Historically, <control>-Q did not perform a literal next function in ex, as it did in vi. IEEE Std 1003.1-2001 requires conformance to historical practice to avoid breaking historical ex scripts and .exrc files.

eof

Whether the eof character immediately modifies the autoindent characters in the prompt is left unspecified so that implementations can conform in the presence of systems that do not support this functionality. Implementations are encouraged to modify the line and redisplay it immediately, if possible.

The specification of the handling of the eof character differs from historical practice only in that eof characters are not discarded if they follow normal characters in the text input. Historically, they were always discarded.

Command Descriptions in ex

Historically, several commands (for example, global, v, visual, s, write, wq, yank, !, <, >, &, and ~) were executable in empty files (that is, the default address(es) were 0), or permitted explicit addresses of 0 (for example, 0 was a valid address, or 0,0 was a valid range). Addresses of 0, or command execution in an empty file, make sense only for commands that add new text to the edit buffer or write commands (because users may wish to write empty files). IEEE Std 1003.1-2001 requires this behavior for such commands and disallows it otherwise, for consistency and simplicity of specification.

A count to an ex command has been historically corrected to be no greater than the last line in a file; for example, in a five-line file, the command 1,6print would fail, but the command 1print300 would succeed. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the use of flags in ex commands could be obscure. General historical practice was as described by IEEE Std 1003.1-2001, but there were some special cases. For instance, the list, number, and print commands ignored trailing address offsets; for example, 3p +++# would display line 3, and 3 would be the current line after the execution of the command. The open and visual commands ignored both the trailing offsets and the trailing flags. Also, flags specified to the open and visual commands interacted badly with the list edit option, and setting and then unsetting it during the open/visual session would cause vi to stop displaying lines in the specified format. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit any of these exceptions to the general rule.

IEEE Std 1003.1-2001 uses the word copy in several places when discussing buffers. This is not intended to imply implementation.

Historically, ex users could not specify numeric buffers because of the ambiguity this would cause; for example, in the command 3 delete 2, it is unclear whether 2 is a buffer name or a count. IEEE Std 1003.1-2001 requires conformance to historical practice by default, but does not preclude extensions.

Historically, the contents of the unnamed buffer were frequently discarded after commands that did not explicitly affect it; for example, when using the edit command to switch files. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

The ex utility did not historically have access to the numeric buffers, and, furthermore, deleting lines in ex did not modify their contents. For example, if, after doing a delete in vi, the user switched to ex, did another delete, and then switched back to vi, the contents of the numeric buffers would not have changed. IEEE Std 1003.1-2001 requires conformance to historical practice. Numeric buffers are described in the ex utility in order to confine the description of buffers to a single location in IEEE Std 1003.1-2001.

The metacharacters that trigger shell expansion in file arguments match historical practice, as does the method for doing shell expansion. Implementations wishing to provide users with the flexibility to alter the set of metacharacters are encouraged to provide a shellmeta string edit option.

Historically, ex commands executed from vi refreshed the screen when it did not strictly need to do so; for example, :!date > /dev/null does not require a screen refresh because the output of the UNIX date command requires only a single line of the screen. IEEE Std 1003.1-2001 requires that the screen be refreshed if it has been overwritten, but makes no requirements as to how an implementation should make that determination. Implementations may prompt and refresh the screen regardless.

Abbreviate

Historical practice was that characters that were entered as part of an abbreviation replacement were subject to map expansions, the showmatch edit option, further abbreviation expansions, and so on; that is, they were logically pushed onto the terminal input queue, and were not a simple replacement. IEEE Std 1003.1-2001 requires conformance to historical practice. Historical practice was that whenever a non-word character (that had not been escaped by a <control>-V) was entered after a word character, vi would check for abbreviations. The check was based on the type of the character entered before the word character of the word/non-word pair that triggered the check. The word character of the word/non-word pair that triggered the check and all characters entered before the trigger pair that were of that type were included in the check, with the exception of <blank>s, which always delimited the abbreviation.

This means that, for the abbreviation to work, the lhs must end with a word character, there can be no transitions from word to non-word characters (or vice versa) other than between the last and next-to-last characters in the lhs, and there can be no <blank>s in the lhs. In addition, because of the historical quoting rules, it was impossible to enter a literal <control>-V in the lhs. IEEE Std 1003.1-2001 requires conformance to historical practice. Historical implementations did not inform users when abbreviations that could never be used were entered; implementations are strongly encouraged to do so.

For example, the following abbreviations will work:

:ab (p  REPLACE
:ab p   REPLACE
:ab ((p REPLACE

The following abbreviations will not work:

:ab (   REPLACE
:ab (pp REPLACE

Historical practice is that words on the vi colon command line were subject to abbreviation expansion, including the arguments to the abbrev (and more interestingly) the unabbrev command. Because there are implementations that do not do abbreviation expansion for the first argument to those commands, this is permitted, but not required, by IEEE Std 1003.1-2001. However, the following sequence:

:ab foo bar
:ab foo baz

resulted in the addition of an abbreviation of "baz" for the string "bar" in historical ex/ vi, and the sequence:

:ab foo1 bar
:ab foo2 bar
:unabbreviate foo2

deleted the abbreviation "foo1" , not "foo2" . These behaviors are not permitted by IEEE Std 1003.1-2001 because they clearly violate the expectations of the user.

It was historical practice that <control>-V, not backslash, characters be interpreted as escaping subsequent characters in the abbreviate command. IEEE Std 1003.1-2001 requires conformance to historical practice; however, it should be noted that an abbreviation containing a <blank> will never work.

Append

Historically, any text following a vertical-line command separator after an append, change, or insert command became part of the insert text. For example, in the command:

:g/pattern/append|stuff1

a line containing the text "stuff1" would be appended to each line matching pattern. It was also historically valid to enter:

:append|stuff1
stuff2
.

and the text on the ex command line would be appended along with the text inserted after it. There was an historical bug, however, that the user had to enter two terminating lines (the '.' lines) to terminate text input mode in this case. IEEE Std 1003.1-2001 requires conformance to historical practice, but disallows the historical need for multiple terminating lines.

Change

See the RATIONALE for the append command. Historical practice for cursor positioning after the change command when no text is input, is as described in IEEE Std 1003.1-2001. However, one System V implementation is known to have been modified such that the cursor is positioned on the first address specified, and not on the line before the first address. IEEE Std 1003.1-2001 disallows this modification for consistency.

Historically, the change command did not support buffer arguments, although some implementations allow the specification of an optional buffer. This behavior is neither required nor disallowed by IEEE Std 1003.1-2001.

Change Directory

A common extension in ex implementations is to use the elements of a cdpath edit option as prefix directories for path arguments to chdir that are relative pathnames and that do not have '.' or ".." as their first component. Elements in the cdpath edit option are colon-separated. The initial value of the cdpath edit option is the value of the shell CDPATH environment variable. This feature was not included in IEEE Std 1003.1-2001 because it does not exist in any of the implementations considered historical practice.

Copy

Historical implementations of ex permitted copies to lines inside of the specified range; for example, :2,5copy3 was a valid command. IEEE Std 1003.1-2001 requires conformance to historical practice.

Delete

IEEE Std 1003.1-2001 requires support for the historical parsing of a delete command followed by flags, without any intervening <blank>s. For example:

1dp
Deletes the first line and prints the line that was second.
1delep
As for 1dp.
1d
Deletes the first line, saving it in buffer p.
1d p1l
(Pee-one-ell.) Deletes the first line, saving it in buffer p, and listing the line that was second.

Edit

Historically, any ex command could be entered as a + command argument to the edit command, although some (for example, insert and append) were known to confuse historical implementations. For consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that any command be supported as an argument to the edit command.

Historically, the command argument was executed with the current line set to the last line of the file, regardless of whether the edit command was executed from visual mode or not. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the + command specified to the edit and next commands was delimited by the first <blank>, and there was no way to quote them. For consistency, IEEE Std 1003.1-2001 requires that the usual ex backslash quoting be provided.

Historically, specifying the + command argument to the edit command required a filename to be specified as well; for example, :edit +100 would always fail. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this usage to fail for that reason.

Historically, only the cursor position of the last file edited was remembered by the editor. IEEE Std 1003.1-2001 requires that this be supported; however, implementations are permitted to remember and restore the cursor position for any file previously edited.

File

Historical versions of the ex editor file command displayed a current line and number of lines in the edit buffer of 0 when the file was empty, while the vi <control>-G command displayed a current line and number of lines in the edit buffer of 1 in the same situation. IEEE Std 1003.1-2001 does not permit this discrepancy, instead requiring that a message be displayed indicating that the file is empty.

Global

The two-pass operation of the global and v commands is not intended to imply implementation, only the required result of the operation.

The current line and column are set as specified for the individual ex commands. This requirement is cumulative; that is, the current line and column must track across all the commands executed by the global or v commands.

Insert

See the RATIONALE for the append command.

Historically, insert could not be used with an address of zero; that is, not when the edit buffer was empty. IEEE Std 1003.1-2001 requires that this command behave consistently with the append command.

Join

The action of the join command in relation to the special characters is only defined for the POSIX locale because the correct amount of white space after a period varies; in Japanese none is required, in French only a single space, and so on.

List

The historical output of the list command was potentially ambiguous. The standard developers believed correcting this to be more important than adhering to historical practice, and IEEE Std 1003.1-2001 requires unambiguous output.

Map

Historically, command mode maps only applied to command names; for example, if the character 'x' was mapped to 'y' , the command fx searched for the 'x' character, not the 'y' character. IEEE Std 1003.1-2001 requires this behavior. Historically, entering <control>-V as the first character of a vi command was an error. Several implementations have extended the semantics of vi such that <control>-V means that the subsequent command character is not mapped. This is permitted, but not required, by IEEE Std 1003.1-2001. Regardless, using <control>-V to escape the second or later character in a sequence of characters that might match a map command, or any character in text input mode, is historical practice, and stops the entered keys from matching a map. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historical implementations permitted digits to be used as a map command lhs, but then ignored the map. IEEE Std 1003.1-2001 requires that the mapped digits not be ignored.

The historical implementation of the map command did not permit map commands that were more than a single character in length if the first character was printable. This behavior is permitted, but not required, by IEEE Std 1003.1-2001.

Historically, mapped characters were remapped unless the remap edit option was not set, or the prefix of the mapped characters matched the mapping characters; for example, in the map:

:map ab abcd

the characters "ab" were used as is and were not remapped, but the characters "cd" were mapped if appropriate. This can cause infinite loops in the vi mapping mechanisms. IEEE Std 1003.1-2001 requires conformance to historical practice, and that such loops be interruptible.

Text input maps had the same problems with expanding the lhs for the ex map! and unmap! command as did the ex abbreviate and unabbreviate commands. See the RATIONALE for the ex abbreviate command. IEEE Std 1003.1-2001 requires similar modification of some historical practice for the map and unmap commands, as described for the abbreviate and unabbreviate commands.

Historically, maps that were subsets of other maps behaved differently depending on the order in which they were defined. For example:

:map! ab     short
:map! abc    long

would always translate the characters "ab" to "short" , regardless of how fast the characters "abc" were entered. If the entry order was reversed:

:map! abc    long
:map! ab     short

the characters "ab" would cause the editor to pause, waiting for the completing 'c' character, and the characters might never be mapped to "short" . For consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that the shortest match be used at all times.

The length of time the editor spends waiting for the characters to complete the lhs is unspecified because the timing capabilities of systems are often inexact and variable, and it may depend on other factors such as the speed of the connection. The time should be long enough for the user to be able to complete the sequence, but not long enough for the user to have to wait. Some implementations of vi have added a keytime option, which permits users to set the number of 0,1 seconds the editor waits for the completing characters. Because mapped terminal function and cursor keys tend to start with an <ESC> character, and <ESC> is the key ending vi text input mode, maps starting with <ESC> characters are generally exempted from this timeout period, or, at least timed out differently.

Mark

Historically, users were able to set the "previous context" marks explicitly. In addition, the ex commands " and '` and the vi commands ", ``, `', and '` all referred to the same mark. In addition, the previous context marks were not set if the command, with which the address setting the mark was associated, failed. IEEE Std 1003.1-2001 requires conformance to historical practice. Historically, if marked lines were deleted, the mark was also deleted, but would reappear if the change was undone. IEEE Std 1003.1-2001 requires conformance to historical practice.

The description of the special events that set the ` and ' marks matches historical practice. For example, historically the command /a/,/b/ did not set the ` and ' marks, but the command /a/,/b/delete did.

Next

Historically, any ex command could be entered as a + command argument to the next command, although some (for example, insert and append) were known to confuse historical implementations. IEEE Std 1003.1-2001 requires that any command be permitted and that it behave as specified. The next command can accept more than one file, so usage such as:

next `ls [abc] `

is valid; it need not be valid for the edit or read commands, for example, because they expect only one filename.

Historically, the next command behaved differently from the :rewind command in that it ignored the force flag if the autowrite flag was set. For consistency, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, the next command positioned the cursor as if the file had never been edited before, regardless. IEEE Std 1003.1-2001 does not permit this behavior, for consistency with the edit command.

Implementations wanting to provide a counterpart to the next command that edited the previous file have used the command prev[ious], which takes no file argument. IEEE Std 1003.1-2001 does not require this command.

Open

Historically, the open command would fail if the open edit option was not set. IEEE Std 1003.1-2001 does not mention the open edit option and does not require this behavior. Some historical implementations do not permit entering open mode from open or visual mode, only from ex mode. For consistency, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, entering open mode from the command line (that is, vi +open) resulted in anomalous behaviors; for example, the ex file and set commands, and the vi command <control>-G did not work. For consistency, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, the open command only permitted '/' characters to be used as the search pattern delimiter. For consistency, IEEE Std 1003.1-2001 requires that the search delimiters used by the s, global, and v commands be accepted as well.

Preserve

The preserve command does not historically cause the file to be considered unmodified for the purposes of future commands that may exit the editor. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historical documentation stated that mail was not sent to the user when preserve was executed; however, historical implementations did send mail in this case. IEEE Std 1003.1-2001 requires conformance to the historical implementations.

Print

The writing of NUL by the print command is not specified as a special case because the standard developers did not want to require ex to support NUL characters. Historically, characters were displayed using the ARPA standard mappings, which are as follows:

1.
Printable characters are left alone.

2.
Control characters less than \177 are represented as '^' followed by the character offset from the '@' character in the ASCII map; for example, \007 is represented as '^G' .

3.
\177 is represented as '^' followed by '?' .

The display of characters having their eighth bit set was less standard. Existing implementations use hex (0x00), octal (\000), and a meta-bit display. (The latter displayed bytes that had their eighth bit set as the two characters "M-" followed by the seven-bit display as described above.) The latter probably has the best claim to historical practice because it was used for the -v option of 4 BSD and 4 BSD-derived versions of the cat utility since 1980.

No specific display format is required by IEEE Std 1003.1-2001.

Explicit dependence on the ASCII character set has been avoided where possible, hence the use of the phrase an "implementation-defined multi-character sequence" for the display of non-printable characters in preference to the historical usage of, for instance, "^I" for the <tab>. Implementations are encouraged to conform to historical practice in the absence of any strong reason to diverge.

Historically, all ex commands beginning with the letter 'p' could be entered using capitalized versions of the commands; for example, P[rint], Pre[serve], and Pu[t] were all valid command names. IEEE Std 1003.1-2001 permits, but does not require, this historical practice because capital forms of the commands are used by some implementations for other purposes.

Put

Historically, an ex put command, executed from open or visual mode, was the same as the open or visual mode P command, if the buffer was named and was cut in character mode, and the same as the p command if the buffer was named and cut in line mode. If the unnamed buffer was the source of the text, the entire line from which the text was taken was usually put, and the buffer was handled as if in line mode, but it was possible to get extremely anomalous behavior. In addition, using the Q command to switch into ex mode, and then doing a put often resulted in errors as well, such as appending text that was unrelated to the (supposed) contents of the buffer. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit these behaviors. All ex put commands are required to operate in line mode, and the contents of the buffers are not altered by changing the mode of the editor.

Read

Historically, an ex read command executed from open or visual mode, executed in an empty file, left an empty line as the first line of the file. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior. Historically, a read in open or visual mode from a program left the cursor at the last line read in, not the first. For consistency, IEEE Std 1003.1-2001 does not permit this behavior.

Historical implementations of ex were unable to undo read commands that read from the output of a program. For consistency, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, the ex and vi message after a successful read or write command specified "characters", not "bytes". IEEE Std 1003.1-2001 requires that the number of bytes be displayed, not the number of characters, because it may be difficult in multi-byte implementations to determine the number of characters read. Implementations are encouraged to clarify the message displayed to the user.

Historically, reads were not permitted on files other than type regular, except that FIFO files could be read (probably only because they did not exist when ex and vi were originally written). Because the historical ex evaluated read! and read ! equivalently, there can be no optional way to force the read. IEEE Std 1003.1-2001 permits, but does not require, this behavior.

Recover

Some historical implementations of the editor permitted users to recover the edit buffer contents from a previous edit session, and then exit without saving those contents (or explicitly discarding them). The intent of IEEE Std 1003.1-2001 in requiring that the edit buffer be treated as already modified is to prevent this user error.

Rewind

Historical implementations supported the rewind command when the user was editing the first file in the list; that is, the file that the rewind command would edit. IEEE Std 1003.1-2001 requires conformance to historical practice.

Substitute

Historically, ex accepted an r option to the s command. The effect of the r option was to use the last regular expression used in any command as the pattern, the same as the ~ command. The r option is not required by IEEE Std 1003.1-2001. Historically, the c and g options were toggled; for example, the command :s/abc/def/ was the same as s/abc/def/ccccgggg. For simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

The tilde command is often used to replace the last search RE. For example, in the sequence:

s/red/blue/
/green
~

the ~ command is equivalent to:

s/green/blue/

Historically, ex accepted all of the following forms:

s/abc/def/
s/abc/def
s/abc/
s/abc

IEEE Std 1003.1-2001 requires conformance to this historical practice.

The s command presumes that the '^' character only occupies a single column in the display. Much of the ex and vi specification presumes that the <space> only occupies a single column in the display. There are no known character sets for which this is not true.

Historically, the final column position for the substitute commands was based on previous column movements; a search for a pattern followed by a substitution would leave the column position unchanged, while a 0 command followed by a substitution would change the column position to the first non- <blank>. For consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that the final column position always be set to the first non- <blank>.

Set

Historical implementations redisplayed all of the options for each occurrence of the all keyword. IEEE Std 1003.1-2001 permits, but does not require, this behavior.

Tag

No requirement is made as to where ex and vi shall look for the file referenced by the tag entry. Historical practice has been to look for the path found in the tags file, based on the current directory. A useful extension found in some implementations is to look based on the directory containing the tags file that held the entry, as well. No requirement is made as to which reference for the tag in the tags file is used. This is deliberate, in order to permit extensions such as multiple entries in a tags file for a tag.

Because users often specify many different tags files, some of which need not be relevant or exist at any particular time, IEEE Std 1003.1-2001 requires that error messages about problem tags files be displayed only if the requested tag is not found, and then, only once for each time that the tag edit option is changed.

The requirement that the current edit buffer be unmodified is only necessary if the file indicated by the tag entry is not the same as the current file (as defined by the current pathname). Historically, the file would be reloaded if the filename had changed, as well as if the filename was different from the current pathname. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior, requiring that the name be the only factor in the decision.

Historically, vi only searched for tags in the current file from the current cursor to the end of the file, and therefore, if the wrapscan option was not set, tags occurring before the current cursor were not found. IEEE Std 1003.1-2001 considers this a bug, and implementations are required to search for the first occurrence in the file, regardless.

Undo

The undo description deliberately uses the word "modified". The undo command is not intended to undo commands that replace the contents of the edit buffer, such as edit, next, tag, or recover.

Cursor positioning after the undo command was inconsistent in the historical vi, sometimes attempting to restore the original cursor position ( global, undo, and v commands), and sometimes, in the presence of maps, placing the cursor on the last line added or changed instead of the first. IEEE Std 1003.1-2001 requires a simplified behavior for consistency and simplicity of specification.

Version

The version command cannot be exactly specified since there is no widely-accepted definition of what the version information should contain. Implementations are encouraged to do something reasonably intelligent.

Write

Historically, the ex and vi message after a successful read or write command specified "characters", not "bytes". IEEE Std 1003.1-2001 requires that the number of bytes be displayed, not the number of characters because it may be difficult in multi-byte implementations to determine the number of characters written. Implementations are encouraged to clarify the message displayed to the user.

Implementation-defined tests are permitted so that implementations can make additional checks; for example, for locks or file modification times.

Historically, attempting to append to a nonexistent file caused an error. It has been left unspecified in IEEE Std 1003.1-2001 to permit implementations to let the write succeed, so that the append semantics are similar to those of the historical csh.

Historical vi permitted empty edit buffers to be written. However, since the way vi got around dealing with "empty" files was to always have a line in the edit buffer, no matter what, it wrote them as files of a single, empty line. IEEE Std 1003.1-2001 does not permit this behavior.

Historically, ex restored standard output and standard error to their values as of when ex was invoked, before writes to programs were performed. This could disturb the terminal configuration as well as be a security issue for some terminals. IEEE Std 1003.1-2001 does not permit this, requiring that the program output be captured and displayed as if by the ex print command.

Adjust Window

Historically, the line count was set to the value of the scroll option if the type character was end-of-file. This feature was broken on most historical implementations long ago, however, and is not documented anywhere. For this reason, IEEE Std 1003.1-2001 is resolutely silent.

Historically, the z command was <blank>-sensitive and z + and z - did different things than z+ and z- because the type could not be distinguished from a flag. (The commands z . and z = were historically invalid.) IEEE Std 1003.1-2001 requires conformance to this historical practice.

Historically, the z command was further <blank>-sensitive in that the count could not be <blank>-delimited; for example, the commands z= 5 and z- 5 were also invalid. Because the count is not ambiguous with respect to either the type character or the flags, this is not permitted by IEEE Std 1003.1-2001.

Escape

Historically, ex filter commands only read the standard output of the commands, letting standard error appear on the terminal as usual. The vi utility, however, read both standard output and standard error. IEEE Std 1003.1-2001 requires the latter behavior for both ex and vi, for consistency.

Shift Left and Shift Right

Historically, it was possible to add shift characters to increase the effect of the command; for example, <<< outdented (or >>> indented) the lines 3 levels of indentation instead of the default 1. IEEE Std 1003.1-2001 requires conformance to historical practice.

<control>-D

Historically, the <control>-D command erased the prompt, providing the user with an unbroken presentation of lines from the edit buffer. This is not required by IEEE Std 1003.1-2001; implementations are encouraged to provide it if possible. Historically, the <control>-D command took, and then ignored, a count. IEEE Std 1003.1-2001 does not permit this behavior.

Write Line Number

Historically, the ex = command, when executed in ex mode in an empty edit buffer, reported 0, and from open or visual mode, reported 1. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Execute

Historically, ex did not correctly handle the inclusion of text input commands (that is, append, insert, and change) in executed buffers. IEEE Std 1003.1-2001 does not permit this exclusion for consistency.

Historically, the logical contents of the buffer being executed did not change if the buffer itself were modified by the commands being executed; that is, buffer execution did not support self-modifying code. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the @ command took a range of lines, and the @ buffer was executed once per line, with the current line ( '.' ) set to each specified line. IEEE Std 1003.1-2001 requires conformance to historical practice.

Some historical implementations did not notice if errors occurred during buffer execution. This, coupled with the ability to specify a range of lines for the ex @ command, makes it trivial to cause them to drop core. IEEE Std 1003.1-2001 requires that implementations stop buffer execution if any error occurs, if the specified line doesn't exist, or if the contents of the edit buffer itself are replaced (for example, the buffer executes the ex :edit command).

Regular Expressions in ex

Historical practice is that the characters in the replacement part of the last s command-that is, those matched by entering a '~' in the regular expression-were not further expanded by the regular expression engine. So, if the characters contained the string "a.," they would match 'a' followed by ".," and not 'a' followed by any character. IEEE Std 1003.1-2001 requires conformance to historical practice.

Edit Options in ex

The following paragraphs describe the historical behavior of some edit options that were not, for whatever reason, included in IEEE Std 1003.1-2001. Implementations are strongly encouraged to only use these names if the functionality described here is fully supported.

extended
The extended edit option has been used in some implementations of vi to provide extended regular expressions instead of basic regular expressions This option was omitted from IEEE Std 1003.1-2001 because it is not widespread historical practice.
flash
The flash edit option historically caused the screen to flash instead of beeping on error. This option was omitted from IEEE Std 1003.1-2001 because it is not found in some historical implementations.
hardtabs
The hardtabs edit option historically defined the number of columns between hardware tab settings. This option was omitted from IEEE Std 1003.1-2001 because it was believed to no longer be generally useful.
modeline
The modeline (sometimes named modelines) edit option historically caused ex or vi to read the five first and last lines of the file for editor commands. This option is a security problem, and vendors are strongly encouraged to delete it from historical implementations.
open
The open edit option historically disallowed the ex open and visual commands. This edit option was omitted because these commands are required by IEEE Std 1003.1-2001.
optimize
The optimize edit option historically expedited text throughput by setting the terminal to not do automatic <carriage-return>s when printing more than one logical line of output. This option was omitted from IEEE Std 1003.1-2001 because it was intended for terminals without addressable cursors, which are rarely, if ever, still used.
ruler
The ruler edit option has been used in some implementations of vi to present a current row/column ruler for the user. This option was omitted from IEEE Std 1003.1-2001 because it is not widespread historical practice.
sourceany
The sourceany edit option historically caused ex or vi to source start-up files that were owned by users other than the user running the editor. This option is a security problem, and vendors are strongly encouraged to remove it from their implementations.
timeout
The timeout edit option historically enabled the (now standard) feature of only waiting for a short period before returning keys that could be part of a macro. This feature was omitted from IEEE Std 1003.1-2001 because its behavior is now standard, it is not widely useful, and it was rarely documented.
verbose
The verbose edit option has been used in some implementations of vi to cause vi to output error messages for common errors; for example, attempting to move the cursor past the beginning or end of the line instead of only alerting the screen. (The historical vi only alerted the terminal and presented no message for such errors. The historical editor option terse did not select when to present error messages, it only made existing error messages more or less verbose.) This option was omitted from IEEE Std 1003.1-2001 because it is not widespread historical practice; however, implementors are encouraged to use it if they wish to provide error messages for naive users.
wraplen
The wraplen edit option has been used in some implementations of vi to specify an automatic margin measured from the left margin instead of from the right margin. This is useful when multiple screen sizes are being used to edit a single file. This option was omitted from IEEE Std 1003.1-2001 because it is not widespread historical practice; however, implementors are encouraged to use it if they add this functionality.

autoindent, ai

Historically, the command 0a did not do any autoindentation, regardless of the current indentation of line 1. IEEE Std 1003.1-2001 requires that any indentation present in line 1 be used.

autoprint, ap

Historically, the autoprint edit option was not completely consistent or based solely on modifications to the edit buffer. Exceptions were the read command (when reading from a file, but not from a filter), the append, change, insert, global, and v commands, all of which were not affected by autoprint, and the tag command, which was affected by autoprint. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the autoprint option only applied to the last of multiple commands entered using vertical-bar delimiters; for example, delete <newline> was affected by autoprint, but delete|version <newline> was not. IEEE Std 1003.1-2001 requires conformance to historical practice.

autowrite, aw

Appending the '!' character to the ex next command to avoid performing an automatic write was not supported in historical implementations. IEEE Std 1003.1-2001 requires that the behavior match the other ex commands for consistency.

ignorecase, ic

Historical implementations of case-insensitive matching (the ignorecase edit option) lead to counterintuitive situations when uppercase characters were used in range expressions. Historically, the process was as follows:

1.
Take a line of text from the edit buffer.

2.
Convert uppercase to lowercase in text line.

3.
Convert uppercase to lowercase in regular expressions, except in character class specifications.

4.
Match regular expressions against text.

This would mean that, with ignorecase in effect, the text:

The cat sat on the mat

would be matched by

/^the/

but not by:

/^[A-Z]he/

For consistency with other commands implementing regular expressions, IEEE Std 1003.1-2001 does not permit this behavior.

paragraphs, para

The ISO POSIX-2:1993 standard made the default paragraphs and sections edit options implementation-defined, arguing they were historically oriented to the UNIX system troff text formatter, and a "portable user" could use the {, }, [[, ]], (, and ) commands in open or visual mode and have the cursor stop in unexpected places. IEEE Std 1003.1-2001 specifies their values in the POSIX locale because the unusual grouping (they only work when grouped into two characters at a time) means that they cannot be used for general-purpose movement, regardless.

readonly

Implementations are encouraged to provide the best possible information to the user as to the read-only status of the file, with the exception that they should not consider the current special privileges of the process. This provides users with a safety net because they must force the overwrite of read-only files, even when running with additional privileges.

The readonly edit option specification largely conforms to historical practice. The only difference is that historical implementations did not notice that the user had set the readonly edit option in cases where the file was already marked read-only for some reason, and would therefore reinitialize the readonly edit option the next time the contents of the edit buffer were replaced. This behavior is disallowed by IEEE Std 1003.1-2001.

report

The requirement that lines copied to a buffer interact differently than deleted lines is historical practice. For example, if the report edit option is set to 3, deleting 3 lines will cause a report to be written, but 4 lines must be copied before a report is written.

The requirement that the ex global, v, open, undo, and visual commands present reports based on the total number of lines added or deleted during the command execution, and that commands executed by the global and v commands not present reports, is historical practice. IEEE Std 1003.1-2001 extends historical practice by requiring that buffer execution be treated similarly. The reasons for this are two-fold. Historically, only the report by the last command executed from the buffer would be seen by the user, as each new report would overwrite the last. In addition, the standard developers believed that buffer execution had more in common with global and v commands than it did with other ex commands, and should behave similarly, for consistency and simplicity of specification.

showmatch, sm

The length of time the cursor spends on the matching character is unspecified because the timing capabilities of systems are often inexact and variable. The time should be long enough for the user to notice, but not long enough for the user to become annoyed. Some implementations of vi have added a matchtime option that permits users to set the number of 0,1 second intervals the cursor pauses on the matching character.

showmode

The showmode option has been used in some historical implementations of ex and vi to display the current editing mode when in open or visual mode. The editing modes have generally included "command" and "input", and sometimes other modes such as "replace" and "change". The string was usually displayed on the bottom line of the screen at the far right-hand corner. In addition, a preceding '*' character often denoted whether the contents of the edit buffer had been modified. The latter display has sometimes been part of the showmode option, and sometimes based on another option. This option was not available in the 4 BSD historical implementation of vi, but was viewed as generally useful, particularly to novice users, and is required by IEEE Std 1003.1-2001.

The smd shorthand for the showmode option was not present in all historical implementations of the editor. IEEE Std 1003.1-2001 requires it, for consistency.

Not all historical implementations of the editor displayed a mode string for command mode, differentiating command mode from text input mode by the absence of a mode string. IEEE Std 1003.1-2001 permits this behavior for consistency with historical practice, but implementations are encouraged to provide a display string for both modes.

slowopen

Historically the slowopen option was automatically set if the terminal baud rate was less than 1200 baud, or if the baud rate was 1200 baud and the redraw option was not set. The slowopen option had two effects. First, when inserting characters in the middle of a line, characters after the cursor would not be pushed ahead, but would appear to be overwritten. Second, when creating a new line of text, lines after the current line would not be scrolled down, but would appear to be overwritten. In both cases, ending text input mode would cause the screen to be refreshed to match the actual contents of the edit buffer. Finally, terminals that were sufficiently intelligent caused the editor to ignore the slowopen option. IEEE Std 1003.1-2001 permits most historical behavior, extending historical practice to require slowopen behaviors if the edit option is set by the user.

tags

The default path for tags files is left unspecified as implementations may have their own tags implementations that do not correspond to the historical ones. The default tags option value should probably at least include the file ./tags.

term

Historical implementations of ex and vi ignored changes to the term edit option after the initial terminal information was loaded. This is permitted by IEEE Std 1003.1-2001; however, implementations are encouraged to permit the user to modify their terminal type at any time.

terse

Historically, the terse edit option optionally provided a shorter, less descriptive error message, for some error messages. This is permitted, but not required, by IEEE Std 1003.1-2001. Historically, most common visual mode errors (for example, trying to move the cursor past the end of a line) did not result in an error message, but simply alerted the terminal. Implementations wishing to provide messages for novice users are urged to do so based on the edit option verbose, and not terse.

window

In historical implementations, the default for the window edit option was based on the baud rate as follows:

1.
If the baud rate was less than 1200, the edit option w300 set the window value; for example, the line:

set w300=12

would set the window option to 12 if the baud rate was less than 1200.

2.
If the baud rate was equal to 1200, the edit option w1200 set the window value.

3.
If the baud rate was greater than 1200, the edit option w9600 set the window value.

The w300, w1200, and w9600 options do not appear in IEEE Std 1003.1-2001 because of their dependence on specific baud rates.

In historical implementations, the size of the window displayed by various commands was related to, but not necessarily the same as, the window edit option. For example, the size of the window was set by the ex command visual 10, but it did not change the value of the window edit option. However, changing the value of the window edit option did change the number of lines that were displayed when the screen was repainted. IEEE Std 1003.1-2001 does not permit this behavior in the interests of consistency and simplicity of specification, and requires that all commands that change the number of lines that are displayed do it by setting the value of the window edit option.

wrapmargin, wm

Historically, the wrapmargin option did not affect maps inserting characters that also had associated counts; for example :map K 5aABC DEF. Unfortunately, there are widely used maps that depend on this behavior. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, wrapmargin was calculated using the column display width of all characters on the screen. For example, an implementation using "^I" to represent <tab>s when the list edit option was set, where '^' and 'I' each took up a single column on the screen, would calculate the wrapmargin based on a value of 2 for each <tab>. The number edit option similarly changed the effective length of the line as well. IEEE Std 1003.1-2001 requires conformance to historical practice.

FUTURE DIRECTIONS

None.

SEE ALSO

Command Search and Execution , ctags , ed , sed , sh , stty , vi , the System Interfaces volume of IEEE Std 1003.1-2001, access()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


xargs(1p)

XARGS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

xargs - construct argument lists and invoke utility

SYNOPSIS

xargs [-t][-p]][-E eofstr][-I replstr][-L number][-n number [-x]]
[-s size][utility [argument...]]

DESCRIPTION

The xargs utility shall construct a command line consisting of the utility and argument operands specified followed by as many arguments read in sequence from standard input as fit in length and number constraints specified by the options. The xargs utility shall then invoke the constructed command line and wait for its completion. This sequence shall be repeated until one of the following occurs:

*
An end-of-file condition is detected on standard input.

*
The logical end-of-file string (see the -E eofstr option) is found on standard input after double-quote processing, apostrophe processing, and backslash escape processing (see next paragraph).

*
An invocation of a constructed command line returns an exit status of 255.

The application shall ensure that arguments in the standard input are separated by unquoted <blank>s, unescaped <blank>s, or <newline>s. A string of zero or more non-double-quote ( ' )' characters and non- <newline>s can be quoted by enclosing them in double-quotes. A string of zero or more non-apostrophe ( '" ) characters and non- <newline>s can be quoted by enclosing them in apostrophes. Any unquoted character can be escaped by preceding it with a backslash. The utility named by utility shall be executed one or more times until the end-of-file is reached or the logical end-of file string is found. The results are unspecified if the utility named by utility attempts to read from its standard input.

The generated command line length shall be the sum of the size in bytes of the utility name and each argument treated as strings, including a null byte terminator for each of these strings. The xargs utility shall limit the command line length such that when the command line is invoked, the combined argument and environment lists (see the exec family of functions in the System Interfaces volume of IEEE Std 1003.1-2001) shall not exceed {ARG_MAX}-2048 bytes. Within this constraint, if neither the -n nor the -s option is specified, the default command line length shall be at least {LINE_MAX}.

OPTIONS

The xargs utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-E eofstr
Use eofstr as the logical end-of-file string. If -E is not specified, it is unspecified whether the logical end-of-file string is the underscore character ( '_' ) or the end-of-file string capability is disabled. When eofstr is the null string, the logical end-of-file string capability shall be disabled and underscore characters shall be taken literally.
-I replstr
Insert mode: utility is executed for each line from standard input, taking the entire line as a single argument, inserting it in arguments for each occurrence of replstr. A maximum of five arguments in arguments can each contain one or more instances of replstr. Any <blank>s at the beginning of each line shall be ignored. Constructed arguments cannot grow larger than 255 bytes. Option -x shall be forced on.
-L number
The utility shall be executed for each non-empty number lines of arguments from standard input. The last invocation of utility shall be with fewer lines of arguments if fewer than number remain. A line is considered to end with the first <newline> unless the last character of the line is a <blank>; a trailing <blank> signals continuation to the next non-empty line, inclusive. The -L and -n options are mutually-exclusive; the last one specified shall take effect.
-n number
Invoke utility using as many standard input arguments as possible, up to number (a positive decimal integer) arguments maximum. Fewer arguments shall be used if:
*
The command line length accumulated exceeds the size specified by the -s option (or {LINE_MAX} if there is no -s option).

*
The last iteration has fewer than number, but not zero, operands remaining.

-p
Prompt mode: the user is asked whether to execute utility at each invocation. Trace mode ( -t) is turned on to write the command instance to be executed, followed by a prompt to standard error. An affirmative response read from /dev/tty shall execute the command; otherwise, that particular invocation of utility shall be skipped.
-s size
Invoke utility using as many standard input arguments as possible yielding a command line length less than size (a positive decimal integer) bytes. Fewer arguments shall be used if:
*
The total number of arguments exceeds that specified by the -n option.

*
The total number of lines exceeds that specified by the -L option.

*
End-of-file is encountered on standard input before size bytes are accumulated.

Values of size up to at least {LINE_MAX} bytes shall be supported, provided that the constraints specified in the DESCRIPTION are met. It shall not be considered an error if a value larger than that supported by the implementation or exceeding the constraints specified in the DESCRIPTION is given; xargs shall use the largest value it supports within the constraints.

-t
Enable trace mode. Each generated command line shall be written to standard error just prior to invocation.
-x
Terminate if a command line containing number arguments (see the -n option above) or number lines (see the -L option above) will not fit in the implied or specified size (see the -s option above).

OPERANDS

The following operands shall be supported:

utility
The name of the utility to be invoked, found by search path using the PATH environment variable, described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables. If utility is omitted, the default shall be the echo utility. If the utility operand names any of the special built-in utilities in Special Built-In Utilities , the results are undefined.
argument
An initial option or operand for the invocation of utility.

STDIN

The standard input shall be a text file. The results are unspecified if an end-of-file condition is detected immediately following an escaped <newline>.

INPUT FILES

The file /dev/tty shall be used to read responses required by the -p option.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of xargs:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.
LC_MESSAGES
Determine the locale for the processing of affirmative responses and that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the location of utility, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used for diagnostic messages and the -t and -p options. If the -t option is specified, the utility and its constructed argument list shall be written to standard error, as it will be invoked, prior to invocation. If -p is specified, a prompt of the following format shall be written (in the POSIX locale):

"?..."

at the end of the line of the output from -t.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All invocations of utility returned exit status zero.
1-125
A command line meeting the specified requirements could not be assembled, one or more of the invocations of utility returned a non-zero exit status, or some other error occurred.
126
The utility specified by utility was found but could not be invoked.
127
The utility specified by utility could not be found.

CONSEQUENCES OF ERRORS

If a command line meeting the specified requirements cannot be assembled, the utility cannot be invoked, an invocation of the utility is terminated by a signal, or an invocation of the utility exits with exit status 255, the xargs utility shall write a diagnostic message and exit without processing any remaining input.

The following sections are informative.

APPLICATION USAGE

The 255 exit status allows a utility being used by xargs to tell xargs to terminate if it knows no further invocations using the current data stream will succeed. Thus, utility should explicitly exit with an appropriate value to avoid accidentally returning with 255.

Note that input is parsed as lines; <blank>s separate arguments. If xargs is used to bundle output of commands like find dir -print or ls into commands to be executed, unexpected results are likely if any filenames contain any <blank>s or <newline>s. This can be fixed by using find to call a script that converts each file found into a quoted string that is then piped to xargs. Note that the quoting rules used by xargs are not the same as in the shell. They were not made consistent here because existing applications depend on the current rules and the shell syntax is not fully compatible with it. An easy rule that can be used to transform any string into a quoted form that xargs interprets correctly is to precede each character in the string with a backslash.

On implementations with a large value for {ARG_MAX}, xargs may produce command lines longer than {LINE_MAX}. For invocation of utilities, this is not a problem. If xargs is being used to create a text file, users should explicitly set the maximum command line length with the -s option.

The command, env, nice, nohup, time, and xargs utilities have been specified to use exit code 127 if an error occurs so that applications can distinguish "failure to find a utility" from "invoked utility exited with an error indication". The value 127 was chosen because it is not commonly used for other meanings; most utilities use small values for "normal error conditions'' and the values above 128 can be confused with termination due to receipt of a signal. The value 126 was chosen in a similar manner to indicate that the utility could be found, but not invoked. Some scripts produce meaningful error messages differentiating the 126 and 127 cases. The distinction between exit codes 126 and 127 is based on KornShell practice that uses 127 when all attempts to exec the utility fail with [ENOENT], and uses 126 when any attempt to exec the utility fails for any other reason.

EXAMPLES

1.
The following command combines the output of the parenthesised commands onto one line, which is then written to the end-of-file log:

(logname; date; printf "%s\n" "$0 $*") | xargs >>log

2.
The following command invokes diff with successive pairs of arguments originally typed as command line arguments (assuming there are no embedded <blank>s in the elements of the original argument list):

printf "%s\n" "$*" | xargs -n 2 -x diff

3.
In the following commands, the user is asked which files in the current directory are to be archived. The files are archived into arch; a, one at a time, or b, many at a time.

a. ls | xargs -p -L 1 ar -r arch

b. ls | xargs -p -L 1 | xargs ar -r arch

4.
The following executes with successive pairs of arguments originally typed as command line arguments:

echo $* | xargs -n 2 diff

5.
On XSI-conformant systems, the following moves all files from directory $1 to directory $2, and echoes each move command just before doing it:

ls $1 | xargs -I {} -t mv $1/{} $2/{}

RATIONALE

The xargs utility was usually found only in System V-based systems; BSD systems included an apply utility that provided functionality similar to xargs -n number. The SVID lists xargs as a software development extension. This volume of IEEE Std 1003.1-2001 does not share the view that it is used only for development, and therefore it is not optional.

The classic application of the xargs utility is in conjunction with the find utility to reduce the number of processes launched by a simplistic use of the find -exec combination. The xargs utility is also used to enforce an upper limit on memory required to launch a process. With this basis in mind, this volume of IEEE Std 1003.1-2001 selected only the minimal features required.

Although the 255 exit status is mostly an accident of historical implementations, it allows a utility being used by xargs to tell xargs to terminate if it knows no further invocations using the current data stream shall succeed. Any non-zero exit status from a utility falls into the 1-125 range when xargs exits. There is no statement of how the various non-zero utility exit status codes are accumulated by xargs. The value could be the addition of all codes, their highest value, the last one received, or a single value such as 1. Since no algorithm is arguably better than the others, and since many of the standard utilities say little more (portably) than "pass/fail", no new algorithm was invented.

Several other xargs options were withdrawn because simple alternatives already exist within this volume of IEEE Std 1003.1-2001. For example, the -i replstr option can be just as efficiently performed using a shell for loop. Since xargs calls an exec function with each input line, the -i option does not usually exploit the grouping capabilities of xargs.

The requirement that xargs never produces command lines such that invocation of utility is within 2048 bytes of hitting the POSIX exec {ARG_MAX} limitations is intended to guarantee that the invoked utility has room to modify its environment variables and command line arguments and still be able to invoke another utility. Note that the minimum {ARG_MAX} allowed by the System Interfaces volume of IEEE Std 1003.1-2001 is 4096 bytes and the minimum value allowed by this volume of IEEE Std 1003.1-2001 is 2048 bytes; therefore, the 2048 bytes difference seems reasonable. Note, however, that xargs may never be able to invoke a utility if the environment passed in to xargs comes close to using {ARG_MAX} bytes.

The version of xargs required by this volume of IEEE Std 1003.1-2001 is required to wait for the completion of the invoked command before invoking another command. This was done because historical scripts using xargs assumed sequential execution. Implementations wanting to provide parallel operation of the invoked utilities are encouraged to add an option enabling parallel invocation, but should still wait for termination of all of the children before xargs terminates normally.

The -e option was omitted from the ISO POSIX-2:1993 standard in the belief that the eofstr option-argument was recognized only when it was on a line by itself and before quote and escape processing were performed, and that the logical end-of-file processing was only enabled if a -e option was specified. In that case, a simple sed script could be used to duplicate the -e functionality. Further investigation revealed that:

*
The logical end-of-file string was checked for after quote and escape processing, making a sed script that provided equivalent functionality much more difficult to write.

*
The default was to perform logical end-of-file processing with an underscore as the logical end-of-file string.

To correct this misunderstanding, the -E eofstr option was adopted from the X/Open Portability Guide. Users should note that the description of the -E option matches historical documentation of the -e option (which was not adopted because it did not support the Utility Syntax Guidelines), by saying that if eofstr is the null string, logical end-of-file processing is disabled. Historical implementations of xargs actually did not disable logical end-of-file processing; they treated a null argument found in the input as a logical end-of-file string. (A null string argument could be generated using single or double quotes ( '' or "" ). Since this behavior was not documented historically, it is considered to be a bug.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , echo , find , the System Interfaces volume of IEEE Std 1003.1-2001, exec

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


m4(1p)

M4

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

m4 - macro processor (DEVELOPMENT)

SYNOPSIS

m4 [-s][-D name[=val]]...[-U name]... file...

DESCRIPTION

The m4 utility is a macro processor that shall read one or more text files, process them according to their included macro statements, and write the results to standard output.

OPTIONS

The m4 utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the order of the -D and -U options shall be significant.

The following options shall be supported:

-s
Enable line synchronization output for the c99 preprocessor phase (that is, #line directives).
-D name[=val]

Define name to val or to null if = val is omitted.

-U name
Undefine name.

OPERANDS

The following operand shall be supported:

file
A pathname of a text file to be processed. If no file is given, or if it is '-' , the standard input shall be read.

STDIN

The standard input shall be a text file that is used if no file operand is given, or if it is '-' .

INPUT FILES

The input file named by the file operand shall be a text file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of m4:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be the same as the input files, after being processed for macro expansion.

STDERR

The standard error shall be used to display strings with the errprint macro, macro tracing enabled by the traceon macro, the defined text for macros written by the dumpdef macro, or for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The m4 utility shall compare each token from the input against the set of built-in and user-defined macros. If the token matches the name of a macro, then the token shall be replaced by the macro's defining text, if any, and rescanned for matching macro names. Once no portion of the token matches the name of a macro, it shall be written to standard output. Macros may have arguments, in which case the arguments shall be substituted into the defining text before it is rescanned.

Macro calls have the form:

name(arg1, arg2, ..., argn)

Macro names shall consist of letters, digits, and underscores, where the first character is not a digit. Tokens not of this form shall not be treated as macros.

The application shall ensure that the left parenthesis immediately follows the name of the macro. If a token matching the name of a macro is not followed by a left parenthesis, it is handled as a use of that macro without arguments.

If a macro name is followed by a left parenthesis, its arguments are the comma-separated tokens between the left parenthesis and the matching right parenthesis. Unquoted <blank>s and <newline>s preceding each argument shall be ignored. All other characters, including trailing <blank>s and <newline>s, are retained. Commas enclosed between left and right parenthesis characters do not delimit arguments.

Arguments are positionally defined and referenced. The string "$1" in the defining text shall be replaced by the first argument. Systems shall support at least nine arguments; only the first nine can be referenced, using the strings "$1" to "$9" , inclusive. The string "$0" is replaced with the name of the macro. The string "$#" is replaced by the number of arguments as a string. The string "$*" is replaced by a list of all of the arguments, separated by commas. The string "$@" is replaced by a list of all of the arguments separated by commas, and each argument is quoted using the current left and right quoting strings.

If fewer arguments are supplied than are in the macro definition, the omitted arguments are taken to be null. It is not an error if more arguments are supplied than are in the macro definition.

No special meaning is given to any characters enclosed between matching left and right quoting strings, but the quoting strings are themselves discarded. By default, the left quoting string consists of a grave accent ( '`' ) and the right quoting string consists of an acute accent ( '" ); see also the changequote macro.

Comments are written but not scanned for matching macro names; by default, the begin-comment string consists of the number sign character and the end-comment string consists of a <newline>. See also the changecom and dnl macros.

The m4 utility shall make available the following built-in macros. They can be redefined, but once this is done the original meaning is lost. Their values shall be null unless otherwise stated. In the descriptions below, the term defining text refers to the value of the macro: the second argument to the define macro, among other things. Except for the first argument to the eval macro, all numeric arguments to built-in macros shall be interpreted as decimal values. The string values produced as the defining text of the decr, divnum, incr, index, len, and sysval built-in macros shall be in the form of a decimal-constant as defined in the C language.

changecom
The changecom macro shall set the begin-comment and end-comment strings. With no arguments, the comment mechanism shall be disabled. With a single argument, that argument shall become the begin-comment string and the <newline> shall become the end-comment string. With two arguments, the first argument shall become the begin-comment string and the second argument shall become the end-comment string. Systems shall support comment strings of at least five characters.
changequote
The changequote macro shall set the begin-quote and end-quote strings. With no arguments, the quote strings shall be set to the default values (that is, `'). With a single argument, that argument shall become the begin-quote string and the <newline> shall become the end-quote string. With two arguments, the first argument shall become the begin-quote string and the second argument shall become the end-quote string. Systems shall support quote strings of at least five characters.
decr
The defining text of the decr macro shall be its first argument decremented by 1. It shall be an error to specify an argument containing any non-numeric characters.
define
The second argument shall become the defining text of the macro whose name is the first argument.
defn
The defining text of the defn macro shall be the quoted definition (using the current quoting strings) of its arguments.
divert
The m4 utility maintains nine temporary buffers, numbered 1 to 9, inclusive. When the last of the input has been processed, any output that has been placed in these buffers shall be written to standard output in buffer-numerical order. The divert macro shall divert future output to the buffer specified by its argument. Specifying no argument or an argument of 0 shall resume the normal output process. Output diverted to a stream other than 0 to 9 shall be discarded. It shall be an error to specify an argument containing any non-numeric characters.
divnum
The defining text of the divnum macro shall be the number of the current output stream as a string.
dnl
The dnl macro shall cause m4 to discard all input characters up to and including the next <newline>.
dumpdef
The dumpdef macro shall write the defined text to standard error for each of the macros specified as arguments, or, if no arguments are specified, for all macros.
errprint
The errprint macro shall write its arguments to standard error.
eval
The eval macro shall evaluate its first argument as an arithmetic expression, using 32-bit signed integer arithmetic. All of the C-language operators shall be supported, except for:

[]
->
++
--
(type)
unary *
sizeof,
.
?:
unary &

and all assignment operators. It shall be an error to specify any of these operators. Precedence and associativity shall be as in the ISO C standard. Systems shall support octal and hexadecimal numbers as in the ISO C standard. The second argument, if specified, shall set the radix for the result; the default is 10. The third argument, if specified, sets the minimum number of digits in the result. It shall be an error to specify the second or third argument containing any non-numeric characters.

ifdef
If the first argument to the ifdef macro is defined, the defining text shall be the second argument. Otherwise, the defining text shall be the third argument, if specified, or the null string, if not.
ifelse
The ifelse macro takes three or more arguments. If the first two arguments compare as equal strings (after macro expansion of both arguments), the defining text shall be the third argument. If the first two arguments do not compare as equal strings and there are three arguments, the defining text shall be null. If the first two arguments do not compare as equal strings and there are four or five arguments, the defining text shall be the fourth argument. If the first two arguments do not compare as equal strings and there are six or more arguments, the first three arguments shall be discarded and processing shall restart with the remaining arguments.
include
The defining text for the include macro shall be the contents of the file named by the first argument. It shall be an error if the file cannot be read.
incr
The defining text of the incr macro shall be its first argument incremented by 1. It shall be an error to specify an argument containing any non-numeric characters.
index
The defining text of the index macro shall be the first character position (as a string) in the first argument where a string matching the second argument begins (zero origin), or -1 if the second argument does not occur.
len
The defining text of the len macro shall be the length (as a string) of the first argument.
m4exit
Exit from the m4 utility. If the first argument is specified, it is the exit code. The default is zero. It shall be an error to specify an argument containing any non-numeric characters.
m4wrap
The first argument shall be processed when EOF is reached. If the m4wrap macro is used multiple times, the arguments specified shall be processed in the order in which the m4wrap macros were processed.
maketemp
The defining text shall be the first argument, with any trailing 'X' characters replaced with the current process ID as a string.
popdef
The popdef macro shall delete the current definition of its arguments, replacing that definition with the previous one. If there is no previous definition, the macro is undefined.
pushdef
The pushdef macro shall be equivalent to the define macro with the exception that it shall preserve any current definition for future retrieval using the popdef macro.
shift
The defining text for the shift macro shall be all of its arguments except for the first one.
sinclude
The sinclude macro shall be equivalent to the include macro, except that it shall not be an error if the file is inaccessible.
substr
The defining text for the substr macro shall be the substring of the first argument beginning at the zero-offset character position specified by the second argument. The third argument, if specified, shall be the number of characters to select; if not specified, the characters from the starting point to the end of the first argument shall become the defining text. It shall not be an error to specify a starting point beyond the end of the first argument and the defining text shall be null. It shall be an error to specify an argument containing any non-numeric characters.
syscmd
The syscmd macro shall interpret its first argument as a shell command line. The defining text shall be the string result of that command. No output redirection shall be performed by the m4 utility. The exit status value from the command can be retrieved using the sysval macro.
sysval
The defining text of the sysval macro shall be the exit value of the utility last invoked by the syscmd macro (as a string).
traceon
The traceon macro shall enable tracing for the macros specified as arguments, or, if no arguments are specified, for all macros. The trace output shall be written to standard error in an unspecified format.
traceoff
The traceoff macro shall disable tracing for the macros specified as arguments, or, if no arguments are specified, for all macros.
translit
The defining text of the translit macro shall be the first argument with every character that occurs in the second argument replaced with the corresponding character from the third argument.
undefine
The undefine macro shall delete all definitions (including those preserved using the pushdef macro) of the macros named by its arguments.
undivert
The undivert macro shall cause immediate output of any text in temporary buffers named as arguments, or all temporary buffers if no arguments are specified. Buffers can be undiverted into other temporary buffers. Undiverting shall discard the contents of the temporary buffer. It shall be an error to specify an argument containing any non-numeric characters.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred

If the m4exit macro is used, the exit value can be specified by the input file.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The defn macro is useful for renaming macros, especially built-ins.

EXAMPLES

If the file m4src contains the lines:

The value of `VER' is "VER".
ifdef(`VER', "VER" is defined to be VER., VER is not defined.)
ifelse(VER, 1, "VER" is `VER'.)
ifelse(VER, 2, "VER" is `VER'., "VER" is not 2.)
end

then the command

m4 m4src

or the command:

m4 -U VER m4src

produces the output:

The value of VER is "VER".
VER is not defined.

VER is not 2.
end

The command:

m4 -D VER m4src

produces the output:

The value of VER is "".
VER is defined to be .

VER is not 2.
end

The command:

m4 -D VER=1 m4src

produces the output:

The value of VER is "1".
VER is defined to be 1.
VER is 1.
VER is not 2.
end

The command:

m4 -D VER=2 m4src

produces the output:
The value of VER is "2".
VER is defined to be 2.

VER is 2.
end

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

c99

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


id(1p)

ID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

id - return user identity

SYNOPSIS

id [user]

id -G[-n] [user]

id -g[-nr] [user]

id -u[-nr] [user]

DESCRIPTION

If no user operand is provided, the id utility shall write the user and group IDs and the corresponding user and group names of the invoking process to standard output. If the effective and real IDs do not match, both shall be written. If multiple groups are supported by the underlying system (see the description of {NGROUPS_MAX} in the System Interfaces volume of IEEE Std 1003.1-2001), the supplementary group affiliations of the invoking process shall also be written.

If a user operand is provided and the process has the appropriate privileges, the user and group IDs of the selected user shall be written. In this case, effective IDs shall be assumed to be identical to real IDs. If the selected user has more than one allowable group membership listed in the group database, these shall be written in the same manner as the supplementary groups described in the preceding paragraph.

OPTIONS

The id utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-G
Output all different group IDs (effective, real, and supplementary) only, using the format "%u\n" . If there is more than one distinct group affiliation, output each such affiliation, using the format " %u" , before the <newline> is output.
-g
Output only the effective group ID, using the format "%u\n" .
-n
Output the name in the format "%s" instead of the numeric ID using the format "%u" .
-r
Output the real ID instead of the effective ID.
-u
Output only the effective user ID, using the format "%u\n" .

OPERANDS

The following operand shall be supported:

user
The login name for which information is to be written.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of id:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The following formats shall be used when the LC_MESSAGES locale category specifies the POSIX locale. In other locales, the strings uid, gid, euid, egid, and groups may be replaced with more appropriate strings corresponding to the locale.

"uid=%u(%s) gid=%u(%s)\n", <real user ID>, <user-name>,
    <real group ID>, <group-name>

If the effective and real user IDs do not match, the following shall be inserted immediately before the '\n' character in the previous format:

" euid=%u(%s)"

with the following arguments added at the end of the argument list:

<effective user ID>, <effective user-name>

If the effective and real group IDs do not match, the following shall be inserted directly before the '\n' character in the format string (and after any addition resulting from the effective and real user IDs not matching):

" egid=%u(%s)"

with the following arguments added at the end of the argument list:

<effective group-ID>, <effective group name>

If the process has supplementary group affiliations or the selected user is allowed to belong to multiple groups, the first shall be added directly before the <newline> in the format string:

" groups=%u(%s)"

with the following arguments added at the end of the argument list:

<supplementary group ID>, <supplementary group name>

and the necessary number of the following added after that for any remaining supplementary group IDs:

",%u(%s)"

and the necessary number of the following arguments added at the end of the argument list:

<supplementary group ID>, <supplementary group name>

If any of the user ID, group ID, effective user ID, effective group ID, or supplementary/multiple group IDs cannot be mapped by the system into printable user or group names, the corresponding "(%s)" and name argument shall be omitted from the corresponding format string.

When any of the options are specified, the output format shall be as described in the OPTIONS section.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Output produced by the -G option and by the default case could potentially produce very long lines on systems that support large numbers of supplementary groups. (On systems with user and group IDs that are 32-bit integers and with group names with a maximum of 8 bytes per name, 93 supplementary groups plus distinct effective and real group and user IDs could theoretically overflow the 2048-byte {LINE_MAX} text file line limit on the default output case. It would take about 186 supplementary groups to overflow the 2048-byte barrier using id -G). This is not expected to be a problem in practice, but in cases where it is a concern, applications should consider using fold -s before postprocessing the output of id.

EXAMPLES

None.

RATIONALE

The functionality provided by the 4 BSD groups utility can be simulated using:

id -Gn [ user ]

The 4 BSD command groups was considered, but it was not included because it did not provide the functionality of the id utility of the SVID. Also, it was thought that it would be easier to modify id to provide the additional functionality necessary to systems with multiple groups than to invent another command.

The options -u, -g, -n, and -r were added to ease the use of id with shell commands substitution. Without these options it is necessary to use some preprocessor such as sed to select the desired piece of information. Since output such as that produced by:

id -u -n

is frequently wanted, it seemed desirable to add the options.

FUTURE DIRECTIONS

None.

SEE ALSO

fold , logname , who , the System Interfaces volume of IEEE Std 1003.1-2001, getgid(), getgroups(), getuid()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uustat(1p)

UUSTAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uustat - uucp status inquiry and job control

SYNOPSIS

uustat [ -q| -k jobid| -r jobid]

uustat [-s system][-u user]

DESCRIPTION

The uustat utility shall display the status of, or cancel, previously specified uucp requests, or provide general status on uucp connections to other systems.

When no options are given, uustat shall write to standard output the status of all uucp requests issued by the current user.

Typical implementations of this utility require a communications line configured to use the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, but other communications means may be used. On systems where there are no available communications means (either temporarily or permanently), this utility shall write an error message describing the problem and exit with a non-zero exit status.

OPTIONS

The uustat utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-q
Write the jobs queued for each machine.
-k jobid
Kill the uucp request whose job identification is jobid. The application shall ensure that the killed uucp request belongs to the person invoking uustat unless that user has appropriate privileges.
-r jobid
Rejuvenate jobid. The files associated with jobid are touched so that their modification time is set to the current time. This prevents the cleanup program from deleting the job until the jobs modification time reaches the limit imposed by the program.
-s system
Write the status of all uucp requests for remote system system.
-u user
Write the status of all uucp requests issued by user.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uustat:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error, and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall consist of information about each job selected, in an unspecified format. The information shall include at least the job ID, the user ID or name, and the remote system name.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

uucp

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ln(1p)

LN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ln - link files

SYNOPSIS

ln [-fs] source_file target_file

ln [-fs] source_file ... target_dir

DESCRIPTION

In the first synopsis form, the ln utility shall create a new directory entry (link) at the destination path specified by the target_file operand. If the -s option is specified, a symbolic link shall be created for the file specified by the source_file operand. This first synopsis form shall be assumed when the final operand does not name an existing directory; if more than two operands are specified and the final is not an existing directory, an error shall result.

In the second synopsis form, the ln utility shall create a new directory entry (link), or if the -s option is specified a symbolic link, for each file specified by a source_file operand, at a destination path in the existing directory named by target_dir.

If the last operand specifies an existing file of a type not specified by the System Interfaces volume of IEEE Std 1003.1-2001, the behavior is implementation-defined.

The corresponding destination path for each source_file shall be the concatenation of the target directory pathname, a slash character, and the last pathname component of the source_file. The second synopsis form shall be assumed when the final operand names an existing directory.

For each source_file:

1.
If the destination path exists:
a.
If the -f option is not specified, ln shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.

b.
Actions shall be performed equivalent to the unlink() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called using destination as the path argument. If this fails for any reason, ln shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.

2.
If the -s option is specified, ln shall create a symbolic link named by the destination path and containing as its pathname source_file. The ln utility shall do nothing more with source_file and shall go on to any remaining files.

3.
If source_file is a symbolic link, actions shall be performed equivalent to the link() function using the object that source_file references as the path1 argument and the destination path as the path2 argument. The ln utility shall do nothing more with source_file and shall go on to any remaining files.

4.
Actions shall be performed equivalent to the link() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 using source_file as the path1 argument, and the destination path as the path2 argument.

OPTIONS

The ln utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-f
Force existing destination pathnames to be removed to allow the link.
-s
Create symbolic links instead of hard links.

OPERANDS

The following operands shall be supported:

source_file
A pathname of a file to be linked. If the -s option is specified, no restrictions on the type of file or on its existence shall be made. If the -s option is not specified, whether a directory can be linked is implementation-defined.
target_file
The pathname of the new directory entry to be created.
target_dir
A pathname of an existing directory in which the new directory entries are created.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ln:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All the specified files were linked successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

Some historic versions of ln (including the one specified by the SVID) unlink the destination file, if it exists, by default. If the mode does not permit writing, these versions prompt for confirmation before attempting the unlink. In these versions the -f option causes ln not to attempt to prompt for confirmation.

This allows ln to succeed in creating links when the target file already exists, even if the file itself is not writable (although the directory must be). Early proposals specified this functionality.

This volume of IEEE Std 1003.1-2001 does not allow the ln utility to unlink existing destination paths by default for the following reasons:

*
The ln utility has historically been used to provide locking for shell applications, a usage that is incompatible with ln unlinking the destination path by default. There was no corresponding technical advantage to adding this functionality.

*
This functionality gave ln the ability to destroy the link structure of files, which changes the historical behavior of ln.

*
This functionality is easily replicated with a combination of rm and ln.

*
It is not historical practice in many systems; BSD and BSD-derived systems do not support this behavior. Unfortunately, whichever behavior is selected can cause scripts written expecting the other behavior to fail.

*
It is preferable that ln perform in the same manner as the link() function, which does not permit the target to exist already.

This volume of IEEE Std 1003.1-2001 retains the -f option to provide support for shell scripts depending on the SVID semantics. It seems likely that shell scripts would not be written to handle prompting by ln and would therefore have specified the -f option.

The -f option is an undocumented feature of many historical versions of the ln utility, allowing linking to directories. These versions require modification.

Early proposals of this volume of IEEE Std 1003.1-2001 also required a -i option, which behaved like the -i options in cp and mv, prompting for confirmation before unlinking existing files. This was not historical practice for the ln utility and has been omitted.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , find , pax , rm , the System Interfaces volume of IEEE Std 1003.1-2001, link(), unlink()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lp(1p)

LP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lp - send files to a printer

SYNOPSIS

lp [-c][-d dest][-n copies][-msw][-o option]... [-t title][file...]

DESCRIPTION

The lp utility shall copy the input files to an output destination in an unspecified manner. The default output destination should be to a hardcopy device, such as a printer or microfilm recorder, that produces non-volatile, human-readable documents. If such a device is not available to the application, or if the system provides no such device, the lp utility shall exit with a non-zero exit status.

The actual writing to the output device may occur some time after the lp utility successfully exits. During the portion of the writing that corresponds to each input file, the implementation shall guarantee exclusive access to the device.

The lp utility shall associate a unique request ID with each request.

Normally, a banner page is produced to separate and identify each print job. This page may be suppressed by implementation-defined conditions, such as an operator command or one of the -o option values.

OPTIONS

The lp utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Exit only after further access to any of the input files is no longer required. The application can then safely delete or modify the files without affecting the output operation. Normally, files are not copied, but are linked whenever possible. If the -c option is not given, then the user should be careful not to remove any of the files before the request has been printed in its entirety. It should also be noted that in the absence of the -c option, any changes made to the named files after the request is made but before it is printed may be reflected in the printed output. On some implementations, -c may be on by default.
-d dest
Specify a string that names the destination ( dest). If dest is a printer, the request shall be printed only on that specific printer. If dest is a class of printers, the request shall be printed on the first available printer that is a member of the class. Under certain conditions (printer unavailability, file space limitation, and so on), requests for specific destinations need not be accepted. Destination names vary between systems.

If -d is not specified, and neither the LPDEST nor PRINTER environment variable is set, an unspecified destination is used. The -d dest option shall take precedence over LPDEST , which in turn shall take precedence over PRINTER . Results are undefined when dest contains a value that is not a valid destination name.

-m
Send mail (see mailx ) after the files have been printed. By default, no mail is sent upon normal completion of the print request.
-n copies
Write copies number of copies of the files, where copies is a positive decimal integer. The methods for producing multiple copies and for arranging the multiple copies when multiple file operands are used are unspecified, except that each file shall be output as an integral whole, not interleaved with portions of other files.
-o option
Specify printer-dependent or class-dependent options. Several such options may be collected by specifying the -o option more than once.
-s
Suppress messages from lp.
-t title
Write title on the banner page of the output.
-w
Write a message on the user's terminal after the files have been printed. If the user is not logged in, then mail shall be sent instead.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be output. If no file operands are specified, or if a file operand is '-' , the standard input shall be used. If a file operand is used, but the -c option is not specified, the process performing the writing to the output device may have user and group permissions that differ from that of the process invoking lp.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' . See the INPUT FILES section.

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of lp:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
LC_TIME
Determine the format and contents of date and time strings displayed in the lp banner page, if any.
LPDEST
Determine the destination. If the LPDEST environment variable is not set, the PRINTER environment variable shall be used. The -d dest option takes precedence over LPDEST . Results are undefined when -d is not specified and LPDEST contains a value that is not a valid destination name.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PRINTER
Determine the output device or destination. If the LPDEST and PRINTER environment variables are not set, an unspecified output device is used. The -d dest option and the LPDEST environment variable shall take precedence over PRINTER . Results are undefined when -d is not specified, LPDEST is unset, and PRINTER contains a value that is not a valid device or destination name.
TZ
Determine the timezone used to calculate date and time strings displayed in the lp banner page, if any. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The lp utility shall write a request ID to the standard output, unless -s is specified. The format of the message is unspecified. The request ID can be used on systems supporting the historical cancel and lpstat utilities.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were processed successfully.
>0
No output device was available, or an error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The pr and fold utilities can be used to achieve reasonable formatting for the implementation's default page size.

A conforming application can use one of the file operands only with the -c option or if the file is publicly readable and guaranteed to be available at the time of printing. This is because IEEE Std 1003.1-2001 gives the implementation the freedom to queue up the request for printing at some later time by a different process that might not be able to access the file.

EXAMPLES

1.
To print file file:

lp -c file

2.
To print multiple files with headers:

pr file1 file2 | lp

RATIONALE

The lp utility was designed to be a basic version of a utility that is already available in many historical implementations. The standard developers considered that it should be implementable simply as:

cat "$@" > /dev/lp

after appropriate processing of options, if that is how the implementation chose to do it and if exclusive access could be granted (so that two users did not write to the device simultaneously). Although in the future the standard developers may add other options to this utility, it should always be able to execute with no options or operands and send the standard input to an unspecified output device.

This volume of IEEE Std 1003.1-2001 makes no representations concerning the format of the printed output, except that it must be "human-readable" and "non-volatile". Thus, writing by default to a disk or tape drive or a display terminal would not qualify. (Such destinations are not prohibited when -d dest, LPDEST , or PRINTER are used, however.)

This volume of IEEE Std 1003.1-2001 is worded such that a "print job" consisting of multiple input files, possibly in multiple copies, is guaranteed to print so that any one file is not intermixed with another, but there is no statement that all the files or copies have to print out together.

The -c option may imply a spooling operation, but this is not required. The utility can be implemented to wait until the printer is ready and then wait until it is finished. Because of that, there is no attempt to define a queuing mechanism (priorities, classes of output, and so on).

On some historical systems, the request ID reported on the STDOUT can be used to later cancel or find the status of a request using utilities not defined in this volume of IEEE Std 1003.1-2001.

Although the historical System V lp and BSD lpr utilities have provided similar functionality, they used different names for the environment variable specifying the destination printer. Since the name of the utility here is lp, LPDEST (used by the System V lp utility) was given precedence over PRINTER (used by the BSD lpr utility). Since environments of users frequently contain one or the other environment variable, the lp utility is required to recognize both. If this was not done, many applications would send output to unexpected output devices when users moved from system to system.

Some have commented that lp has far too little functionality to make it worthwhile. Requests have proposed additional options or operands or both that added functionality. The requests included:

*
Wording requiring the output to be "hardcopy"

*
A requirement for multiple printers

*
Options for supporting various page-description languages

Given that a compliant system is not required to even have a printer, placing further restrictions upon the behavior of the printer is not useful. Since hardcopy format is so application-dependent, it is difficult, if not impossible, to select a reasonable subset of functionality that should be required on all compliant systems.

The term unspecified is used in this section in lieu of implementation-defined as most known implementations would not be able to make definitive statements in their conformance documents; the existence and usage of printers is very dependent on how the system administrator configures each individual system.

Since the default destination, device type, queuing mechanisms, and acceptable forms of input are all unspecified, usage guidelines for what a conforming application can do are as follows:

*
Use the command in a pipeline, or with -c, so that there are no permission problems and the files can be safely deleted or modified.

*
Limit output to text files of reasonable line lengths and printable characters and include no device-specific formatting information, such as a page description language. The meaning of "reasonable" in this context can only be answered as a quality-of-implementation issue, but it should be apparent from historical usage patterns in the industry and the locale. The pr and fold utilities can be used to achieve reasonable formatting for the default page size of the implementation.

Alternatively, the application can arrange its installation in such a way that it requires the system administrator or operator to provide the appropriate information on lp options and environment variable values.

At a minimum, having this utility in this volume of IEEE Std 1003.1-2001 tells the industry that conforming applications require a means to print output and provides at least a command name and LPDEST routing mechanism that can be used for discussions between vendors, application writers, and users. The use of "should" in the DESCRIPTION of lp clearly shows the intent of the standard developers, even if they cannot mandate that all systems (such as laptops) have printers.

This volume of IEEE Std 1003.1-2001 does not specify what the ownership of the process performing the writing to the output device may be. If -c is not used, it is unspecified whether the process performing the writing to the output device has permission to read file if there are any restrictions in place on who may read file until after it is printed. Also, if -c is not used, the results of deleting file before it is printed are unspecified.

FUTURE DIRECTIONS

None.

SEE ALSO

mailx

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ls(1p)

LS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ls - list directory contents

SYNOPSIS

ls [-CFRacdilqrtu1][-H | -L ][-fgmnopsx][file...]

DESCRIPTION

For each operand that names a file of a type other than directory or symbolic link to a directory, ls shall write the name of the file as well as any requested, associated information. For each operand that names a file of type directory, ls shall write the names of files contained within the directory as well as any requested, associated information. If one of the -d, -F, or -l options are specified, and one of the -H or -L options are not specified, for each operand that names a file of type symbolic link to a directory, ls shall write the name of the file as well as any requested, associated information. If none of the -d, -F, or -l options are specified, or the -H or -L options are specified, for each operand that names a file of type symbolic link to a directory, ls shall write the names of files contained within the directory as well as any requested, associated information.

If no operands are specified, ls shall write the contents of the current directory. If more than one operand is specified, ls shall write non-directory operands first; it shall sort directory and non-directory operands separately according to the collating sequence in the current locale.

The ls utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, ls shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate.

OPTIONS

The ls utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-C
Write multi-text-column output with entries sorted down the columns, according to the collating sequence. The number of text columns and the column separator characters are unspecified, but should be adapted to the nature of the output device.
-F
Do not follow symbolic links named as operands unless the -H or -L options are specified. Write a slash ( '/' ) immediately after each pathname that is a directory, an asterisk ( '*' ) after each that is executable, a vertical bar ( '|' ) after each that is a FIFO, and an at sign ( '@' ) after each that is a symbolic link. For other file types, other symbols may be written.
-H
If a symbolic link referencing a file of type directory is specified on the command line, ls shall evaluate the file information and file type to be those of the file referenced by the link, and not the link itself; however, ls shall write the name of the link itself and not the file referenced by the link.
-L
Evaluate the file information and file type for all symbolic links (whether named on the command line or encountered in a file hierarchy) to be those of the file referenced by the link, and not the link itself; however, ls shall write the name of the link itself and not the file referenced by the link. When -L is used with -l, write the contents of symbolic links in the long format (see the STDOUT section).
-R
Recursively list subdirectories encountered.
-a
Write out all directory entries, including those whose names begin with a period ( '.' ). Entries beginning with a period shall not be written out unless explicitly referenced, the -a option is supplied, or an implementation-defined condition shall cause them to be written.
-c
Use time of last modification of the file status information (see <sys/stat.h> in the System Interfaces volume of IEEE Std 1003.1-2001) instead of last modification of the file itself for sorting ( -t) or writing ( -l).
-d
Do not follow symbolic links named as operands unless the -H or -L options are specified. Do not treat directories differently than other types of files. The use of -d with -R produces unspecified results.
-f
Force each argument to be interpreted as a directory and list the name found in each slot. This option shall turn off -l, -t, -s, and -r, and shall turn on -a; the order is the order in which entries appear in the directory.
-g
The same as -l, except that the owner shall not be written.
-i
For each file, write the file's file serial number (see stat() in the System Interfaces volume of IEEE Std 1003.1-2001).
-l
(The letter ell.) Do not follow symbolic links named as operands unless the -H or -L options are specified. Write out in long format (see the STDOUT section). When -l (ell) is specified, -1 (one) shall be assumed.
-m
Stream output format; list files across the page, separated by commas.
-n
The same as -l, except that the owner's UID and GID numbers shall be written, rather than the associated character strings.
-o
The same as -l, except that the group shall not be written.
-p
Write a slash ( '/' ) after each filename if that file is a directory.
-q
Force each instance of non-printable filename characters and <tab>s to be written as the question-mark ( '?' ) character. Implementations may provide this option by default if the output is to a terminal device.
-r
Reverse the order of the sort to get reverse collating sequence or oldest first.
-s
Indicate the total number of file system blocks consumed by each file displayed. The block size is implementation-defined.
-t
Sort with the primary key being time modified (most recently modified first) and the secondary key being filename in the collating sequence.
-u
Use time of last access (see <sys/stat.h>) instead of last modification of the file for sorting ( -t) or writing ( -l).
-x
The same as -C, except that the multi-text-column output is produced with entries sorted across, rather than down, the columns.
-1
(The numeric digit one.) Force output to be one entry per line.

Specifying more than one of the options in the following mutually-exclusive pairs shall not be considered an error: -C and -l (ell), -m and -l (ell), -x and -l (ell), -C and -1 (one), -H and -L, -c and -u. The last option specified in each pair shall determine the output format.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be written. If the file specified is not found, a diagnostic message shall be output on standard error.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ls:

COLUMNS
Determine the user's preferred column position width for writing multiple text-column output. If this variable contains a string representing a decimal integer, the ls utility shall calculate how many pathname text columns to write (see -C) based on the width provided. If COLUMNS is not set or invalid, an implementation-defined number of column positions shall be assumed, based on the implementation's knowledge of the output device. The column width chosen to write the names of files in any given directory shall be constant. Filenames shall not be truncated to fit into the multiple text-column output.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for character collation information in determining the pathname collation sequence.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments) and which characters are defined as printable (character class print).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_TIME
Determine the format and contents for date and time strings written by ls.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone for date and time strings written by ls. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The default format shall be to list one entry per line to standard output; the exceptions are to terminals or when one of the -C, -m, or -x options is specified. If the output is to a terminal, the format is implementation-defined.

When -m is specified, the format used shall be:

"%s, %s, ...\n", <filename1>, <filename2>

where the largest number of filenames shall be written without exceeding the length of the line.

If the -i option is specified, the file's file serial number (see <sys/stat.h>) shall be written in the following format before any other output for the corresponding entry:

%u ", <file serial number>

If the -l option is specified without -L, the following information shall be written:

"%s %u %s %s %u %s %s\n", <file mode>, <number of links>,
    <owner name>, <group name>, <number of bytes in the file>,
    <date and time>, <pathname>

If the file is a symbolic link, this information shall be about the link itself and the <pathname> field shall be of the form:

"%s -> %s", <pathname of link>, <contents of link>

If both -l and -L are specified, the following information shall be written:

"%s %u %s %s %u %s %s\n", <file mode>, <number of links>,
    <owner name>, <group name>, <number of bytes in the file>,
    <date and time>, <pathname of link>

where all fields except <pathname of link> shall be for the file resolved from the symbolic link.

The -g, -n, and -o options use the same format as -l, but with omitted items and their associated <blank>s. See the OPTIONS section.

In both the preceding -l forms, if <owner name> or <group name> cannot be determined, or if -n is given, they shall be replaced with their associated numeric values using the format %u .

The <date and time> field shall contain the appropriate date and timestamp of when the file was last modified. In the POSIX locale, the field shall be the equivalent of the output of the following date command:

date "+%b %e %H:%M"

if the file has been modified in the last six months, or:

date "+%b %e %Y"

(where two <space>s are used between %e and %Y ) if the file has not been modified in the last six months or if the modification date is in the future, except that, in both cases, the final <newline> produced by date shall not be included and the output shall be as if the date command were executed at the time of the last modification date of the file rather than the current time. When the LC_TIME locale category is not set to the POSIX locale, a different format and order of presentation of this field may be used.

If the file is a character special or block special file, the size of the file may be replaced with implementation-defined information associated with the device in question.

If the pathname was specified as a file operand, it shall be written as specified.

The file mode written under the -l, -g, -n, and -o options shall consist of the following format:

"%c%s%s%s%c", <entry type>, <owner permissions>,
    <group permissions>, <other permissions>,
    <optional alternate access method flag>

The <optional alternate access method flag> shall be a single <space> if there is no alternate or additional access control method associated with the file; otherwise, a printable character shall be used.

The <entry type> character shall describe the type of file, as follows:

d
Directory.
b
Block special file.
c
Character special file.
l (ell)
Symbolic link.
p
FIFO.
-
Regular file.

Implementations may add other characters to this list to represent other implementation-defined file types.

The next three fields shall be three characters each:

<owner permissions>

Permissions for the file owner class (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.4, File Access Permissions).

<group permissions>

Permissions for the file group class.

<other permissions>

Permissions for the file other class.

Each field shall have three character positions:

1.
If 'r' , the file is readable; if '-' , the file is not readable.

2.
If 'w' , the file is writable; if '-' , the file is not writable.

3.
The first of the following that applies:
S
If in <owner permissions>, the file is not executable and set-user-ID mode is set. If in <group permissions>, the file is not executable and set-group-ID mode is set.
s
If in <owner permissions>, the file is executable and set-user-ID mode is set. If in <group permissions>, the file is executable and set-group-ID mode is set.
T
If in <other permissions> and the file is a directory, search permission is not granted to others, and the restricted deletion flag is set.
t
If in <other permissions> and the file is a directory, search permission is granted to others, and the restricted deletion flag is set.
x
The file is executable or the directory is searchable.
-
None of the attributes of 'S' , 's' , 'T' , 't' , or 'x' applies.

Implementations may add other characters to this list for the third character position. Such additions shall, however, be written in lowercase if the file is executable or searchable, and in uppercase if it is not.

If any of the -l, -g, -n, -o, or -s options is specified, each list of files within the directory shall be preceded by a status line indicating the number of file system blocks occupied by files in the directory in 512-byte units, rounded up to the next integral number of units, if necessary. In the POSIX locale, the format shall be:

"total %u\n", <number of units in the directory>

If more than one directory, or a combination of non-directory files and directories are written, either as a result of specifying multiple operands, or the -R option, each list of files within a directory shall be preceded by:

"\n%s:\n", <directory name>

If this string is the first thing to be written, the first <newline> shall not be written. This output shall precede the number of units in the directory.

If the -s option is given, each file shall be written with the number of blocks used by the file. Along with -C, -1, -m, or -x, the number and a <space> shall precede the filename; with -g, -l, -n, or -o, they shall precede each line describing a file.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Many implementations use the equal sign ( '=' ) to denote sockets bound to the file system for the -F option. Similarly, many historical implementations use the 's' character to denote sockets as the entry type characters for the -l option.

It is difficult for an application to use every part of the file modes field of ls -l in a portable manner. Certain file types and executable bits are not guaranteed to be exactly as shown, as implementations may have extensions. Applications can use this field to pass directly to a user printout or prompt, but actions based on its contents should generally be deferred, instead, to the test utility.

The output of ls (with the -l and related options) contains information that logically could be used by utilities such as chmod and touch to restore files to a known state. However, this information is presented in a format that cannot be used directly by those utilities or be easily translated into a format that can be used. A character has been added to the end of the permissions string so that applications at least have an indication that they may be working in an area they do not understand instead of assuming that they can translate the permissions string into something that can be used. Future issues or related documents may define one or more specific characters to be used based on different standard additional or alternative access control mechanisms.

As with many of the utilities that deal with filenames, the output of ls for multiple files or in one of the long listing formats must be used carefully on systems where filenames can contain embedded white space. Systems and system administrators should institute policies and user training to limit the use of such filenames.

The number of disk blocks occupied by the file that it reports varies depending on underlying file system type, block size units reported, and the method of calculating the number of blocks. On some file system types, the number is the actual number of blocks occupied by the file (counting indirect blocks and ignoring holes in the file); on others it is calculated based on the file size (usually making an allowance for indirect blocks, but ignoring holes).

EXAMPLES

An example of a small directory tree being fully listed with ls -laRF a in the POSIX locale:

total 11
drwxr-xr-x   3 hlj      prog          64 Jul  4 12:07 ./
drwxrwxrwx   4 hlj      prog        3264 Jul  4 12:09 ../
drwxr-xr-x   2 hlj      prog          48 Jul  4 12:07 b/
-rwxr--r--   1 hlj      prog         572 Jul  4 12:07 foo*

a/b:
total 4
drwxr-xr-x   2 hlj      prog          48 Jul  4 12:07 ./
drwxr-xr-x   3 hlj      prog          64 Jul  4 12:07 ../
-rw-r--r--   1 hlj      prog         700 Jul  4 12:07 bar

RATIONALE

Some historical implementations of the ls utility show all entries in a directory except dot and dot-dot when a superuser invokes ls without specifying the -a option. When "normal" users invoke ls without specifying -a, they should not see information about any files with names beginning with a period unless they were named as file operands.

Implementations are expected to traverse arbitrary depths when processing the -R option. The only limitation on depth should be based on running out of physical storage for keeping track of untraversed directories.

The -1 (one) option was historically found in BSD and BSD-derived implementations only. It is required in this volume of IEEE Std 1003.1-2001 so that conforming applications might ensure that output is one entry per line, even if the output is to a terminal.

Generally, this volume of IEEE Std 1003.1-2001 is silent about what happens when options are given multiple times. In the cases of -C, -l, and -1, however, it does specify the results of these overlapping options. Since ls is one of the most aliased commands, it is important that the implementation perform intuitively. For example, if the alias were:

alias ls="ls -C"

and the user typed ls -1, single-text-column output should result, not an error.

The BSD ls provides a -A option (like -a, but dot and dot-dot are not written out). The small difference from -a did not seem important enough to require both.

Implementations may make -q the default for terminals to prevent trojan horse attacks on terminals with special escape sequences. This is not required because:

*
Some control characters may be useful on some terminals; for example, a system might write them as "\001" or "^A" .

*
Special behavior for terminals is not relevant to applications portability.

An early proposal specified that the optional alternate access method flag had to be '+' if there was an alternate access method used on the file or <space> if there was not. This was changed to be <space> if there is not and a single printable character if there is. This was done for three reasons:

1.
There are historical implementations using characters other than '+' .

2.
There are implementations that vary this character used in that position to distinguish between various alternate access methods in use.

3.
The standard developers did not want to preclude future specifications that might need a way to specify more than one alternate access method.

Nonetheless, implementations providing a single alternate access method are encouraged to use '+' .

In an early proposal, the units used to specify the number of blocks occupied by files in a directory in an ls -l listing were implementation-defined. This was because BSD systems have historically used 1024-byte units and System V systems have historically used 512-byte units. It was pointed out by BSD developers that their system has used 512-byte units in some places and 1024-byte units in other places. (System V has consistently used 512.) Therefore, this volume of IEEE Std 1003.1-2001 usually specifies 512. Future releases of BSD are expected to consistently provide 512 bytes as a default with a way of specifying 1024-byte units where appropriate.

The <date and time> field in the -l format is specified only for the POSIX locale. As noted, the format can be different in other locales. No mechanism for defining this is present in this volume of IEEE Std 1003.1-2001, as the appropriate vehicle is a messaging system; that is, the format should be specified as a "message".

FUTURE DIRECTIONS

The -s uses implementation-defined units and cannot be used portably; it may be withdrawn in a future version.

SEE ALSO

chmod() , find , the System Interfaces volume of IEEE Std 1003.1-2001, stat(), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mv(1p)

MV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mv - move files

SYNOPSIS

mv [-fi] source_file target_file

mv [-fi] source_file... target_file

DESCRIPTION

In the first synopsis form, the mv utility shall move the file named by the source_file operand to the destination specified by the target_file. This first synopsis form is assumed when the final operand does not name an existing directory and is not a symbolic link referring to an existing directory.

In the second synopsis form, mv shall move each file named by a source_file operand to a destination file in the existing directory named by the target_dir operand, or referenced if target_dir is a symbolic link referring to an existing directory. The destination path for each source_file shall be the concatenation of the target directory, a single slash character, and the last pathname component of the source_file. This second form is assumed when the final operand names an existing directory.

If any operand specifies an existing file of a type not specified by the System Interfaces volume of IEEE Std 1003.1-2001, the behavior is implementation-defined.

For each source_file the following steps shall be taken:

1.
If the destination path exists, the -f option is not specified, and either of the following conditions is true:
a.
The permissions of the destination path do not permit writing and the standard input is a terminal.

b.
The -i option is specified.

the mv utility shall write a prompt to standard error and read a line from standard input. If the response is not affirmative, mv shall do nothing more with the current source_file and go on to any remaining source_files.

2.
The mv utility shall perform actions equivalent to the rename() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:
a.
The source_file operand is used as the old argument.

b.
The destination path is used as the new argument.

If this succeeds, mv shall do nothing more with the current source_file and go on to any remaining source_files. If this fails for any reasons other than those described for the errno [EXDEV] in the System Interfaces volume of IEEE Std 1003.1-2001, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.

3.
If the destination path exists, and it is a file of type directory and source_file is not a file of type directory, or it is a file not of type directory and source_file is a file of type directory, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.

4.
If the destination path exists, mv shall attempt to remove it. If this fails for any reason, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.

5.
The file hierarchy rooted in source_file shall be duplicated as a file hierarchy rooted in the destination path. If source_file or any of the files below it in the hierarchy are symbolic links, the links themselves shall be duplicated, including their contents, rather than any files to which they refer. The following characteristics of each file in the file hierarchy shall be duplicated:
*
The time of last data modification and time of last access

*
The user ID and group ID

*
The file mode

If the user ID, group ID, or file mode of a regular file cannot be duplicated, the file mode bits S_ISUID and S_ISGID shall not be duplicated.

When files are duplicated to another file system, the implementation may require that the process invoking mv has read access to each file being duplicated.

If the duplication of the file hierarchy fails for any reason, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.

If the duplication of the file characteristics fails for any reason, mv shall write a diagnostic message to standard error, but this failure shall not cause mv to modify its exit status.

6.
The file hierarchy rooted in source_file shall be removed. If this fails for any reason, mv shall write a diagnostic message to the standard error, do nothing more with the current source_file, and go on to any remaining source_files.

OPTIONS

The mv utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-f
Do not prompt for confirmation if the destination path exists. Any previous occurrence of the -i option is ignored.
-i
Prompt for confirmation if the destination path exists. Any previous occurrence of the -f option is ignored.

Specifying more than one of the -f or -i options shall not be considered an error. The last option specified shall determine the behavior of mv.

OPERANDS

The following operands shall be supported:

source_file
A pathname of a file or directory to be moved.
target_file
A new pathname for the file or directory being moved.
target_dir
A pathname of an existing directory into which to move the input files.

STDIN

The standard input shall be used to read an input line in response to each prompt specified in the STDERR section. Otherwise, the standard input shall not be used.

INPUT FILES

The input files specified by each source_file operand can be of any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of mv:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.
LC_MESSAGES
Determine the locale for the processing of affirmative responses that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

Prompts shall be written to the standard error under the conditions specified in the DESCRIPTION section. The prompts shall contain the destination pathname, but their format is otherwise unspecified. Otherwise, the standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output files may be of any file type.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were moved successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If the copying or removal of source_file is prematurely terminated by a signal or error, mv may leave a partial copy of source_file at the source or destination. The mv utility shall not modify both source_file and the destination path simultaneously; termination at any point shall leave either source_file or the destination path complete.

The following sections are informative.

APPLICATION USAGE

Some implementations mark for update the st_ctime field of renamed files and some do not. Applications which make use of the st_ctime field may behave differently with respect to renamed files unless they are designed to allow for either behavior.

EXAMPLES

If the current directory contains only files a (of any type defined by the System Interfaces volume of IEEE Std 1003.1-2001), b (also of any type), and a directory c:

mv a b c
mv c d

results with the original files a and b residing in the directory d in the current directory.

RATIONALE

Early proposals diverged from the SVID and BSD historical practice in that they required that when the destination path exists, the -f option is not specified, and input is not a terminal, mv fails. This was done for compatibility with cp. The current text returns to historical practice. It should be noted that this is consistent with the rename() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, which does not require write permission on the target.

For absolute clarity, paragraph (1), describing the behavior of mv when prompting for confirmation, should be interpreted in the following manner:

if (exists AND (NOT f_option) AND
    ((not_writable AND input_is_terminal) OR i_option))

The -i option exists on BSD systems, giving applications and users a way to avoid accidentally unlinking files when moving others. When the standard input is not a terminal, the 4.3 BSD mv deletes all existing destination paths without prompting, even when -i is specified; this is inconsistent with the behavior of the 4.3 BSD cp utility, which always generates an error when the file is unwritable and the standard input is not a terminal. The standard developers decided that use of -i is a request for interaction, so when the destination path exists, the utility takes instructions from whatever responds to standard input.

The rename() function is able to move directories within the same file system. Some historical versions of mv have been able to move directories, but not to a different file system. The standard developers considered that this was an annoying inconsistency, so this volume of IEEE Std 1003.1-2001 requires directories to be able to be moved even across file systems. There is no -R option to confirm that moving a directory is actually intended, since such an option was not required for moving directories in historical practice. Requiring the application to specify it sometimes, depending on the destination, seemed just as inconsistent. The semantics of the rename() function were preserved as much as possible. For example, mv is not permitted to "rename" files to or from directories, even though they might be empty and removable.

Historic implementations of mv did not exit with a non-zero exit status if they were unable to duplicate any file characteristics when moving a file across file systems, nor did they write a diagnostic message for the user. The former behavior has been preserved to prevent scripts from breaking; a diagnostic message is now required, however, so that users are alerted that the file characteristics have changed.

The exact format of the interactive prompts is unspecified. Only the general nature of the contents of prompts are specified because implementations may desire more descriptive prompts than those used on historical implementations. Therefore, an application not using the -f option or using the -i option relies on the system to provide the most suitable dialog directly with the user, based on the behavior specified.

When mv is dealing with a single file system and source_file is a symbolic link, the link itself is moved as a consequence of the dependence on the rename() functionality, per the DESCRIPTION. Across file systems, this has to be made explicit.

FUTURE DIRECTIONS

None.

SEE ALSO

cp , ln , the System Interfaces volume of IEEE Std 1003.1-2001, rename()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nl(1p)

NL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nl - line numbering filter

SYNOPSIS

nl [-p][-b type][-d delim][-f type][-h type][-i incr][-l num][-n format]
[-s sep][-v startnum][-w width][file]

DESCRIPTION

The nl utility shall read lines from the named file or the standard input if no file is named and shall reproduce the lines to standard output. Lines shall be numbered on the left. Additional functionality may be provided in accordance with the command options in effect.

The nl utility views the text it reads in terms of logical pages. Line numbering shall be reset at the start of each logical page. A logical page consists of a header, a body, and a footer section. Empty sections are valid. Different line numbering options are independently available for header, body, and footer (for example, no numbering of header and footer lines while numbering blank lines only in the body).

The starts of logical page sections shall be signaled by input lines containing nothing but the following delimiter characters:
Line | Start of
\:\:\: | Header
\:\: | Body
\: | Footer

Unless otherwise specified, nl shall assume the text being read is in a single logical page body.

OPTIONS

The nl utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. Only one file can be named.

The following options shall be supported:

-b type
Specify which logical page body lines shall be numbered. Recognized types and their meaning are:
a
Number all lines.
t
Number only non-empty lines.
n
No line numbering.
p string
Number only lines that contain the basic regular expression specified in string.

The default type for logical page body shall be t (text lines numbered).

-d delim
Specify the delimiter characters that indicate the start of a logical page section. These can be changed from the default characters "\:" to two user-specified characters. If only one character is entered, the second character shall remain the default character ':' .
-f type
Specify the same as b type except for footer. The default for logical page footer shall be n (no lines numbered).
-h type
Specify the same as b type except for header. The default type for logical page header shall be n (no lines numbered).
-i incr
Specify the increment value used to number logical page lines. The default shall be 1.
-l num
Specify the number of blank lines to be considered as one. For example, -l 2 results in only the second adjacent blank line being numbered (if the appropriate -h a, -b a, or -f a option is set). The default shall be 1.
-n format
Specify the line numbering format. Recognized values are: ln, left justified, leading zeros suppressed; rn, right justified, leading zeros suppressed; rz, right justified, leading zeros kept. The default format shall be rn (right justified).
-p
Specify that numbering should not be restarted at logical page delimiters.
-s sep
Specify the characters used in separating the line number and the corresponding text line. The default sep shall be a <tab>.
-v startnum
Specify the initial value used to number logical page lines. The default shall be 1.
-w width
Specify the number of characters to be used for the line number. The default width shall be 6.

OPERANDS

The following operand shall be supported:

file
A pathname of a text file to be line-numbered.

STDIN

The standard input is a text file that is used if no file operand is given.

INPUT FILES

The input file named by the file operand is a text file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of nl:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the behavior of character classes within regular expressions, and for deciding which characters are in character class graph (for the -b t, -f t, and -h t options).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be a text file in the following format:

"%s%s%s", <line number>, <separator>, <input line>

where <line number> is one of the following numeric formats:

%6d
When the rn format is used (the default; see -n).
%06d
When the rz format is used.
%-6d
When the ln format is used.
<empty>
When line numbers are suppressed for a portion of the page; the <separator> is also suppressed.

In the preceding list, the number 6 is the default width; the -w option can change this value.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

In using the -d delim option, care should be taken to escape characters that have special meaning to the command interpreter.

EXAMPLES

The command:

nl -v 10 -i 10 -d \!+ file1

numbers file1 starting at line number 10 with an increment of 10. The logical page delimiter is "!+" . Note that the '!' has to be escaped when using csh as a command interpreter because of its history substitution syntax. For ksh and sh the escape is not necessary, but does not do any harm.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pr

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nm(1p)

NM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nm - write the name list of an object file (DEVELOPMENT)

SYNOPSIS

nm [-APv][-efox][ -g| -u][-t format] file...

DESCRIPTION

This utility shall be provided on systems that support both the User Portability Utilities option and the Software Development Utilities option. On other systems it is optional. Certain options are only available on XSI-conformant systems.

The nm utility shall display symbolic information appearing in the object file, executable file, or object-file library named by file. If no symbolic information is available for a valid input file, the nm utility shall report that fact, but not consider it an error condition.

The default base used when numeric values are written is unspecified. On XSI-conformant systems, it shall be decimal.

OPTIONS

The nm utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-A
Write the full pathname or library name of an object on each line.
-e
Write only external (global) and static symbol information.
-f
Produce full output. Write redundant symbols ( .text, .data, and .bss), normally suppressed.
-g
Write only external (global) symbol information.
-o
Write numeric values in octal (equivalent to -t o).
-P
Write information in a portable output format, as specified in the STDOUT section.
-t format
Write each numeric value in the specified format. The format shall be dependent on the single character used as the format option-argument:
d
The offset is written in decimal (default).
o
The offset is written in octal.
x
The offset is written in hexadecimal.

-u
Write only undefined symbols.
-v
Sort output by value instead of alphabetically.
-x
Write numeric values in hexadecimal (equivalent to -t x).

OPERANDS

The following operand shall be supported:

file
A pathname of an object file, executable file, or object-file library.

STDIN

See the INPUT FILES section.

INPUT FILES

The input file shall be an object file, an object-file library whose format is the same as those produced by the ar utility for link editing, or an executable file. The nm utility may accept additional implementation-defined object library formats for the input file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of nm:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for character collation information for the symbol-name and symbol-value collation sequences.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If symbolic information is present in the input files, then for each file or for each member of an archive, the nm utility shall write the following information to standard output. By default, the format is unspecified, but the output shall be sorted alphabetically by symbol name:

*
Library or object name, if -A is specified

*
Symbol name

*
Symbol type, which shall either be one of the following single characters or an implementation-defined type represented by a single character:
A
Global absolute symbol.
a
Local absolute symbol.
B
Global "bss" (that is, uninitialized data space) symbol.
b
Local bss symbol.
D
Global data symbol.
d
Local data symbol.
T
Global text symbol.
t
Local text symbol.
U
Undefined symbol.

*
Value of the symbol

*
The size associated with the symbol, if applicable

This information may be supplemented by additional information specific to the implementation.

If the -P option is specified, the previous information shall be displayed using the following portable format. The three versions differ depending on whether -t d, -t o, or -t x was specified, respectively:

"%s%s %s %d %d\n", <library/object name>, <name>, <type>,
    <value>, <size>

"%s%s %s %o %o\n", <library/object name>, <name>, <type>,
    <value>, <size>

"%s%s %s %x %x\n", <library/object name>, <name>, <type>,
    <value>, <size>
where <library/object name> shall be formatted as follows:
*
If -A is not specified, <library/object name> shall be an empty string.

*
If -A is specified and the corresponding file operand does not name a library:

"%s: ", <file>

*
If -A is specified and the corresponding file operand names a library. In this case, <object file> shall name the object file in the library containing the symbol being described:

"%s[%s]: ", <file>, <object file>

If -A is not specified, then if more than one file operand is specified or if only one file operand is specified and it names a library, nm shall write a line identifying the object containing the following symbols before the lines containing those symbols, in the form:

*
If the corresponding file operand does not name a library:

"%s:\n", <file>

*
If the corresponding file operand names a library; in this case, <object file> shall be the name of the file in the library containing the following symbols:

"%s[%s]:\n", <file>, <object file>

If -P is specified, but -t is not, the format shall be as if -t x had been specified.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Mechanisms for dynamic linking make this utility less meaningful when applied to an executable file because a dynamically linked executable may omit numerous library routines that would be found in a statically linked executable.

EXAMPLES

None.

RATIONALE

Historical implementations of nm have used different bases for numeric output and supplied different default types of symbols that were reported. The -t format option, similar to that used in od and strings, can be used to specify the numeric base; -g and -u can be used to restrict the amount of output or the types of symbols included in the output.

The compromise of using -t format versus using -d, -o, and other similar options was necessary because of differences in the meaning of -o between implementations. The -o option from BSD has been provided here as -A to avoid confusion with the -o from System V (which has been provided here as -t and as -o on XSI-conformant systems).

The option list was significantly reduced from that provided by historical implementations.

The nm description is a subset of both the System V and BSD nm utilities with no specified default output.

It was recognized that mechanisms for dynamic linking make this utility less meaningful when applied to an executable file (because a dynamically linked executable file may omit numerous library routines that would be found in a statically linked executable file), but the value of nm during software development was judged to outweigh other limitations.

The default output format of nm is not specified because of differences in historical implementations. The -P option was added to allow some type of portable output format. After a comparison of the different formats used in SunOS, BSD, SVR3, and SVR4, it was decided to create one that did not match the current format of any of these four systems. The format devised is easy to parse by humans, easy to parse in shell scripts, and does not need to vary depending on locale (because no English descriptions are included). All of the systems currently have the information available to use this format.

The format given in nm STDOUT uses spaces between the fields, which may be any number of <blank>s required to align the columns. The single-character types were selected to match historical practice, and the requirement that implementation additions also be single characters made parsing the information easier for shell scripts.

FUTURE DIRECTIONS

None.

SEE ALSO

ar , c99

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


od(1p)

OD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

od - dump files in various formats

SYNOPSIS

od [-v][-A address_base][-j skip][-N count][-t type_string]...
[file...]

od [-bcdosx][file] [[+]offset[.][b]]

DESCRIPTION

The od utility shall write the contents of its input files to standard output in a user-specified format.

OPTIONS

The od utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the order of presentation of the -t options and the -bcdosx options is significant.

The following options shall be supported:

-A address_base

Specify the input offset base. See the EXTENDED DESCRIPTION section. The application shall ensure that the address_base option-argument is a character. The characters 'd' , 'o' , and 'x' specify that the offset base shall be written in decimal, octal, or hexadecimal, respectively. The character 'n' specifies that the offset shall not be written.

-b
Interpret bytes in octal. This shall be equivalent to -t o1.
-c
Interpret bytes as characters specified by the current setting of the LC_CTYPE category. Certain non-graphic characters appear as C escapes: "NUL=\0" , "BS=\b" , "FF=\f" , "NL=\n" , "CR=\r" , "HT=\t" ; others appear as 3-digit octal numbers.
-d
Interpret words (two-byte units) in unsigned decimal. This shall be equivalent to -t u2.
-j skip
Jump over skip bytes from the beginning of the input. The od utility shall read or seek past the first skip bytes in the concatenated input files. If the combined input is not at least skip bytes long, the od utility shall write a diagnostic message to standard error and exit with a non-zero exit status.

By default, the skip option-argument shall be interpreted as a decimal number. With a leading 0x or 0X, the offset shall be interpreted as a hexadecimal number; otherwise, with a leading '0' , the offset shall be interpreted as an octal number. Appending the character 'b' , 'k' , or 'm' to offset shall cause it to be interpreted as a multiple of 512, 1024, or 1048576 bytes, respectively. If the skip number is hexadecimal, any appended 'b' shall be considered to be the final hexadecimal digit.

-N count
Format no more than count bytes of input. By default, count shall be interpreted as a decimal number. With a leading 0x or 0X, count shall be interpreted as a hexadecimal number; otherwise, with a leading '0' , it shall be interpreted as an octal number. If count bytes of input (after successfully skipping, if -j skip is specified) are not available, it shall not be considered an error; the od utility shall format the input that is available.
-o
Interpret words (two-byte units) in octal. This shall be equivalent to -t o2.
-s
Interpret words (two-byte units) in signed decimal. This shall be equivalent to -t d2.
-t type_string

Specify one or more output types. See the EXTENDED DESCRIPTION section. The application shall ensure that the type_string option-argument is a string specifying the types to be used when writing the input data. The string shall consist of the type specification characters a , c , d , f , o , u , and x , specifying named character, character, signed decimal, floating point, octal, unsigned decimal, and hexadecimal, respectively. The type specification characters d , f , o , u , and x can be followed by an optional unsigned decimal integer that specifies the number of bytes to be transformed by each instance of the output type. The type specification character f can be followed by an optional F , D , or L indicating that the conversion should be applied to an item of type float, double, or long double, respectively. The type specification characters d , o , u , and x can be followed by an optional C , S , I , or L indicating that the conversion should be applied to an item of type char, short, int, or long, respectively. Multiple types can be concatenated within the same type_string and multiple -t options can be specified. Output lines shall be written for each type specified in the order in which the type specification characters are specified.

-v
Write all input data. Without the -v option, any number of groups of output lines, which would be identical to the immediately preceding group of output lines (except for the byte offsets), shall be replaced with a line containing only an asterisk ( '*' ).
-x
Interpret words (two-byte units) in hexadecimal. This shall be equivalent to -t x2.

Multiple types can be specified by using multiple -bcdostx options. Output lines are written for each type specified in the order in which the types are specified.

OPERANDS

The following operands shall be supported:

file
A pathname of a file to be read. If no file operands are specified, the standard input shall be used.

If there are no more than two operands, none of the -A, -j, -N, or -t options is specified, and either of the following is true: the first character of the last operand is a plus sign ( '+' ), or there are two operands and the first character of the last operand is numeric; the last operand shall be interpreted as an offset operand on XSI-conformant systems. Under these conditions, the results are unspecified on systems that are not XSI-conformant systems.

[+]offset[.][b]
The offset operand specifies the offset in the file where dumping is to commence. This operand is normally interpreted as octal bytes. If '.' is appended, the offset shall be interpreted in decimal. If 'b' is appended, the offset shall be interpreted in units of 512 bytes.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

The input files can be any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of od:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_NUMERIC

Determine the locale for selecting the radix character used when writing floating-point formatted output.

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the EXTENDED DESCRIPTION section.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The od utility shall copy sequentially each input file to standard output, transforming the input data according to the output types specified by the -t option or the -bcdosx options. If no output type is specified, the default output shall be as if -t oS had been specified.

The number of bytes transformed by the output type specifier c may be variable depending on the LC_CTYPE category.

The default number of bytes transformed by output type specifiers d , f , o , u , and x corresponds to the various C-language types as follows. If the c99 compiler is present on the system, these specifiers shall correspond to the sizes used by default in that compiler. Otherwise, these sizes may vary among systems that conform to IEEE Std 1003.1-2001.

*
For the type specifier characters d , o , u , and x , the default number of bytes shall correspond to the size of the underlying implementation's basic integer type. For these specifier characters, the implementation shall support values of the optional number of bytes to be converted corresponding to the number of bytes in the C-language types char, short, int, and long. These numbers can also be specified by an application as the characters 'C' , 'S' , 'I' , and 'L' , respectively. The implementation shall also support the values 1, 2, 4, and 8, even if it provides no C-Language types of those sizes. The implementation shall support the decimal value corresponding to the C-language type long long. The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system.

*
For the type specifier character f , the default number of bytes shall correspond to the number of bytes in the underlying implementation's basic double precision floating-point data type. The implementation shall support values of the optional number of bytes to be converted corresponding to the number of bytes in the C-language types float, double, and long double. These numbers can also be specified by an application as the characters 'F' , 'D' , and 'L' , respectively.

The type specifier character a specifies that bytes shall be interpreted as named characters from the International Reference Version (IRV) of the ISO/IEC 646:1991 standard. Only the least significant seven bits of each byte shall be used for this type specification. Bytes with the values listed in the following table shall be written using the corresponding names for those characters.

Table: Named Characters in od
Value | Name | Value | Name | Value | Name | Value | Name
\000 | nul | \001 | soh | \002 | stx | \003 | etx
\004 | eot | \005 | enq | \006 | ack | \007 | bel
\010 | bs | \011 | ht | \012 | lf or nl | \013 | vt
\014 | ff | \015 | cr | \016 | so | \017 | si
\020 | dle | \021 | dc1 | \022 | dc2 | \023 | dc3
\024 | dc4 | \025 | nak | \026 | syn | \027 | etb
\030 | can | \031 | em | \032 | sub | \033 | esc
\034 | fs | \035 | gs | \036 | rs | \037 | us
\040 | sp | \177 | del |  |  |  |
Note:
The "\012" value may be written either as lf or nl.

The type specifier character c specifies that bytes shall be interpreted as characters specified by the current setting of the LC_CTYPE locale category. Characters listed in the table in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ) shall be written as the corresponding escape sequences, except that backslash shall be written as a single backslash and a NUL shall be written as '\0' . Other non-printable characters shall be written as one three-digit octal number for each byte in the character. If the size of a byte on the system is greater than nine bits, the format used for non-printable characters is implementation-defined. Printable multi-byte characters shall be written in the area corresponding to the first byte of the character; the two-character sequence "**" shall be written in the area corresponding to each remaining byte in the character, as an indication that the character is continued. When either the -j skip or -N count option is specified along with the c type specifier, and this results in an attempt to start or finish in the middle of a multi-byte character, the result is implementation-defined.

The input data shall be manipulated in blocks, where a block is defined as a multiple of the least common multiple of the number of bytes transformed by the specified output types. If the least common multiple is greater than 16, the results are unspecified. Each input block shall be written as transformed by each output type, one per written line, in the order that the output types were specified. If the input block size is larger than the number of bytes transformed by the output type, the output type shall sequentially transform the parts of the input block, and the output from each of the transformations shall be separated by one or more <blank>s.

If, as a result of the specification of the -N option or end-of-file being reached on the last input file, input data only partially satisfies an output type, the input shall be extended sufficiently with null bytes to write the last byte of the input.

Unless -A n is specified, the first output line produced for each input block shall be preceded by the input offset, cumulative across input files, of the next byte to be written. The format of the input offset is unspecified; however, it shall not contain any <blank>s, shall start at the first character of the output line, and shall be followed by one or more <blank>s. In addition, the offset of the byte following the last byte written shall be written after all the input data has been processed, but shall not be followed by any <blank>s.

If no -A option is specified, the input offset base is unspecified.

EXIT STATUS

The following exit values shall be returned:

0
All input files were processed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

XSI-conformant applications are warned not to use filenames starting with '+' or a first operand starting with a numeric character so that the old functionality can be maintained by implementations, unless they specify one of the -A, -j, or -N options. To guarantee that one of these filenames is always interpreted as a filename, an application could always specify the address base format with the -A option.

EXAMPLES

If a file containing 128 bytes with decimal values zero to 127, in increasing order, is supplied as standard input to the command:

od -A d -t a

on an implementation using an input block size of 16 bytes, the standard output, independent of the current locale setting, would be similar to:

0000000 nul soh stx etx eot enq ack bel  bs  ht  nl  vt  ff  cr  so  si
0000016 dle dc1 dc2 dc3 dc4 nak syn etb can  em sub esc  fs  gs  rs  us
0000032  sp   !   "   #   $   %   &   '   (   )   *   +   ,   -   .  /
0000048   0   1   2   3   4   5   6   7   8   9   :   ;   <   =   >   ?
0000064   @   A   B   C   D   E   F   G   H   I   J   K   L   M   N   O
0000080   P   Q   R   S   T   U   V   W   X   Y   Z   [   \   ]   ^   _
0000096   `   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o
0000112   p   q   r   s   t   u   v   w   x   y   z   {   |   }   ~ del
0000128

Note that this volume of IEEE Std 1003.1-2001 allows nl or lf to be used as the name for the ISO/IEC 646:1991 standard IRV character with decimal value 10. The IRV names this character lf (line feed), but traditional implementations have referred to this character as newline ( nl) and the POSIX locale character set symbolic name for the corresponding character is a <newline>.

The command:

od -A o -t o2x2x -N 18

on a system with 32-bit words and an implementation using an input block size of 16 bytes could write 18 bytes in approximately the following format:

0000000 032056 031440 041123 042040 052516 044530 020043 031464
          342e   3320   4253   4420   554e   4958   2023   3334
             342e3320      42534420      554e4958      20233334
0000020 032472
          353a
             353a0000
0000022

The command:

od -A d -t f -t o4 -t x4 -N 24 -j 0x15

on a system with 64-bit doubles (for example, IEEE Std 754-1985 double precision floating-point format) would skip 21 bytes of input data and then write 24 bytes in approximately the following format:

0000000    1.00000000000000e+00    1.57350000000000e+01
        07774000000 00000000000 10013674121 35341217270
           3ff00000    00000000    402f3851    eb851eb8
0000016    1.40668230000000e+02
        10030312542 04370303230
           40619562    23e18698
0000024

RATIONALE

The od utility went through several names in early proposals, including hd, xd, and most recently hexdump. There were several objections to all of these based on the following reasons:

*
The hd and xd names conflicted with historical utilities that behaved differently.

*
The hexdump description was much more complex than needed for a simple dump utility.

*
The od utility has been available on all historical implementations and there was no need to create a new name for a utility so similar to the historical od utility.

The original reasons for not standardizing historical od were also fairly widespread. Those reasons are given below along with rationale explaining why the standard developers believe that this version does not suffer from the indicated problem:

*
The BSD and System V versions of od have diverged, and the intersection of features provided by both does not meet the needs of the user community. In fact, the System V version only provides a mechanism for dumping octal bytes and shorts, signed and unsigned decimal shorts, hexadecimal shorts, and ASCII characters. BSD added the ability to dump floats, doubles, named ASCII characters, and octal, signed decimal, unsigned decimal, and hexadecimal longs. The version presented here provides more normalized forms for dumping bytes, shorts, ints, and longs in octal, signed decimal, unsigned decimal, and hexadecimal; float, double, and long double; and named ASCII as well as current locale characters.

*
It would not be possible to come up with a compatible superset of the BSD and System V flags that met the requirements of the standard developers. The historical default od output is the specified default output of this utility. None of the option letters chosen for this version of od conflict with any of the options to historical versions of od.

*
On systems with different sizes for short, int, and long, there was no way to ask for dumps of ints, even in the BSD version. Because of the way options are named, the name space could not be extended to solve these problems. This is why the -t option was added (with type specifiers more closely matched to the printf() formats used in the rest of this volume of IEEE Std 1003.1-2001) and the optional field sizes were added to the d , f , o , u , and x type specifiers. It is also one of the reasons why the historical practice was not mandated as a required obsolescent form of od. (Although the old versions of od are not listed as an obsolescent form, implementations are urged to continue to recognize the older forms for several more years.) The a , c , f , o , and x types match the meaning of the corresponding format characters in the historical implementations of od except for the default sizes of the fields converted. The d format is signed in this volume of IEEE Std 1003.1-2001 to match the printf() notation. (Historical versions of od used d as a synonym for u in this version. The System V implementation uses s for signed decimal; BSD uses i for signed decimal and s for null-terminated strings.) Other than d and u , all of the type specifiers match format characters in the historical BSD version of od.

The sizes of the C-language types char, short, int, long, float, double, and long double are used even though it is recognized that there may be zero or more than one compiler for the C language on an implementation and that they may use different sizes for some of these types. (For example, one compiler might use 2 bytes shorts, 2 bytes ints, and 4 bytes longs, while another compiler (or an option to the same compiler) uses 2 bytes shorts, 4 bytes ints, and 4 bytes longs.) Nonetheless, there has to be a basic size known by the implementation for these types, corresponding to the values reported by invocations of the getconf utility when called with system_var operands {UCHAR_MAX}, {USHORT_MAX}, {UINT_MAX}, and {ULONG_MAX} for the types char, short, int, and long, respectively. There are similar constants required by the ISO C standard, but not required by the System Interfaces volume of IEEE Std 1003.1-2001 or this volume of IEEE Std 1003.1-2001. They are {FLT_MANT_DIG}, {DBL_MANT_DIG}, and {LDBL_MANT_DIG} for the types float, double, and long double, respectively. If the optional c99 utility is provided by the implementation and used as specified by this volume of IEEE Std 1003.1-2001, these are the sizes that would be provided. If an option is used that specifies different sizes for these types, there is no guarantee that the od utility is able to interpret binary data output by such a program correctly.

This volume of IEEE Std 1003.1-2001 requires that the numeric values of these lengths be recognized by the od utility and that symbolic forms also be recognized. Thus, a conforming application can always look at an array of unsigned long data elements using od -t uL.

*
The method of specifying the format for the address field based on specifying a starting offset in a file unnecessarily tied the two together. The -A option now specifies the address base and the -S option specifies a starting offset.

*
It would be difficult to break the dependence on U.S. ASCII to achieve an internationalized utility. It does not seem to be any harder for od to dump characters in the current locale than it is for the ed or sed l commands. The c type specifier does this without difficulty and is completely compatible with the historical implementations of the c format character when the current locale uses a superset of the ISO/IEC 646:1991 standard as a codeset. The a type specifier (from the BSD a format character) was left as a portable means to dump ASCII (or more correctly ISO/IEC 646:1991 standard (IRV)) so that headers produced by pax could be deciphered even on systems that do not use the ISO/IEC 646:1991 standard as a subset of their base codeset.

The use of "**" as an indication of continuation of a multi-byte character in c specifier output was chosen based on seeing an implementation that uses this method. The continuation bytes have to be marked in a way that is not ambiguous with another single-byte or multi-byte character.

An early proposal used -S and -n, respectively, for the -j and -N options eventually selected. These were changed to avoid conflicts with historical implementations.

The original standard specified -t o2 as the default when no output type was given. This was changed to -t oS (the length of a short) to accommodate a supercomputer implementation that historically used 64 bits as its default (and that defined shorts as 64 bits). This change should not affect conforming applications. The requirement to support lengths of 1, 2, and 4 was added at the same time to address an historical implementation that had no two-byte data types in its C compiler.

The use of a basic integer data type is intended to allow the implementation to choose a word size commonly used by applications on that architecture.

FUTURE DIRECTIONS

All option and operand interfaces marked as extensions may be withdrawn in a future version.

SEE ALSO

c99 , sed

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qsub(1p)

QSUB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qsub - submit a script

SYNOPSIS

qsub [-a date_time][-A account_string][-c interval]
[-C directive_prefix][-e path_name][-h][-j join_list][-k keep_list]
[-m mail_options][-M mail_list][-N name]
[-o path_name][-p priority][-q destination][-r y|n]
[-S path_name_list][-u user_list][-v variable_list][-V]
[-z][script]

DESCRIPTION

To submit a script is to create a batch job that executes the script. A script is submitted by a request to a batch server. The qsub utility is a user-accessible batch client that submits a script.

Upon successful completion, the qsub utility shall have created a batch job that will execute the submitted script.

The qsub utility shall submit a script by sending a Queue Job Request to a batch server.

The qsub utility shall place the value of the following environment variables in the Variable_List attribute of the batch job: HOME , LANG , LOGNAME , PATH , MAIL , SHELL , and TZ . The name of the environment variable shall be the current name prefixed with the string PBS_O_.

Note:
If the current value of the HOME variable in the environment space of the qsub utility is /aa/bb/cc, then qsub shall place PBS_O_HOME = /aa/bb/cc in the Variable_List attribute of the batch job.

In addition to the variables described above, the qsub utility shall add the following variables with the indicated values to the variable list:

PBS_O_WORKDIR
The absolute path of the current working directory of the qsub utility process.
PBS_O_HOST
The name of the host on which the qsub utility is running.

OPTIONS

The qsub utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-a date_time
Define the time at which a batch job becomes eligible for execution.

The qsub utility shall accept an option-argument that conforms to the syntax of the time operand of the touch utility.

Table: Environment Variable Values (Utilities)
Variable Name | Value at qsub Time
PBS_O_HOME | HOME
PBS_O_HOST | Client host name
PBS_O_LANG | LANG
PBS_O_LOGNAME | LOGNAME
PBS_O_PATH | PATH
PBS_O_MAIL | MAIL
PBS_O_SHELL | SHELL
PBS_O_TZ | TZ
PBS_O_WORKDIR | Current working directory
Note:
The server that initiates execution of the batch job will add other variables to the batch job's environment; see Batch Job Execution .

The qsub utility shall set the Execution_Time attribute of the batch job to the number of seconds since the Epoch that is equivalent to the local time expressed by the value of the date_time option-argument. The Epoch is defined in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.149, Epoch.

If the -a option is not presented to the qsub utility, the utility shall set the Execution_Time attribute of the batch job to a time (number of seconds since the Epoch) that is earlier than the time at which the utility exits.

-A account_string

Define the account to which the resource consumption of the batch job should be charged.

The syntax of the account_string option-argument is unspecified.

The qsub utility shall set the Account_Name attribute of the batch job to the value of the account_string option-argument.

If the -A option is not presented to the qsub utility, the utility shall omit the Account_Name attribute from the attributes of the batch job.

-c interval
Define whether the batch job should be checkpointed, and if so, how often.

The qsub utility shall accept a value for the interval option-argument that is one of the following:

n
No checkpointing shall be performed on the batch job (NO_CHECKPOINT).
s
Checkpointing shall be performed only when the batch server is shut down (CHECKPOINT_AT_SHUTDOWN).
c
Automatic periodic checkpointing shall be performed at the Minimum_Cpu_Interval attribute of the batch queue, in units of CPU minutes (CHECKPOINT_AT_MIN_CPU_INTERVAL).
c=minutes
Automatic periodic checkpointing shall be performed every minutes of CPU time, or every Minimum_Cpu_Interval minutes, whichever is greater. The minutes argument shall conform to the syntax for unsigned integers and shall be greater than zero.

The qsub utility shall set the Checkpoint attribute of the batch job to the value of the interval option-argument.

If the -c option is not presented to the qsub utility, the utility shall set the Checkpoint attribute of the batch job to the single character 'u' (CHECKPOINT_UNSPECIFIED).

-C directive_prefix

Define the prefix that declares a directive to the qsub utility within the script.

The directive_prefix is not a batch job attribute; it affects the behavior of the qsub utility.

If the -C option is presented to the qsub utility, and the value of the directive_prefix option-argument is the null string, the utility shall not scan the script file for directives. If the -C option is not presented to the qsub utility, then the value of the PBS_DPREFIX environment variable is used. If the environment variable is not defined, then #PBS encoded in the portable character set is the default.

-e path_name
Define the path to be used for the standard error stream of the batch job.

The qsub utility shall accept a path_name option-argument which can be preceded by a host name element of the form hostname:.

If the path_name option-argument constitutes an absolute pathname, the qsub utility shall set the Error_Path attribute of the batch job to the value of the path_name option-argument.

If the path_name option-argument constitutes a relative pathname and no host name element is specified, the qsub utility shall set the Error_Path attribute of the batch job to the value of the absolute pathname derived by expanding the path_name option-argument relative to the current directory of the process executing qsub.

If the path_name option-argument constitutes a relative pathname and a host name element is specified, the qsub utility shall set the Error_Path attribute of the batch job to the value of the path_name option-argument without expansion. The host name element shall be included.

If the path_name option-argument does not include a host name element, the qsub utility shall prefix the pathname with hostname:, where hostname is the name of the host upon which the qsub utility is being executed.

If the -e option is not presented to the qsub utility, the utility shall set the Error_Path attribute of the batch job to the host name and path of the current directory of the submitting process and the default filename.

The default filename for standard error has the following format:

job_name.esequence_number
-h
Specify that a USER hold is applied to the batch job.

The qsub utility shall set the value of the Hold_Types attribute of the batch job to the value USER.

If the -h option is not presented to the qsub utility, the utility shall set the Hold_Types attribute of the batch job to the value NO_HOLD.

-j join_list
Define which streams of the batch job are to be merged. The qsub -j option shall accept a value for the join_list option-argument that is a string of alphanumeric characters in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set).

The qsub utility shall accept a join_list option-argument that consists of one or more of the characters 'e' and 'o' , or the single character 'n' .

All of the other batch job output streams specified will be merged into the output stream represented by the character listed first in the join_list option-argument.

For each unique character in the join_list option-argument, the qsub utility shall add a value to the Join_Path attribute of the batch job as follows, each representing a different batch job stream to join:

e
The standard error of the batch job (JOIN_STD_ERROR).
o
The standard output of the batch job (JOIN_STD_OUTPUT).

An existing Join_Path attribute can be cleared by the following join type:

n
NO_JOIN

If 'n' is specified, then no files are joined. The qsub utility shall consider it an error if any join type other than 'n' is combined with join type 'n' .

Strictly conforming applications shall not repeat any of the characters 'e' , 'o' , or 'n' within the join_list option-argument. The qsub utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters.

An implementation may define other join types. The conformance document for an implementation shall describe any additional batch job streams, how they are specified, their internal behavior, and how they affect the behavior of the utility.

If the -j option is not presented to the qsub utility, the utility shall set the value of the Join_Path attribute of the batch job to NO_JOIN.

-k keep_list
Define which output of the batch job to retain on the execution host.

The qsub -k option shall accept a value for the keep_list option-argument that is a string of alphanumeric characters in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set).

The qsub utility shall accept a keep_list option-argument that consists of one or more of the characters 'e' and 'o' , or the single character 'n' .

For each unique character in the keep_list option-argument, the qsub utility shall add a value to the Keep_Files attribute of the batch job as follows, each representing a different batch job stream to keep:

e
The standard error of the batch job (KEEP_STD_ERROR).
o
The standard output of the batch job (KEEP_STD_OUTPUT).

If both 'e' and 'o' are specified, then both files are retained. An existing Keep_Files attribute can be cleared by the following keep type:

n
NO_KEEP

If 'n' is specified, then no files are retained. The qsub utility shall consider it an error if any keep type other than 'n' is combined with keep type 'n' .

Strictly conforming applications shall not repeat any of the characters 'e' , 'o' , or 'n' within the keep_list option-argument. The qsub utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters.

An implementation may define other keep types. The conformance document for an implementation shall describe any additional keep types, how they are specified, their internal behavior, and how they affect the behavior of the utility. If the -k option is not presented to the qsub utility, the utility shall set the Keep_Files attribute of the batch job to the value NO_KEEP.

-m mail_options

Define the points in the execution of the batch job at which the batch server that manages the batch job shall send mail about a change in the state of the batch job.

The qsub -m option shall accept a value for the mail_options option-argument that is a string of alphanumeric characters in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set).

The qsub utility shall accept a value for the mail_options option-argument that is a string of one or more of the characters 'e' , 'b' , and 'a' , or the single character 'n' .

For each unique character in the mail_options option-argument, the qsub utility shall add a value to the Mail_Users attribute of the batch job as follows, each representing a different time during the life of a batch job at which to send mail:

e
MAIL_AT_EXIT
b
MAIL_AT_BEGINNING
a
MAIL_AT_ABORT

If any of these characters are duplicated in the mail_options option-argument, the duplicates shall be ignored.

An existing Mail_Points attribute can be cleared by the following mail type:

n
NO_MAIL

If 'n' is specified, then mail is not sent. The qsub utility shall consider it an error if any mail type other than 'n' is combined with mail type 'n' .

Strictly conforming applications shall not repeat any of the characters 'e' , 'b' , 'a' , or 'n' within the mail_options option-argument.

The qsub utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters. An implementation may define other mail types. The conformance document for an implementation shall describe any additional mail types, how they are specified, their internal behavior, and how they affect the behavior of the utility.

If the -m option is not presented to the qsub utility, the utility shall set the Mail_Points attribute to the value MAIL_AT_ABORT.

-M mail_list
Define the list of users to which a batch server that executes the batch job shall send mail, if the server sends mail about the batch job.

The syntax of the mail_list option-argument is unspecified.

If the implementation of the qsub utility uses a name service to locate users, the utility should accept the syntax used by the name service.

If the implementation of the qsub utility does not use a name service to locate users, the implementation should accept the following syntax for user names:

mail_address[,,mail_address,, ...]

The interpretation of mail_address is implementation-defined.

The qsub utility shall set the Mail_Users attribute of the batch job to the value of the mail_list option-argument.

If the -M option is not presented to the qsub utility, the utility shall place only the user name and host name for the current process in the Mail_Users attribute of the batch job.

-N name
Define the name of the batch job.

The qsub -N option shall accept a value for the name option-argument that is a string of up to 15 alphanumeric characters in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set) where the first character is alphabetic.

The qsub utility shall set the value of the Job_Name attribute of the batch job to the value of the name option-argument.

If the -N option is not presented to the qsub utility, the utility shall set the Job_Name attribute of the batch job to the name of the script argument from which the directory specification if any, has been removed.

If the -N option is not presented to the qsub utility, and the script is read from standard input, the utility shall set the Job_Name attribute of the batch job to the value STDIN.

-o path_name
Define the path for the standard output of the batch job.

The qsub utility shall accept a path_name option-argument that conforms to the syntax of the path_name element defined in the System Interfaces volume of IEEE Std 1003.1-2001, which can be preceded by a host name element of the form hostname:.

If the path_name option-argument constitutes an absolute pathname, the qsub utility shall set the Output_Path attribute of the batch job to the value of the path_name option-argument without expansion.

If the path_name option-argument constitutes a relative pathname and no host name element is specified, the qsub utility shall set the Output_Path attribute of the batch job to the pathname derived by expanding the value of the path_name option-argument relative to the current directory of the process executing the qsub.

If the path_name option-argument constitutes a relative pathname and a host name element is specified, the qsub utility shall set the Output_Path attribute of the batch job to the value of the path_name option-argument without expansion.

If the path_name option-argument does not specify a host name element, the qsub utility shall prefix the pathname with hostname:, where hostname is the name of the host upon which the qsub utility is executing.

If the -o option is not presented to the qsub utility, the utility shall set the Output_Path attribute of the batch job to the host name and path of the current directory of the submitting process and the default filename.

The default filename for standard output has the following format:

job_name.osequence_number
-p priority
Define the priority the batch job should have relative to other batch jobs owned by the batch server.

The qsub utility shall set the Priority attribute of the batch job to the value of the priority option-argument.

If the -p option is not presented to the qsub utility, the value of the Priority attribute is implementation-defined.

The qsub utility shall accept a value for the priority option-argument that conforms to the syntax for signed decimal integers, and which is not less than -1024 and not greater than 1023.

-q destination

Define the destination of the batch job.

The destination is not a batch job attribute; it determines the batch server, and possibly the batch queue, to which the qsub utility batch queues the batch job.

The qsub utility shall submit the script to the batch server named by the destination option-argument or the server that owns the batch queue named in the destination option-argument.

The qsub utility shall accept an option-argument for the -q option that conforms to the syntax for a destination (see Destination ).

If the -q option is not presented to the qsub utility, the qsub utility shall submit the batch job to the default destination. The mechanism for determining the default destination is implementation-defined.

-r y|n
Define whether the batch job is rerunnable.

If the value of the option-argument is y, the qsub utility shall set the Rerunable attribute of the batch job to TRUE.

If the value of the option-argument is n, the qsub utility shall set the Rerunable attribute of the batch job to FALSE.

If the -r option is not presented to the qsub utility, the utility shall set the Rerunable attribute of the batch job to TRUE.

-S path_name_list

Define the pathname to the shell under which the batch job is to execute.

The qsub utility shall accept a path_name_list option-argument that conforms to the following syntax:

pathname[@host][,,pathname[@host],, ...]

The qsub utility shall allow only one pathname for a given host name. The qsub utility shall allow only one pathname that is missing a corresponding host name.

The qsub utility shall add a value to the Shell_Path_List attribute of the batch job for each entry in the path_name_list option-argument.

If the -S option is not presented to the qsub utility, the utility shall set the Shell_Path_List attribute of the batch job to the null string.

The conformance document for an implementation shall describe the mechanism used to set the default shell and determine the current value of the default shell. An implementation shall provide a means for the installation to set the default shell to the login shell of the user under which the batch job is to execute. See Multiple Keyword-Value Pairs for a means of removing keyword= value (and value@ keyword) pairs and other general rules for list-oriented batch job attributes.

-u user_list
Define the user name under which the batch job is to execute.

The qsub utility shall accept a user_list option-argument that conforms to the following syntax:

username[@host][,,username[@host],, ...]

The qsub utility shall accept only one user name that is missing a corresponding host name. The qsub utility shall accept only one user name per named host.

The qsub utility shall add a value to the User_List attribute of the batch job for each entry in the user_list option-argument.

If the -u option is not presented to the qsub utility, the utility shall set the User_List attribute of the batch job to the user name from which the utility is executing. See Multiple Keyword-Value Pairs for a means of removing keyword= value (and value@ keyword) pairs and other general rules for list-oriented batch job attributes.

-v variable_list

Add to the list of variables that are exported to the session leader of the batch job.

A variable_list is a set of strings of either the form < variable> or < variable= value>, delimited by commas.

If the -v option is presented to the qsub utility, the utility shall also add, to the environment Variable_List attribute of the batch job, every variable named in the environment variable_list option-argument and, optionally, values of specified variables.

If a value is not provided on the command line, the qsub utility shall set the value of each variable in the environment Variable_List attribute of the batch job to the value of the corresponding environment variable for the process in which the utility is executing; see Environment Variable Values (Utilities) .

A conforming application shall not repeat a variable in the environment variable_list option-argument.

The qsub utility shall not repeat a variable in the environment Variable_List attribute of the batch job. See Multiple Keyword-Value Pairs for a means of removing keyword= value (and value@ keyword) pairs and other general rules for list-oriented batch job attributes.

-V
Specify that all of the environment variables of the process are exported to the context of the batch job.

The qsub utility shall place every environment variable in the process in which the utility is executing in the list and shall set the value of each variable in the attribute to the value of that variable in the process.

-z
Specify that the utility does not write the batch job_identifier of the created batch job to standard output.

If the -z option is presented to the qsub utility, the utility shall not write the batch job_identifier of the created batch job to standard output.

If the -z option is not presented to the qsub utility, the utility shall write the identifier of the created batch job to standard output.

OPERANDS

The qsub utility shall accept a script operand that indicates the path to the script of the batch job.

If the script operand is not presented to the qsub utility, or if the operand is the single-character string '-' , the utility shall read the script from standard input.

If the script represents a partial path, the qsub utility shall expand the path relative to the current directory of the process executing the utility.

STDIN

The qsub utility reads the script of the batch job from standard input if the script operand is omitted or is the single character '-' .

INPUT FILES

In addition to binding the file indicated by the script operand to the batch job, the qsub utility reads the script file and acts on directives in the script.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qsub:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.
PBS_DPREFIX

Determine the default prefix for directives within the script.

SHELL
Determine the pathname of the preferred command language interpreter of the user.
TZ
Determine the timezone used to interpret the date-time option-argument. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Once created, a batch job exists until it exits, aborts, or is deleted.

After a batch job is created by the qsub utility, batch servers might route, execute, modify, or delete the batch job.

STDOUT

The qsub utility writes the batch job_identifier assigned to the batch job to standard output, unless the -z option is specified.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

Script Preservation

The qsub utility shall make the script available to the server executing the batch job in such a way that the server executes the script as it exists at the time of submission.

The qsub utility can send a copy of the script to the server with the Queue Job Request or store a temporary copy of the script in a location specified to the server.

Option Specification

A script can contain directives to the qsub utility.

The qsub utility shall scan the lines of the script for directives, skipping blank lines, until the first line that begins with a string other than the directive string; if directives occur on subsequent lines, the utility shall ignore those directives.

Lines are separated by a <newline>. If the first line of the script begins with "#!" or a colon ( ':' ), then it is skipped. The qsub utility shall process a line in the script as a directive if and only if the string of characters from the first non-white-space character on the line until the first <space> or <tab> on the line match the directive prefix. If a line in the script contains a directive and the final characters of the line are backslash ( '\' ) and <newline>, then the next line shall be interpreted as a continuation of that directive.

The qsub utility shall process the options and option-arguments contained on the directive prefix line using the same syntax as if the options were input on the qsub utility.

The qsub utility shall continue to process a directive prefix line until after a <newline> is encountered. An implementation may ignore lines which, according to the syntax of the shell that will interpret the script, are comments. An implementation shall describe in the conformance document the format of any shell comments that it will recognize.

If an option is present in both a directive and the arguments to the qsub utility, the utility shall ignore the option and the corresponding option-argument, if any, in the directive.

If an option that is present in the directive is not present in the arguments to the qsub utility, the utility shall process the option and the option-argument, if any.

In order of preference, the qsub utility shall select the directive prefix from one of the following sources:

*
If the -C option is presented to the utility, the value of the directive_prefix option-argument

*
If the environment variable PBS_DPREFIX is defined, the value of that variable

*
The four-character string "#PBS" encoded in the portable character set

If the -C option is present in the script file it shall be ignored.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qsub utility allows users to create a batch job that will process the script specified as the operand of the utility.

The options of the qsub utility allow users to control many aspects of the queuing and execution of a batch job.

The -a option allows users to designate the time after which the batch job will become eligible to run. By specifying an execution time, users can take advantage of resources at off-peak hours, synchronize jobs with chronologically predictable events, and perhaps take advantage of off-peak pricing of computing time. For these reasons and others, a timing option is existing practice on the part of almost every batch system, including NQS.

The -A option allows users to specify the account that will be charged for the batch job. Support for account is not mandatory for conforming batch servers.

The -C option allows users to prescribe the prefix for directives within the script file. The default prefix "#PBS" may be inappropriate if the script will be interpreted with an alternate shell, as specified by the -S option.

The -c option allows users to establish the checkpointing interval for their jobs. A checkpointing system, which is not defined by this volume of IEEE Std 1003.1-2001, allows recovery of a batch job at the most recent checkpoint in the event of a crash. Checkpointing is typically used for jobs that consume expensive computing time or must meet a critical schedule. Users should be allowed to make the tradeoff between the overhead of checkpointing and the risk to the timely completion of the batch job; therefore, this volume of IEEE Std 1003.1-2001 provides the checkpointing interval option. Support for checkpointing is optional for batch servers.

The -e option allows users to redirect the standard error streams of their jobs to a non-default path. For example, if the submitted script generally produces a great deal of useless error output, a user might redirect the standard error output to the null device. Or, if the file system holding the default location (the home directory of the user) has too little free space, the user might redirect the standard error stream to a file in another file system.

The -h option allows users to create a batch job that is held until explicitly released. The ability to create a held job is useful when some external event must complete before the batch job can execute. For example, the user might submit a held job and release it when the system load has dropped.

The -j option allows users to merge the standard error of a batch job into its standard output stream, which has the advantage of showing the sequential relationship between output and error messages.

The -m option allows users to designate those points in the execution of a batch job at which mail will be sent to the submitting user, or to the account(s) indicated by the -M option. By requesting mail notification at points of interest in the life of a job, the submitting user, or other designated users, can track the progress of a batch job.

The -N option allows users to associate a name with the batch job. The job name in no way affects the processing of the batch job, but rather serves as a mnemonic handle for users. For example, the batch job name can help the user distinguish between multiple jobs listed by the qstat utility.

The -o option allows users to redirect the standard output stream. A user might, for example, wish to redirect to the null device the standard output stream of a job that produces copious yet superfluous output.

The -P option allows users to designate the relative priority of a batch job for selection from a queue.

The -q option allows users to specify an initial queue for the batch job. If the user specifies a routing queue, the batch server routes the batch job to another queue for execution or further routing. If the user specifies a non-routing queue, the batch server of the queue eventually executes the batch job.

The -r option allows users to control whether the submitted job will be rerun if the controlling batch node fails during execution of the batch job. The -r option likewise allows users to indicate whether or not the batch job is eligible to be rerun by the qrerun utility. Some jobs cannot be correctly rerun because of changes they make in the state of databases or other aspects of their environment. This volume of IEEE Std 1003.1-2001 specifies that the default, if the -r option is not presented to the utility, will be that the batch job cannot be rerun, since the result of rerunning a non-rerunnable job might be catastrophic.

The -S option allows users to specify the program (usually a shell) that will be invoked to process the script of the batch job. This option has been modified to allow a list of shell names and locations associated with different hosts.

The -u option is useful when the submitting user is authorized to use more than one account on a given host, in which case the -u option allows the user to select from among those accounts. The option-argument is a list of user-host pairs, so that the submitting user can provide different user identifiers for different nodes in the event the batch job is routed. The -u option provides a lot of flexibility to accommodate sites with complex account structures. Users that have the same user identifier on all the hosts they are authorized to use will not need to use the -u option.

The -V option allows users to export all their current environment variables, as of the time the batch job is submitted, to the context of the processes of the batch job.

The -v option allows users to export specific environment variables from their current process to the processes of the batch job.

The -z option allows users to suppress the writing of the batch job identifier to standard output. The -z option is an existing NQS practice that has been standardized.

Historically, the qsub utility has served the batch job-submission function in the NQS system, the existing practice on which it is based. Some changes and additions have been made to the qsub utility in this volume of IEEE Std 1003.1-2001, vis-a-vis NQS, as a result of the growing pool of experience with distributed batch systems.

The set of features of the qsub utility as defined in this volume of IEEE Std 1003.1-2001 appears to incorporate all the common existing practice on potentially conforming platforms.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , qrerun , qstat , touch

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pr(1p)

PR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pr - print files

SYNOPSIS

pr [+page][-column][-adFmrt][-e[char][ gap]][-h header][-i[char][gap]]

[-l lines][-n[char][width]][-o offset][-s[char]][-w width][-fp]
[file...]

DESCRIPTION

The pr utility is a printing and pagination filter. If multiple input files are specified, each shall be read, formatted, and written to standard output. By default, the input shall be separated into 66-line pages, each with:

*
A 5-line header that includes the page number, date, time, and the pathname of the file

*
A 5-line trailer consisting of blank lines

If standard output is associated with a terminal, diagnostic messages shall be deferred until the pr utility has completed processing.

When options specifying multi-column output are specified, output text columns shall be of equal width; input lines that do not fit into a text column shall be truncated. By default, text columns shall be separated with at least one <blank>.

OPTIONS

The pr utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that: the page option has a '+' delimiter; page and column can be multi-digit numbers; some of the option-arguments are optional; and some of the option-arguments cannot be specified as separate arguments from the preceding option letter. In particular, the -s option does not allow the option letter to be separated from its argument, and the options -e, -i, and -n require that both arguments, if present, not be separated from the option letter.

The following options shall be supported. In the following option descriptions, column, lines, offset, page, and width are positive decimal integers; gap is a non-negative decimal integer.

+page
Begin output at page number page of the formatted input.
-column
Produce multi-column output that is arranged in column columns (the default shall be 1) and is written down each column in the order in which the text is received from the input file. This option should not be used with -m. The options -e and -i shall be assumed for multiple text-column output. Whether or not text columns are produced with identical vertical lengths is unspecified, but a text column shall never exceed the length of the page (see the -l option). When used with -t, use the minimum number of lines to write the output.
-a
Modify the effect of the - column option so that the columns are filled across the page in a round-robin order (for example, when column is 2, the first input line heads column 1, the second heads column 2, the third is the second line in column 1, and so on).
-d
Produce output that is double-spaced; append an extra <newline> following every <newline> found in the input.
-e[char][gap]

Expand each input <tab> to the next greater column position specified by the formula n* gap+1, where n is an integer > 0. If gap is zero or is omitted, it shall default to 8. All <tab>s in the input shall be expanded into the appropriate number of <space>s. If any non-digit character, char, is specified, it shall be used as the input <tab>.

-f
Use a <form-feed> for new pages, instead of the default behavior that uses a sequence of <newline>s. Pause before beginning the first page if the standard output is associated with a terminal.
-F
Use a <form-feed> for new pages, instead of the default behavior that uses a sequence of <newline>s.
-h header
Use the string header to replace the contents of the file operand in the page header.
-i[char][gap]
In output, replace multiple <space>s with <tab>s wherever two or more adjacent <space>s reach column positions gap+1, 2* gap+1, 3* gap+1, and so on. If gap is zero or is omitted, default tab settings at every eighth column position shall be assumed. If any non-digit character, char, is specified, it shall be used as the output <tab>.
-l lines
Override the 66-line default and reset the page length to lines. If lines is not greater than the sum of both the header and trailer depths (in lines), the pr utility shall suppress both the header and trailer, as if the -t option were in effect.
-m
Merge files. Standard output shall be formatted so the pr utility writes one line from each file specified by a file operand, side by side into text columns of equal fixed widths, in terms of the number of column positions. Implementations shall support merging of at least nine file operands.
-n[char][width]

Provide width-digit line numbering (default for width shall be 5). The number shall occupy the first width column positions of each text column of default output or each line of -m output. If char (any non-digit character) is given, it shall be appended to the line number to separate it from whatever follows (default for char is a <tab>).

-o offset
Each line of output shall be preceded by offset <space>s. If the -o option is not specified, the default offset shall be zero. The space taken is in addition to the output line width (see the -w option below).
-p
Pause before beginning each page if the standard output is directed to a terminal ( pr shall write an <alert> to standard error and wait for a <carriage-return> to be read on /dev/tty).
-r
Write no diagnostic reports on failure to open files.
-s[char]
Separate text columns by the single character char instead of by the appropriate number of <space>s (default for char shall be <tab>).
-t
Write neither the five-line identifying header nor the five-line trailer usually supplied for each page. Quit writing after the last line of each file without spacing to the end of the page.
-w width
Set the width of the line to width column positions for multiple text-column output only. If the -w option is not specified and the -s option is not specified, the default width shall be 72. If the -w option is not specified and the -s option is specified, the default width shall be 512.

For single column output, input lines shall not be truncated.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be written. If no file operands are specified, or if a file operand is '-' , the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' . See the INPUT FILES section.

INPUT FILES

The input files shall be text files.

The file /dev/tty shall be used to read responses required by the -p option.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of pr:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and which characters are defined as printable (character class print). Non-printable characters are still written to standard output, but are not counted for the purpose for column-width and line-length calculations.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_TIME
Determine the format of the date and time for use in writing header lines.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone used to calculate date and time strings written in header lines. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

If pr receives an interrupt while writing to a terminal, it shall flush all accumulated error messages to the screen before terminating.

STDOUT

The pr utility output shall be a paginated version of the original file (or files). This pagination shall be accomplished using either <form-feed>s or a sequence of <newline>s, as controlled by the -F or -f option. Page headers shall be generated unless the -t option is specified. The page headers shall be of the form:

"\n\n%s %s Page %d\n\n\n", <output of date>, <file>, <page number>

In the POSIX locale, the <output of date> field, representing the date and time of last modification of the input file (or the current date and time if the input file is standard input), shall be equivalent to the output of the following command as it would appear if executed at the given time:

date "+%b %e %H:%M %Y"

without the trailing <newline>, if the page being written is from standard input. If the page being written is not from standard input, in the POSIX locale, the same format shall be used, but the time used shall be the modification time of the file corresponding to file instead of the current time. When the LC_TIME locale category is not set to the POSIX locale, a different format and order of presentation of this field may be used.

If the standard input is used instead of a file operand, the <file> field shall be replaced by a null string.

If the -h option is specified, the <file> field shall be replaced by the header argument.

STDERR

The standard error shall be used for diagnostic messages and for alerting the terminal when -p is specified.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

1.
Print a numbered list of all files in the current directory:

ls -a | pr -n -h "Files in $(pwd)."

2.
Print file1 and file2 as a double-spaced, three-column listing headed by "file list'':

pr -3d -h "file list" file1 file2

3.
Write file1 on file2, expanding tabs to columns 10, 19, 28, ...:

pr -e9 -t <file1 >file2

RATIONALE

This utility is one of those that does not follow the Utility Syntax Guidelines because of its historical origins. The standard developers could have added new options that obeyed the guidelines (and marked the old options obsolescent) or devised an entirely new utility; there are examples of both actions in this volume of IEEE Std 1003.1-2001. Because of its widespread use by historical applications, the standard developers decided to exempt this version of pr from many of the guidelines.

Implementations are required to accept option-arguments to the -h, -l, -o, and -w options whether presented as part of the same argument or as a separate argument to pr, as suggested by the Utility Syntax Guidelines. The -n and -s options, however, are specified as in historical practice because they are frequently specified without their optional arguments. If a <blank> were allowed before the option-argument in these cases, a file operand could mistakenly be interpreted as an option-argument in historical applications.

The text about the minimum number of lines in multi-column output was included to ensure that a best effort is made in balancing the length of the columns. There are known historical implementations in which, for example, 60-line files are listed by pr -2 as one column of 56 lines and a second of 4. Although this is not a problem when a full page with headers and trailers is produced, it would be relatively useless when used with -t.

Historical implementations of the pr utility have differed in the action taken for the -f option. BSD uses it as described here for the -F option; System V uses it to change trailing <newline>s on each page to a <form-feed> and, if standard output is a TTY device, sends an <alert> to standard error and reads a line from /dev/tty before the first page. There were strong arguments from both sides of this issue concerning historical practice and as a result the -F option was added. XSI-conformant systems support the System V historical actions for the -f option.

The <output of date> field in the -l format is specified only for the POSIX locale. As noted, the format can be different in other locales. No mechanism for defining this is present in this volume of IEEE Std 1003.1-2001, as the appropriate vehicle is a message catalog; that is, the format should be specified as a "message".

FUTURE DIRECTIONS

None.

SEE ALSO

expand , lp

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ps(1p)

PS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ps - report process status

SYNOPSIS

ps [-aA][-defl][-G grouplist][-o format]...[-p proclist][-t termlist]

[-U userlist][-g grouplist][-n namelist][-u userlist]

DESCRIPTION

The ps utility shall write information about processes, subject to having the appropriate privileges to obtain information about those processes.

By default, ps shall select all processes with the same effective user ID as the current user and the same controlling terminal as the invoker.

OPTIONS

The ps utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Write information for all processes associated with terminals. Implementations may omit session leaders from this list.
-A
Write information for all processes.
-d
Write information for all processes, except session leaders.
-e
Write information for all processes. (Equivalent to -A.)
-f
Generate a full listing. (See the STDOUT section for the contents of a full listing.)
-g grouplist
Write information for processes whose session leaders are given in grouplist. The application shall ensure that the grouplist is a single argument in the form of a <blank> or comma-separated list.
-G grouplist
Write information for processes whose real group ID numbers are given in grouplist. The application shall ensure that the grouplist is a single argument in the form of a <blank> or comma-separated list.
-l
Generate a long listing. (See STDOUT for the contents of a long listing.)
-n namelist
Specify the name of an alternative system namelist file in place of the default. The name of the default file and the format of a namelist file are unspecified.
-o format
Write information according to the format specification given in format. This is fully described in the STDOUT section. Multiple -o options can be specified; the format specification shall be interpreted as the <space>-separated concatenation of all the format option-arguments.
-p proclist
Write information for processes whose process ID numbers are given in proclist. The application shall ensure that the proclist is a single argument in the form of a <blank> or comma-separated list.
-t termlist
Write information for processes associated with terminals given in termlist. The application shall ensure that the termlist is a single argument in the form of a <blank> or comma-separated list. Terminal identifiers shall be given in an implementation-defined format. On XSI-conformant systems, they shall be given in one of two forms: the device's filename (for example, tty04) or, if the device's filename starts with tty, just the identifier following the characters tty (for example, "04" ).
-u userlist
Write information for processes whose user ID numbers or login names are given in userlist. The application shall ensure that the userlist is a single argument in the form of a <blank> or comma-separated list. In the listing, the numerical user ID shall be written unless the -f option is used, in which case the login name shall be written.
-U userlist
Write information for processes whose real user ID numbers or login names are given in userlist. The application shall ensure that the userlist is a single argument in the form of a <blank> or comma-separated list.

With the exception of -o format, all of the options shown are used to select processes. If any are specified, the default list shall be ignored and ps shall select the processes represented by the inclusive OR of all the selection-criteria options.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ps:

COLUMNS
Override the system-selected horizontal display line size, used to determine the number of text columns to display. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables for valid values and results when it is unset or null.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
LC_TIME
Determine the format and contents of the date and time strings displayed.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone used to calculate date and time strings displayed. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

When the -o option is not specified, the standard output format is unspecified.

On XSI-conformant systems, the output format shall be as follows. The column headings and descriptions of the columns in a ps listing are given below. The precise meanings of these fields are implementation-defined. The letters 'f' and 'l' (below) indicate the option ( full or long) that shall cause the corresponding heading to appear; all means that the heading always appears. Note that these two options determine only what information is provided for a process; they do not determine which processes are listed.
F | (l) | Flags (octal and additive) associated with the process.
S | (l) | The state of the process.
UID | (f,l) | The user ID number of the process owner; the login name is printed under the -f option.
PID | (all) | The process ID of the process; it is possible to kill a process if this datum is known.
PPID | (f,l) | The process ID of the parent process.
C | (f,l) | Processor utilization for scheduling.
PRI | (l) | The priority of the process; higher numbers mean lower priority.
NI | (l) | Nice value; used in priority computation.
ADDR | (l) | The address of the process.
SZ | (l) | The size in blocks of the core image of the process.
WCHAN | (l) | The event for which the process is waiting or sleeping; if blank, the process is running.
STIME | (f) | Starting time of the process.
TTY | (all) | The controlling terminal for the process.
TIME | (all) | The cumulative execution time for the process.
CMD | (all) | The command name; the full command name and its arguments are written under the -f option.

A process that has exited and has a parent, but has not yet been waited for by the parent, shall be marked defunct.

Under the option -f, ps tries to determine the command name and arguments given when the process was created by examining memory or the swap area. Failing this, the command name, as it would appear without the option -f, is written in square brackets.

The -o option allows the output format to be specified under user control.

The application shall ensure that the format specification is a list of names presented as a single argument, <blank> or comma-separated. Each variable has a default header. The default header can be overridden by appending an equals sign and the new text of the header. The rest of the characters in the argument shall be used as the header text. The fields specified shall be written in the order specified on the command line, and should be arranged in columns in the output. The field widths shall be selected by the system to be at least as wide as the header text (default or overridden value). If the header text is null, such as -o user=, the field width shall be at least as wide as the default header text. If all header text fields are null, no header line shall be written.

The following names are recognized in the POSIX locale:

ruser
The real user ID of the process. This shall be the textual user ID, if it can be obtained and the field width permits, or a decimal representation otherwise.
user
The effective user ID of the process. This shall be the textual user ID, if it can be obtained and the field width permits, or a decimal representation otherwise.
rgroup
The real group ID of the process. This shall be the textual group ID, if it can be obtained and the field width permits, or a decimal representation otherwise.
group
The effective group ID of the process. This shall be the textual group ID, if it can be obtained and the field width permits, or a decimal representation otherwise.
pid
The decimal value of the process ID.
ppid
The decimal value of the parent process ID.
pgid
The decimal value of the process group ID.
pcpu
The ratio of CPU time used recently to CPU time available in the same period, expressed as a percentage. The meaning of "recently" in this context is unspecified. The CPU time available is determined in an unspecified manner.
vsz
The size of the process in (virtual) memory in 1024 byte units as a decimal integer.
nice
The decimal value of the nice value of the process; see nice() .
etime
In the POSIX locale, the elapsed time since the process was started, in the form:

[[dd-]hh:]mm:ss

where dd shall represent the number of days, hh the number of hours, mm the number of minutes, and ss the number of seconds. The dd field shall be a decimal integer. The hh, mm, and ss fields shall be two-digit decimal integers padded on the left with zeros.

time
In the POSIX locale, the cumulative CPU time of the process in the form:

[dd-]hh:mm:ss

The dd, hh, mm, and ss fields shall be as described in the etime specifier.

tty
The name of the controlling terminal of the process (if any) in the same format used by the who utility.
comm
The name of the command being executed ( argv[0] value) as a string.
args
The command with all its arguments as a string. The implementation may truncate this value to the field width; it is implementation-defined whether any further truncation occurs. It is unspecified whether the string represented is a version of the argument list as it was passed to the command when it started, or is a version of the arguments as they may have been modified by the application. Applications cannot depend on being able to modify their argument list and having that modification be reflected in the output of ps.

Any field need not be meaningful in all implementations. In such a case a hyphen ( '-' ) should be output in place of the field value.

Only comm and args shall be allowed to contain <blank>s; all others shall not. Any implementation-defined variables shall be specified in the system documentation along with the default header and indicating whether the field may contain <blank>s.

The following table specifies the default header to be used in the POSIX locale corresponding to each format specifier.

Table: Variable Names and Default Headers in ps
Format Specifier | Default Header | Format Specifier | Default Header
args | COMMAND | ppid | PPID
comm | COMMAND | rgroup | RGROUP
etime | ELAPSED | ruser | RUSER
group | GROUP | time | TIME
nice | NI | tty | TT
pcpu | %CPU | user | USER
pgid | PGID | vsz | VSZ
pid | PID |  |

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Things can change while ps is running; the snapshot it gives is only true for an instant, and might not be accurate by the time it is displayed.

The args format specifier is allowed to produce a truncated version of the command arguments. In some implementations, this information is no longer available when the ps utility is executed.

If the field width is too narrow to display a textual ID, the system may use a numeric version. Normally, the system would be expected to choose large enough field widths, but if a large number of fields were selected to write, it might squeeze fields to their minimum sizes to fit on one line. One way to ensure adequate width for the textual IDs is to override the default header for a field to make it larger than most or all user or group names.

There is no special quoting mechanism for header text. The header text is the rest of the argument. If multiple header changes are needed, multiple -o options can be used, such as:

ps -o "user=User Name" -o pid=Process\ ID

On some implementations, especially multi-level secure systems, ps may be severely restricted and produce information only about child processes owned by the user.

EXAMPLES

The command:

ps -o user,pid,ppid=MOM -o args

writes at least the following in the POSIX locale:

 USER   PID   MOM   COMMAND
helene    34    12   ps -o uid,pid,ppid=MOM -o args

The contents of the COMMAND field need not be the same in all implementations, due to possible truncation.

RATIONALE

There is very little commonality between BSD and System V implementations of ps. Many options conflict or have subtly different usages. The standard developers attempted to select a set of options for the base standard that were useful on a wide range of systems and selected options that either can be implemented on both BSD and System V-based systems without breaking the current implementations or where the options are sufficiently similar that any changes would not be unduly problematic for users or implementors.

It is recognized that on some implementations, especially multi-level secure systems, ps may be nearly useless. The default output has therefore been chosen such that it does not break historical implementations and also is likely to provide at least some useful information on most systems.

The major change is the addition of the format specification capability. The motivation for this invention is to provide a mechanism for users to access a wider range of system information, if the system permits it, in a portable manner. The fields chosen to appear in this volume of IEEE Std 1003.1-2001 were arrived at after considering what concepts were likely to be both reasonably useful to the "average" user and had a reasonable chance of being implemented on a wide range of systems. Again it is recognized that not all systems are able to provide all the information and, conversely, some may wish to provide more. It is hoped that the approach adopted will be sufficiently flexible and extensible to accommodate most systems. Implementations may be expected to introduce new format specifiers.

The default output should consist of a short listing containing the process ID, terminal name, cumulative execution time, and command name of each process.

The preference of the standard developers would have been to make the format specification an operand of the ps command. Unfortunately, BSD usage precluded this.

At one time a format was included to display the environment array of the process. This was deleted because there is no portable way to display it.

The -A option is equivalent to the BSD -g and the SVID -e. Because the two systems differed, a mnemonic compromise was selected.

The -a option is described with some optional behavior because the SVID omits session leaders, but BSD does not.

In an early proposal, format specifiers appeared for priority and start time. The former was not defined adequately in this volume of IEEE Std 1003.1-2001 and was removed in deference to the defined nice value; the latter because elapsed time was considered to be more useful.

In a new BSD version of ps, a -O option can be used to write all of the default information, followed by additional format specifiers. This was not adopted because the default output is implementation-defined. Nevertheless, this is a useful option that should be reserved for that purpose. In the -o option for the POSIX Shell and Utilities ps, the format is the concatenation of each -o. Therefore, the user can have an alias or function that defines the beginning of their desired format and add more fields to the end of the output in certain cases where that would be useful.

The format of the terminal name is unspecified, but the descriptions of ps, talk, who, and write require that they all use the same format.

The pcpu field indicates that the CPU time available is determined in an unspecified manner. This is because it is difficult to express an algorithm that is useful across all possible machine architectures. Historical counterparts to this value have attempted to show percentage of use in the recent past, such as the preceding minute. Frequently, these values for all processes did not add up to 100%. Implementations are encouraged to provide data in this field to users that will help them identify processes currently affecting the performance of the system.

FUTURE DIRECTIONS

None.

SEE ALSO

kill() , nice() , renice

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


rm(1p)

RM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rm - remove directory entries

SYNOPSIS

rm [-fiRr] file...

DESCRIPTION

The rm utility shall remove the directory entry specified by each file argument.

If either of the files dot or dot-dot are specified as the basename portion of an operand (that is, the final pathname component), rm shall write a diagnostic message to standard error and do nothing more with such operands.

For each file the following steps shall be taken:

1.
If the file does not exist:
a.
If the -f option is not specified, rm shall write a diagnostic message to standard error.

b.
Go on to any remaining files.

2.
If file is of type directory, the following steps shall be taken:
a.
If neither the -R option nor the -r option is specified, rm shall write a diagnostic message to standard error, do nothing more with file, and go on to any remaining files.

b.
If the -f option is not specified, and either the permissions of file do not permit writing and the standard input is a terminal or the -i option is specified, rm shall write a prompt to standard error and read a line from the standard input. If the response is not affirmative, rm shall do nothing more with the current file and go on to any remaining files.

c.
For each entry contained in file, other than dot or dot-dot, the four steps listed here (1 to 4) shall be taken with the entry as if it were a file operand. The rm utility shall not traverse directories by following symbolic links into other parts of the hierarchy, but shall remove the links themselves.

d.
If the -i option is specified, rm shall write a prompt to standard error and read a line from the standard input. If the response is not affirmative, rm shall do nothing more with the current file, and go on to any remaining files.

3.
If file is not of type directory, the -f option is not specified, and either the permissions of file do not permit writing and the standard input is a terminal or the -i option is specified, rm shall write a prompt to the standard error and read a line from the standard input. If the response is not affirmative, rm shall do nothing more with the current file and go on to any remaining files.

4.
If the current file is a directory, rm shall perform actions equivalent to the rmdir() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 called with a pathname of the current file used as the path argument. If the current file is not a directory, rm shall perform actions equivalent to the unlink() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 called with a pathname of the current file used as the path argument.

If this fails for any reason, rm shall write a diagnostic message to standard error, do nothing more with the current file, and go on to any remaining files.

The rm utility shall be able to descend to arbitrary depths in a file hierarchy, and shall not fail due to path length limitations (unless an operand specified by the user exceeds system limitations).

OPTIONS

The rm utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-f
Do not prompt for confirmation. Do not write diagnostic messages or modify the exit status in the case of nonexistent operands. Any previous occurrences of the -i option shall be ignored.
-i
Prompt for confirmation as described previously. Any previous occurrences of the -f option shall be ignored.
-R
Remove file hierarchies. See the DESCRIPTION.
-r
Equivalent to -R.

OPERANDS

The following operand shall be supported:

file
A pathname of a directory entry to be removed.

STDIN

The standard input shall be used to read an input line in response to each prompt specified in the STDOUT section. Otherwise, the standard input shall not be used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of rm:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments) and the behavior of character classes within regular expressions used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.
LC_MESSAGES
Determine the locale for the processing of affirmative responses that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

Prompts shall be written to standard error under the conditions specified in the DESCRIPTION and OPTIONS sections. The prompts shall contain the file pathname, but their format is otherwise unspecified. The standard error also shall be used for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All of the named directory entries for which rm performed actions equivalent to the rmdir() or unlink() functions were removed.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The rm utility is forbidden to remove the names dot and dot-dot in order to avoid the consequences of inadvertently doing something like:

rm -r .*

Some implementations do not permit the removal of the last link to an executable binary file that is being executed; see the [EBUSY] error in the unlink() function defined in the System Interfaces volume of IEEE Std 1003.1-2001. Thus, the rm utility can fail to remove such files.

The -i option causes rm to prompt and read the standard input even if the standard input is not a terminal, but in the absence of -i the mode prompting is not done when the standard input is not a terminal.

EXAMPLES

1.
The following command:

rm a.out core

removes the directory entries: a.out and core.

2.
The following command:

rm -Rf junk

removes the directory junk and all its contents, without prompting.

RATIONALE

For absolute clarity, paragraphs (2b) and (3) in the DESCRIPTION of rm describing the behavior when prompting for confirmation, should be interpreted in the following manner:

if ((NOT f_option) AND
    ((not_writable AND input_is_terminal) OR i_option))

The exact format of the interactive prompts is unspecified. Only the general nature of the contents of prompts are specified because implementations may desire more descriptive prompts than those used on historical implementations. Therefore, an application not using the -f option, or using the -i option, relies on the system to provide the most suitable dialog directly with the user, based on the behavior specified.

The -r option is historical practice on all known systems. The synonym -R option is provided for consistency with the other utilities in this volume of IEEE Std 1003.1-2001 that provide options requesting recursive descent through the file hierarchy.

The behavior of the -f option in historical versions of rm is inconsistent. In general, along with "forcing" the unlink without prompting for permission, it always causes diagnostic messages to be suppressed and the exit status to be unmodified for nonexistent operands and files that cannot be unlinked. In some versions, however, the -f option suppresses usage messages and system errors as well. Suppressing such messages is not a service to either shell scripts or users.

It is less clear that error messages regarding files that cannot be unlinked (removed) should be suppressed. Although this is historical practice, this volume of IEEE Std 1003.1-2001 does not permit the -f option to suppress such messages.

When given the -r and -i options, historical versions of rm prompt the user twice for each directory, once before removing its contents and once before actually attempting to delete the directory entry that names it. This allows the user to "prune" the file hierarchy walk. Historical versions of rm were inconsistent in that some did not do the former prompt for directories named on the command line and others had obscure prompting behavior when the -i option was specified and the permissions of the file did not permit writing. The POSIX Shell and Utilities rm differs little from historic practice, but does require that prompts be consistent. Historical versions of rm were also inconsistent in that prompts were done to both standard output and standard error. This volume of IEEE Std 1003.1-2001 requires that prompts be done to standard error, for consistency with cp and mv, and to allow historical extensions to rm that provide an option to list deleted files on standard output.

The rm utility is required to descend to arbitrary depths so that any file hierarchy may be deleted. This means, for example, that the rm utility cannot run out of file descriptors during its descent (that is, if the number of file descriptors is limited, rm cannot be implemented in the historical fashion where one file descriptor is used per directory level). Also, rm is not permitted to fail because of path length restrictions, unless an operand specified by the user is longer than {PATH_MAX}.

The rm utility removes symbolic links themselves, not the files they refer to, as a consequence of the dependence on the unlink() functionality, per the DESCRIPTION. When removing hierarchies with -r or -R, the prohibition on following symbolic links has to be made explicit.

FUTURE DIRECTIONS

None.

SEE ALSO

rmdir() , the System Interfaces volume of IEEE Std 1003.1-2001, remove(), rmdir(), unlink()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sh(1p)

SH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sh - shell, the standard command language interpreter

SYNOPSIS

sh [-abCefhimnuvx][-o option][+abCefhimnuvx][+o option]
[command_file [argument...]]

sh -c[-abCefhimnuvx][-o option][+abCefhimnuvx][+o option]command_string
[command_name [argument...]]

sh -s[-abCefhimnuvx][-o option][+abCefhimnuvx][+o option][argument]

DESCRIPTION

The sh utility is a command language interpreter that shall execute commands read from a command line string, the standard input, or a specified file. The application shall ensure that the commands to be executed are expressed in the language described in Shell Command Language .

Pathname expansion shall not fail due to the size of a file.

Shell input and output redirections have an implementation-defined offset maximum that is established in the open file description.

OPTIONS

The sh utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, with an extension for support of a leading plus sign ( '+' ) as noted below.

The -a, -b, -C, -e, -f, -m, -n, -o option, -u, -v, and -x options are described as part of the set utility in Special Built-In Utilities . The option letters derived from the set special built-in shall also be accepted with a leading plus sign ( '+' ) instead of a leading hyphen (meaning the reverse case of the option as described in this volume of IEEE Std 1003.1-2001).

The following additional options shall be supported:

-c
Read commands from the command_string operand. Set the value of special parameter 0 (see Special Parameters ) from the value of the command_name operand and the positional parameters ($1, $2, and so on) in sequence from the remaining argument operands. No commands shall be read from the standard input.
-i
Specify that the shell is interactive; see below. An implementation may treat specifying the -i option as an error if the real user ID of the calling process does not equal the effective user ID or if the real group ID does not equal the effective group ID.
-s
Read commands from the standard input.

If there are no operands and the -c option is not specified, the -s option shall be assumed.

If the -i option is present, or if there are no operands and the shell's standard input and standard error are attached to a terminal, the shell is considered to be interactive.

OPERANDS

The following operands shall be supported:

-
A single hyphen shall be treated as the first operand and then ignored. If both '-' and "--" are given as arguments, or if other operands precede the single hyphen, the results are undefined.
argument
The positional parameters ($1, $2, and so on) shall be set to arguments, if any.
command_file
The pathname of a file containing commands. If the pathname contains one or more slash characters, the implementation attempts to read that file; the file need not be executable. If the pathname does not contain a slash character:
*
The implementation shall attempt to read that file from the current working directory; the file need not be executable.

*
If the file is not in the current working directory, the implementation may perform a search for an executable file using the value of PATH , as described in Command Search and Execution .

Special parameter 0 (see Special Parameters ) shall be set to the value of command_file. If sh is called using a synopsis form that omits command_file, special parameter 0 shall be set to the value of the first argument passed to sh from its parent (for example, argv[0] for a C program), which is normally a pathname used to execute the sh utility.

command_name

A string assigned to special parameter 0 when executing the commands in command_string. If command_name is not specified, special parameter 0 shall be set to the value of the first argument passed to sh from its parent (for example, argv[0] for a C program), which is normally a pathname used to execute the sh utility.

command_string

A string that shall be interpreted by the shell as one or more commands, as if the string were the argument to the system() function defined in the System Interfaces volume of IEEE Std 1003.1-2001. If the command_string operand is an empty string, sh shall exit with a zero exit status.

STDIN

The standard input shall be used only if one of the following is true:

*
The -s option is specified.

*
The -c option is not specified and no operands are specified.

*
The script executes one or more commands that require input from standard input (such as a read command that does not redirect its input).

See the INPUT FILES section.

When the shell is using standard input and it invokes a command that also uses standard input, the shell shall ensure that the standard input file pointer points directly after the command it has read when the command begins execution. It shall not read ahead in such a manner that any characters intended to be read by the invoked command are consumed by the shell (whether interpreted by the shell or not) or that characters that are not read by the invoked command are not seen by the shell. When the command expecting to read standard input is started asynchronously by an interactive shell, it is unspecified whether characters are read by the command or interpreted by the shell.

If the standard input to sh is a FIFO or terminal device and is set to non-blocking reads, then sh shall enable blocking reads on standard input. This shall remain in effect when the command completes.

INPUT FILES

The input file shall be a text file, except that line lengths shall be unlimited. If the input file is empty or consists solely of blank lines or comments, or both, sh shall exit with a zero exit status.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of sh:

ENV
This variable, when and only when an interactive shell is invoked, shall be subjected to parameter expansion (see Parameter Expansion ) by the shell, and the resulting value shall be used as a pathname of a file containing shell commands to execute in the current environment. The file need not be executable. If the expanded value of ENV is not an absolute pathname, the results are unspecified. ENV shall be ignored if the real and effective user IDs or real and effective group IDs of the process are different.
FCEDIT
This variable, when expanded by the shell, shall determine the default value for the -e editor option's editor option-argument. If FCEDIT is null or unset, ed shall be used as the editor. This volume of IEEE Std 1003.1-2001 specifies the effects of this variable only for systems supporting the User Portability Utilities option.
HISTFILE
Determine a pathname naming a command history file. If the HISTFILE variable is not set, the shell may attempt to access or create a file .sh_history in the directory referred to by the HOME environment variable. If the shell cannot obtain both read and write access to, or create, the history file, it shall use an unspecified mechanism that allows the history to operate properly. (References to history "file" in this section shall be understood to mean this unspecified mechanism in such cases.) An implementation may choose to access this variable only when initializing the history file; this initialization shall occur when fc or sh first attempt to retrieve entries from, or add entries to, the file, as the result of commands issued by the user, the file named by the ENV variable, or implementation-defined system start-up files. Implementations may choose to disable the history list mechanism for users with appropriate privileges who do not set HISTFILE ; the specific circumstances under which this occurs are implementation-defined. If more than one instance of the shell is using the same history file, it is unspecified how updates to the history file from those shells interact. As entries are deleted from the history file, they shall be deleted oldest first. It is unspecified when history file entries are physically removed from the history file. This volume of IEEE Std 1003.1-2001 specifies the effects of this variable only for systems supporting the User Portability Utilities option.
HISTSIZE
Determine a decimal number representing the limit to the number of previous commands that are accessible. If this variable is unset, an unspecified default greater than or equal to 128 shall be used. The maximum number of commands in the history list is unspecified, but shall be at least 128. An implementation may choose to access this variable only when initializing the history file, as described under HISTFILE . Therefore, it is unspecified whether changes made to HISTSIZE after the history file has been initialized are effective.
HOME
Determine the pathname of the user's home directory. The contents of HOME are used in tilde expansion as described in Tilde Expansion . This volume of IEEE Std 1003.1-2001 specifies the effects of this variable only for systems supporting the User Portability Utilities option.
IFS
(Input Field Separators.) A string treated as a list of characters that shall be used for field splitting and to split lines into words with the read command. See Field Splitting . If IFS is not set, the shell shall behave as if the value of IFS were <space>, <tab>, and <newline>. Implementations may ignore the value of IFS in the environment at the time sh is invoked, treating IFS as if it were not set.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the behavior of range expressions, equivalence classes, and multi-character collating elements within pattern matching.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), which characters are defined as letters (character class alpha), and the behavior of character classes within pattern matching.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
MAIL
Determine a pathname of the user's mailbox file for purposes of incoming mail notification. If this variable is set, the shell shall inform the user if the file named by the variable is created or if its modification time has changed. Informing the user shall be accomplished by writing a string of unspecified format to standard error prior to the writing of the next primary prompt string. Such check shall be performed only after the completion of the interval defined by the MAILCHECK variable after the last such check. The user shall be informed only if MAIL is set and MAILPATH is not set. This volume of IEEE Std 1003.1-2001 specifies the effects of this variable only for systems supporting the User Portability Utilities option.
MAILCHECK

Establish a decimal integer value that specifies how often (in seconds) the shell shall check for the arrival of mail in the files specified by the MAILPATH or MAIL variables. The default value shall be 600 seconds. If set to zero, the shell shall check before issuing each primary prompt. This volume of IEEE Std 1003.1-2001 specifies the effects of this variable only for systems supporting the User Portability Utilities option.

MAILPATH
Provide a list of pathnames and optional messages separated by colons. If this variable is set, the shell shall inform the user if any of the files named by the variable are created or if any of their modification times change. (See the preceding entry for MAIL for descriptions of mail arrival and user informing.) Each pathname can be followed by '%' and a string that shall be subjected to parameter expansion and written to standard error when the modification time changes. If a '%' character in the pathname is preceded by a backslash, it shall be treated as a literal '%' in the pathname. The default message is unspecified.

The MAILPATH environment variable takes precedence over the MAIL variable. This volume of IEEE Std 1003.1-2001 specifies the effects of this variable only for systems supporting the User Portability Utilities option.

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Establish a string formatted as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables, used to effect command interpretation; see Command Search and Execution .
PWD
This variable shall represent an absolute pathname of the current working directory. Assignments to this variable may be ignored unless the value is an absolute pathname of the current working directory and there are no filename components of dot or dot-dot.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the STDERR section.

STDERR

Except as otherwise stated (by the descriptions of any invoked utilities or in interactive mode), standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

See Shell Command Language . The following additional capabilities are supported on systems supporting the User Portability Utilities option.

Command History List

When the sh utility is being used interactively, it shall maintain a list of commands previously entered from the terminal in the file named by the HISTFILE environment variable. The type, size, and internal format of this file are unspecified. Multiple sh processes can share access to the file for a user, if file access permissions allow this; see the description of the HISTFILE environment variable.

Command Line Editing

When sh is being used interactively from a terminal, the current command and the command history (see fc ) can be edited using vi-mode command line editing. This mode uses commands, described below, similar to a subset of those described in the vi utility. Implementations may offer other command line editing modes corresponding to other editing utilities.

The command set -o vi shall enable vi-mode editing and place sh into vi insert mode (see Command Line Editing (vi-mode) ). This command also shall disable any other editing mode that the implementation may provide. The command set +o vi disables vi-mode editing.

Certain block-mode terminals may be unable to support shell command line editing. If a terminal is unable to provide either edit mode, it need not be possible to set -o vi when using the shell on this terminal.

In the following sections, the characters erase, interrupt, kill, and end-of-file are those set by the stty utility.

Command Line Editing (vi-mode)

In vi editing mode, there shall be a distinguished line, the edit line. All the editing operations which modify a line affect the edit line. The edit line is always the newest line in the command history buffer.

With vi-mode enabled, sh can be switched between insert mode and command mode.

When in insert mode, an entered character shall be inserted into the command line, except as noted in vi Line Editing Insert Mode . Upon entering sh and after termination of the previous command, sh shall be in insert mode.

Typing an escape character shall switch sh into command mode (see vi Line Editing Command Mode ). In command mode, an entered character shall either invoke a defined operation, be used as part of a multi-character operation, or be treated as an error. A character that is not recognized as part of an editing command shall terminate any specific editing command and shall alert the terminal. Typing the interrupt character in command mode shall cause sh to terminate command line editing on the current command line, reissue the prompt on the next line of the terminal, and reset the command history (see fc ) so that the most recently executed command is the previous command (that is, the command that was being edited when it was interrupted is not reentered into the history).

In the following sections, the phrase "move the cursor to the beginning of the word" shall mean "move the cursor to the first character of the current word" and the phrase "move the cursor to the end of the word" shall mean "move the cursor to the last character of the current word". The phrase "beginning of the command line" indicates the point between the end of the prompt string issued by the shell (or the beginning of the terminal line, if there is no prompt string) and the first character of the command text.

vi Line Editing Insert Mode

While in insert mode, any character typed shall be inserted in the current command line, unless it is from the following set.

<newline>
Execute the current command line. If the current command line is not empty, this line shall be entered into the command history (see fc ).
erase
Delete the character previous to the current cursor position and move the current cursor position back one character. In insert mode, characters shall be erased from both the screen and the buffer when backspacing.
interrupt
Terminate command line editing with the same effects as described for interrupting command mode; see Command Line Editing (vi-mode) .
kill
Clear all the characters from the input line.
<control>-V
Insert the next character input, even if the character is otherwise a special insert mode character.
<control>-W
Delete the characters from the one preceding the cursor to the preceding word boundary. The word boundary in this case is the closer to the cursor of either the beginning of the line or a character that is in neither the blank nor punct character classification of the current locale.
end-of-file
Interpreted as the end of input in sh. This interpretation shall occur only at the beginning of an input line. If end-of-file is entered other than at the beginning of the line, the results are unspecified.
<ESC>
Place sh into command mode.

vi Line Editing Command Mode

In command mode for the command line editing feature, decimal digits not beginning with 0 that precede a command letter shall be remembered. Some commands use these decimal digits as a count number that affects the operation.

The term motion command represents one of the commands:

<space>  0  b  F  l  W  ^  $  ;  E  f  T  w  |  ,  B  e  h  t

If the current line is not the edit line, any command that modifies the current line shall cause the content of the current line to replace the content of the edit line, and the current line shall become the edit line. This replacement cannot be undone (see the u and U commands below). The modification requested shall then be performed to the edit line. When the current line is the edit line, the modification shall be done directly to the edit line.

Any command that is preceded by count shall take a count (the numeric value of any preceding decimal digits). Unless otherwise noted, this count shall cause the specified operation to repeat by the number of times specified by the count. Also unless otherwise noted, a count that is out of range is considered an error condition and shall alert the terminal, but neither the cursor position, nor the command line, shall change.

The terms word and bigword are used as defined in the vi description. The term save buffer corresponds to the term unnamed buffer in vi.

The following commands shall be recognized in command mode:

<newline>
Execute the current command line. If the current command line is not empty, this line shall be entered into the command history (see fc ).
<control>-L
Redraw the current command line. Position the cursor at the same location on the redrawn line.
#
Insert the character '#' at the beginning of the current command line and treat the resulting edit line as a comment. This line shall be entered into the command history; see fc .
=
Display the possible shell word expansions (see Word Expansions ) of the bigword at the current command line position.
Note:
This does not modify the content of the current line, and therefore does not cause the current line to become the edit line.

These expansions shall be displayed on subsequent terminal lines. If the bigword contains none of the characters '?' , '*' , or '[' , an asterisk ( '*' ) shall be implicitly assumed at the end. If any directories are matched, these expansions shall have a '/' character appended. After the expansion, the line shall be redrawn, the cursor repositioned at the current cursor position, and sh shall be placed in command mode.

\
Perform pathname expansion (see Pathname Expansion ) on the current bigword, up to the largest set of characters that can be matched uniquely. If the bigword contains none of the characters '?' , '*' , or '[' , an asterisk ( '*' ) shall be implicitly assumed at the end. This maximal expansion then shall replace the original bigword in the command line, and the cursor shall be placed after this expansion. If the resulting bigword completely and uniquely matches a directory, a '/' character shall be inserted directly after the bigword. If some other file is completely matched, a single <space> shall be inserted after the bigword. After this operation, sh shall be placed in insert mode.
*
Perform pathname expansion on the current bigword and insert all expansions into the command to replace the current bigword, with each expansion separated by a single <space>. If at the end of the line, the current cursor position shall be moved to the first column position following the expansions and sh shall be placed in insert mode. Otherwise, the current cursor position shall be the last column position of the first character after the expansions and sh shall be placed in insert mode. If the current bigword contains none of the characters '?' , '*' , or '[' , before the operation, an asterisk shall be implicitly assumed at the end.
@letter
Insert the value of the alias named _letter. The symbol letter represents a single alphabetic character from the portable character set; implementations may support additional characters as an extension. If the alias _letter contains other editing commands, these commands shall be performed as part of the insertion. If no alias _letter is enabled, this command shall have no effect.
[count]~
Convert, if the current character is a lowercase letter, to the equivalent uppercase letter and vice versa, as prescribed by the current locale. The current cursor position then shall be advanced by one character. If the cursor was positioned on the last character of the line, the case conversion shall occur, but the cursor shall not advance. If the '~' command is preceded by a count, that number of characters shall be converted, and the cursor shall be advanced to the character position after the last character converted. If the count is larger than the number of characters after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.
[count].
Repeat the most recent non-motion command, even if it was executed on an earlier command line. If the previous command was preceded by a count, and no count is given on the '.' command, the count from the previous command shall be included as part of the repeated command. If the '.' command is preceded by a count, this shall override any count argument to the previous command. The count specified in the '.' command shall become the count for subsequent '.' commands issued without a count.
[number]v
Invoke the vi editor to edit the current command line in a temporary file. When the editor exits, the commands in the temporary file shall be executed and placed in the command history. If a number is included, it specifies the command number in the command history to be edited, rather than the current command line.
[count]l (ell)
[count]<space>

Move the current cursor position to the next character position. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the count is larger than the number of characters after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.

[count]h
Move the current cursor position to the countth (default 1) previous character position. If the cursor was positioned on the first character of the line, the terminal shall be alerted and the cursor shall not be moved. If the count is larger than the number of characters before the cursor, this shall not be considered an error; the cursor shall move to the first character on the line.
[count]w
Move to the start of the next word. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the count is larger than the number of words after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.
[count]W
Move to the start of the next bigword. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the count is larger than the number of bigwords after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.
[count]e
Move to the end of the current word. If at the end of a word, move to the end of the next word. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the count is larger than the number of words after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.
[count]E
Move to the end of the current bigword. If at the end of a bigword, move to the end of the next bigword. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the count is larger than the number of bigwords after the cursor, this shall not be considered an error; the cursor shall advance to the last character on the line.
[count]b
Move to the beginning of the current word. If at the beginning of a word, move to the beginning of the previous word. If the cursor was positioned on the first character of the line, the terminal shall be alerted and the cursor shall not be moved. If the count is larger than the number of words preceding the cursor, this shall not be considered an error; the cursor shall return to the first character on the line.
[count]B
Move to the beginning of the current bigword. If at the beginning of a bigword, move to the beginning of the previous bigword. If the cursor was positioned on the first character of the line, the terminal shall be alerted and the cursor shall not be moved. If the count is larger than the number of bigwords preceding the cursor, this shall not be considered an error; the cursor shall return to the first character on the line.
^
Move the current cursor position to the first character on the input line that is not a <blank>.
$
Move to the last character position on the current command line.
0
(Zero.) Move to the first character position on the current command line.
[count]|
Move to the countth character position on the current command line. If no number is specified, move to the first position. The first character position shall be numbered 1. If the count is larger than the number of characters on the line, this shall not be considered an error; the cursor shall be placed on the last character on the line.
[count]f c
Move to the first occurrence of the character 'c' that occurs after the current cursor position. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the character 'c' does not occur in the line after the current cursor position, the terminal shall be alerted and the cursor shall not be moved.
[count]F c
Move to the first occurrence of the character 'c' that occurs before the current cursor position. If the cursor was positioned on the first character of the line, the terminal shall be alerted and the cursor shall not be moved. If the character 'c' does not occur in the line before the current cursor position, the terminal shall be alerted and the cursor shall not be moved.
[count]t c
Move to the character before the first occurrence of the character 'c' that occurs after the current cursor position. If the cursor was positioned on the last character of the line, the terminal shall be alerted and the cursor shall not be advanced. If the character 'c' does not occur in the line after the current cursor position, the terminal shall be alerted and the cursor shall not be moved.
[count]T c
Move to the character after the first occurrence of the character 'c' that occurs before the current cursor position. If the cursor was positioned on the first character of the line, the terminal shall be alerted and the cursor shall not be moved. If the character 'c' does not occur in the line before the current cursor position, the terminal shall be alerted and the cursor shall not be moved.
[count];
Repeat the most recent f, F, t, or T command. Any number argument on that previous command shall be ignored. Errors are those described for the repeated command.
[count],
Repeat the most recent f, F, t, or T command. Any number argument on that previous command shall be ignored. However, reverse the direction of that command.
a
Enter insert mode after the current cursor position. Characters that are entered shall be inserted before the next character.
A
Enter insert mode after the end of the current command line.
i
Enter insert mode at the current cursor position. Characters that are entered shall be inserted before the current character.
I
Enter insert mode at the beginning of the current command line.
R
Enter insert mode, replacing characters from the command line beginning at the current cursor position.
[count]c motion

Delete the characters between the current cursor position and the cursor position that would result from the specified motion command. Then enter insert mode before the first character following any deleted characters. If count is specified, it shall be applied to the motion command. A count shall be ignored for the following motion commands:

0    ^    $    c

If the motion command is the character 'c' , the current command line shall be cleared and insert mode shall be entered. If the motion command would move the current cursor position toward the beginning of the command line, the character under the current cursor position shall not be deleted. If the motion command would move the current cursor position toward the end of the command line, the character under the current cursor position shall be deleted. If the count is larger than the number of characters between the current cursor position and the end of the command line toward which the motion command would move the cursor, this shall not be considered an error; all of the remaining characters in the aforementioned range shall be deleted and insert mode shall be entered. If the motion command is invalid, the terminal shall be alerted, the cursor shall not be moved, and no text shall be deleted.

C
Delete from the current character to the end of the line and enter insert mode at the new end-of-line.
S
Clear the entire edit line and enter insert mode.
[count]r c
Replace the current character with the character 'c' . With a number count, replace the current and the following count-1 characters. After this command, the current cursor position shall be on the last character that was changed. If the count is larger than the number of characters after the cursor, this shall not be considered an error; all of the remaining characters shall be changed.
[count]_
Append a <space> after the current character position and then append the last bigword in the previous input line after the <space>. Then enter insert mode after the last character just appended. With a number count, append the countth bigword in the previous line.
[count]x
Delete the character at the current cursor position and place the deleted characters in the save buffer. If the cursor was positioned on the last character of the line, the character shall be deleted and the cursor position shall be moved to the previous character (the new last character). If the count is larger than the number of characters after the cursor, this shall not be considered an error; all the characters from the cursor to the end of the line shall be deleted.
[count]X
Delete the character before the current cursor position and place the deleted characters in the save buffer. The character under the current cursor position shall not change. If the cursor was positioned on the first character of the line, the terminal shall be alerted, and the X command shall have no effect. If the line contained a single character, the X command shall have no effect. If the line contained no characters, the terminal shall be alerted and the cursor shall not be moved. If the count is larger than the number of characters before the cursor, this shall not be considered an error; all the characters from before the cursor to the beginning of the line shall be deleted.
[count]d motion

Delete the characters between the current cursor position and the character position that would result from the motion command. A number count repeats the motion command count times. If the motion command would move toward the beginning of the command line, the character under the current cursor position shall not be deleted. If the motion command is d, the entire current command line shall be cleared. If the count is larger than the number of characters between the current cursor position and the end of the command line toward which the motion command would move the cursor, this shall not be considered an error; all of the remaining characters in the aforementioned range shall be deleted. The deleted characters shall be placed in the save buffer.

D
Delete all characters from the current cursor position to the end of the line. The deleted characters shall be placed in the save buffer.
[count]y motion

Yank (that is, copy) the characters from the current cursor position to the position resulting from the motion command into the save buffer. A number count shall be applied to the motion command. If the motion command would move toward the beginning of the command line, the character under the current cursor position shall not be included in the set of yanked characters. If the motion command is y, the entire current command line shall be yanked into the save buffer. The current cursor position shall be unchanged. If the count is larger than the number of characters between the current cursor position and the end of the command line toward which the motion command would move the cursor, this shall not be considered an error; all of the remaining characters in the aforementioned range shall be yanked.

Y
Yank the characters from the current cursor position to the end of the line into the save buffer. The current character position shall be unchanged.
[count]p
Put a copy of the current contents of the save buffer after the current cursor position. The current cursor position shall be advanced to the last character put from the save buffer. A count shall indicate how many copies of the save buffer shall be put.
[count]P
Put a copy of the current contents of the save buffer before the current cursor position. The current cursor position shall be moved to the last character put from the save buffer. A count shall indicate how many copies of the save buffer shall be put.
u
Undo the last command that changed the edit line. This operation shall not undo the copy of any command line to the edit line.
U
Undo all changes made to the edit line. This operation shall not undo the copy of any command line to the edit line.
[count]k
[count]-
Set the current command line to be the countth previous command line in the shell command history. If count is not specified, it shall default to 1. The cursor shall be positioned on the first character of the new command. If a k or - command would retreat past the maximum number of commands in effect for this shell (affected by the HISTSIZE environment variable), the terminal shall be alerted, and the command shall have no effect.
[count]j
[count]+
Set the current command line to be the countth next command line in the shell command history. If count is not specified, it shall default to 1. The cursor shall be positioned on the first character of the new command. If a j or + command advances past the edit line, the current command line shall be restored to the edit line and the terminal shall be alerted.
[number]G
Set the current command line to be the oldest command line stored in the shell command history. With a number number, set the current command line to be the command line number in the history. If command line number does not exist, the terminal shall be alerted and the command line shall not be changed.
/pattern<newline>

Move backwards through the command history, searching for the specified pattern, beginning with the previous command line. Patterns use the pattern matching notation described in Pattern Matching Notation , except that the '^' character shall have special meaning when it appears as the first character of pattern. In this case, the '^' is discarded and the characters after the '^' shall be matched only at the beginning of a line. Commands in the command history shall be treated as strings, not as filenames. If the pattern is not found, the current command line shall be unchanged and the terminal is alerted. If it is found in a previous line, the current command line shall be set to that line and the cursor shall be set to the first character of the new command line.

If pattern is empty, the last non-empty pattern provided to / or ? shall be used. If there is no previous non-empty pattern, the terminal shall be alerted and the current command line shall remain unchanged.

?pattern<newline>

Move forwards through the command history, searching for the specified pattern, beginning with the next command line. Patterns use the pattern matching notation described in Pattern Matching Notation , except that the '^' character shall have special meaning when it appears as the first character of pattern. In this case, the '^' is discarded and the characters after the '^' shall be matched only at the beginning of a line. Commands in the command history shall be treated as strings, not as filenames. If the pattern is not found, the current command line shall be unchanged and the terminal alerted. If it is found in a following line, the current command line shall be set to that line and the cursor shall be set to the fist character of the new command line.

If pattern is empty, the last non-empty pattern provided to / or ? shall be used. If there is no previous non-empty pattern, the terminal shall be alerted and the current command line shall remain unchanged.

n
Repeat the most recent / or ? command. If there is no previous / or ?, the terminal shall be alerted and the current command line shall remain unchanged.
N
Repeat the most recent / or ? command, reversing the direction of the search. If there is no previous / or ?, the terminal shall be alerted and the current command line shall remain unchanged.

EXIT STATUS

The following exit values shall be returned:

0
The script to be executed consisted solely of zero or more blank lines or comments, or both.
1-125
A non-interactive shell detected a syntax, redirection, or variable assignment error.
127
A specified command_file could not be found by a non-interactive shell.

Otherwise, the shell shall return the exit status of the last command it invoked or attempted to invoke (see also the exit utility in Special Built-In Utilities ).

CONSEQUENCES OF ERRORS

See Consequences of Shell Errors .

The following sections are informative.

APPLICATION USAGE

Standard input and standard error are the files that determine whether a shell is interactive when -i is not specified. For example:

sh > file

and:

sh 2> file

create interactive and non-interactive shells, respectively. Although both accept terminal input, the results of error conditions are different, as described in Consequences of Shell Errors ; in the second example a redirection error encountered by a special built-in utility aborts the shell.

A conforming application must protect its first operand, if it starts with a plus sign, by preceding it with the "--" argument that denotes the end of the options.

Applications should note that the standard PATH to the shell cannot be assumed to be either /bin/sh or /usr/bin/sh, and should be determined by interrogation of the PATH returned by getconf PATH , ensuring that the returned pathname is an absolute pathname and not a shell built-in.

For example, to determine the location of the standard sh utility:

command -v sh

On some implementations this might return:

/usr/xpg4/bin/sh

Furthermore, on systems that support executable scripts (the "#!" construct), it is recommended that applications using executable scripts install them using getconf -v to determine the shell pathname and update the "#!" script appropriately as it is being installed (for example, with sed). For example:

#
# Installation time script to install correct POSIX shell pathname
#
# Get list of paths to check
#
Sifs=$IFS
IFS=:
set $(getconf PATH)
IFS=$Sifs
#
# Check each path for 'sh'
#
for i in $@
do
    if [ -f ${i}/sh ];
    then
        Pshell=${i}/sh
    fi
done
#
# This is the list of scripts to update. They should be of the
# form '${name}.source' and will be transformed to '${name}'.
# Each script should begin:
#
# !INSTALLSHELLPATH -p
#
scripts="a b c"
#
# Transform each script
#
for i in ${scripts}
do
    sed -e "s|INSTALLSHELLPATH|${Pshell}|" < ${i}.source > ${i}
done

EXAMPLES

1.
Execute a shell command from a string:

sh -c "cat myfile"

2.
Execute a shell script from a file in the current directory:

sh my_shell_cmds

RATIONALE

The sh utility and the set special built-in utility share a common set of options.

The KornShell ignores the contents of IFS upon entry to the script. A conforming application cannot rely on importing IFS . One justification for this, beyond security considerations, is to assist possible future shell compilers. Allowing IFS to be imported from the environment prevents many optimizations that might otherwise be performed via dataflow analysis of the script itself.

The text in the STDIN section about non-blocking reads concerns an instance of sh that has been invoked, probably by a C-language program, with standard input that has been opened using the O_NONBLOCK flag; see open() in the System Interfaces volume of IEEE Std 1003.1-2001. If the shell did not reset this flag, it would immediately terminate because no input data would be available yet and that would be considered the same as end-of-file.

The options associated with a restricted shell (command name rsh and the -r option) were excluded because the standard developers considered that the implied level of security could not be achieved and they did not want to raise false expectations.

On systems that support set-user-ID scripts, a historical trapdoor has been to link a script to the name -i. When it is called by a sequence such as:

sh -

or by:

#! usr/bin/sh -

the historical systems have assumed that no option letters follow. Thus, this volume of IEEE Std 1003.1-2001 allows the single hyphen to mark the end of the options, in addition to the use of the regular "--" argument, because it was considered that the older practice was so pervasive. An alternative approach is taken by the KornShell, where real and effective user/group IDs must match for an interactive shell; this behavior is specifically allowed by this volume of IEEE Std 1003.1-2001.

Note:
There are other problems with set-user-ID scripts that the two approaches described here do not resolve.

The initialization process for the history file can be dependent on the system start-up files, in that they may contain commands that effectively preempt the user's settings of HISTFILE and HISTSIZE . For example, function definition commands are recorded in the history file, unless the set -o nolog option is set. If the system administrator includes function definitions in some system start-up file called before the ENV file, the history file is initialized before the user gets a chance to influence its characteristics. In some historical shells, the history file is initialized just after the ENV file has been processed. Therefore, it is implementation-defined whether changes made to HISTFILE after the history file has been initialized are effective.

The default messages for the various MAIL -related messages are unspecified because they vary across implementations. Typical messages are:

"you have mail\n"

or:

"you have new mail\n"

It is important that the descriptions of command line editing refer to the same shell as that in IEEE Std 1003.1-2001 so that interactive users can also be application programmers without having to deal with programmatic differences in their two environments. It is also essential that the utility name sh be specified because this explicit utility name is too firmly rooted in historical practice of application programs for it to change.

Consideration was given to mandating a diagnostic message when attempting to set vi-mode on terminals that do not support command line editing. However, it is not historical practice for the shell to be cognizant of all terminal types and thus be able to detect inappropriate terminals in all cases. Implementations are encouraged to supply diagnostics in this case whenever possible, rather than leaving the user in a state where editing commands work incorrectly.

In early proposals, the KornShell-derived emacs mode of command line editing was included, even though the emacs editor itself was not. The community of emacs proponents was adamant that the full emacs editor not be standardized because they were concerned that an attempt to standardize this very powerful environment would encourage vendors to ship strictly conforming versions lacking the extensibility required by the community. The author of the original emacs program also expressed his desire to omit the program. Furthermore, there were a number of historical systems that did not include emacs, or included it without supporting it, but there were very few that did not include and support vi. The shell emacs command line editing mode was finally omitted because it became apparent that the KornShell version and the editor being distributed with the GNU system had diverged in some respects. The author of emacs requested that the POSIX emacs mode either be deleted or have a significant number of unspecified conditions. Although the KornShell author agreed to consider changes to bring the shell into alignment, the standard developers decided to defer specification at that time. At the time, it was assumed that convergence on an acceptable definition would occur for a subsequent draft, but that has not happened, and there appears to be no impetus to do so. In any case, implementations are free to offer additional command line editing modes based on the exact models of editors their users are most comfortable with.

Early proposals had the following list entry in vi Line Editing Insert Mode :

\
If followed by the erase or kill character, that character shall be inserted into the input line. Otherwise, the backslash itself shall be inserted into the input line.

However, this is not actually a feature of sh command line editing insert mode, but one of some historical terminal line drivers. Some conforming implementations continue to do this when the stty iexten flag is set.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , cd , echo , exit() , fc , pwd , read() , set , stty , test , umask() , vi , the System Interfaces volume of IEEE Std 1003.1-2001, dup(), exec, exit(), fork(), open(), pipe(), signal(), system(), ulimit(), umask(), wait()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tr(1p)

TR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tr - translate characters

SYNOPSIS

tr [-c | -C][-s] string1 string2

tr -s [-c | -C] string1

tr -d [-c | -C] string1

tr -ds [-c | -C] string1 string2

DESCRIPTION

The tr utility shall copy the standard input to the standard output with substitution or deletion of selected characters. The options specified and the string1 and string2 operands shall control translations that occur while copying characters and single-character collating elements.

OPTIONS

The tr utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Complement the set of values specified by string1. See the EXTENDED DESCRIPTION section.
-C
Complement the set of characters specified by string1. See the EXTENDED DESCRIPTION section.
-d
Delete all occurrences of input characters that are specified by string1.
-s
Replace instances of repeated characters with a single character, as described in the EXTENDED DESCRIPTION section.

OPERANDS

The following operands shall be supported:

string1, string2

Translation control strings. Each string shall represent a set of characters to be converted into an array of characters used for the translation. For a detailed description of how the strings are interpreted, see the EXTENDED DESCRIPTION section.

STDIN

The standard input can be any type of file.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of tr:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of range expressions and equivalence classes.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments) and the behavior of character classes.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The tr output shall be identical to the input, with the exception of the specified transformations.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The operands string1 and string2 (if specified) define two arrays of characters. The constructs in the following list can be used to specify characters or single-character collating elements. If any of the constructs result in multi-character collating elements, tr shall exclude, without a diagnostic, those multi-character elements from the resulting array.

character
Any character not described by one of the conventions below shall represent itself.
\octal
Octal sequences can be used to represent characters with specific coded values. An octal sequence shall consist of a backslash followed by the longest sequence of one, two, or three-octal-digit characters (01234567). The sequence shall cause the value whose encoding is represented by the one, two, or three-digit octal integer to be placed into the array. If the size of a byte on the system is greater than nine bits, the valid escape sequence used to represent a byte is implementation-defined. Multi-byte characters require multiple, concatenated escape sequences of this type, including the leading '\' for each byte.
\character
The backslash-escape sequences in the Base Definitions volume of IEEE Std 1003.1-2001, Table 5-1, Escape Sequences and Associated Actions ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ) shall be supported. The results of using any other character, other than an octal digit, following the backslash are unspecified.
c-c
In the POSIX locale, this construct shall represent the range of collating elements between the range endpoints (as long as neither endpoint is an octal sequence of the form \octal), inclusive, as defined by the collation sequence. The characters or collating elements in the range shall be placed in the array in ascending collation sequence. If the second endpoint precedes the starting endpoint in the collation sequence, it is unspecified whether the range of collating elements is empty, or this construct is treated as invalid. In locales other than the POSIX locale, this construct has unspecified behavior.

If either or both of the range endpoints are octal sequences of the form \octal, this shall represent the range of specific coded values between the two range endpoints, inclusive.

:class:
Represents all characters belonging to the defined character class, as defined by the current setting of the LC_CTYPE locale category. The following character class names shall be accepted when specified in string1:
alnum blank digit lower punct upper
alpha cntrl graph print space xdigit

In addition, character class expressions of the form [: name:] shall be recognized in those locales where the name keyword has been given a charclass definition in the LC_CTYPE category.

When both the -d and -s options are specified, any of the character class names shall be accepted in string2. Otherwise, only character class names lower or upper are valid in string2 and then only if the corresponding character class ( upper and lower, respectively) is specified in the same relative position in string1. Such a specification shall be interpreted as a request for case conversion. When [: lower:] appears in string1 and [: upper:] appears in string2, the arrays shall contain the characters from the toupper mapping in the LC_CTYPE category of the current locale. When [: upper:] appears in string1 and [: lower:] appears in string2, the arrays shall contain the characters from the tolower mapping in the LC_CTYPE category of the current locale. The first character from each mapping pair shall be in the array for string1 and the second character from each mapping pair shall be in the array for string2 in the same relative position.

Except for case conversion, the characters specified by a character class expression shall be placed in the array in an unspecified order.

If the name specified for class does not define a valid character class in the current locale, the behavior is undefined.

=equiv=
Represents all characters or collating elements belonging to the same equivalence class as equiv, as defined by the current setting of the LC_COLLATE locale category. An equivalence class expression shall be allowed only in string1, or in string2 when it is being used by the combined -d and -s options. The characters belonging to the equivalence class shall be placed in the array in an unspecified order.
x*n
Represents n repeated occurrences of the character x. Because this expression is used to map multiple characters to one, it is only valid when it occurs in string2. If n is omitted or is zero, it shall be interpreted as large enough to extend the string2-based sequence to the length of the string1-based sequence. If n has a leading zero, it shall be interpreted as an octal value. Otherwise, it shall be interpreted as a decimal value.

When the -d option is not specified:

*
Each input character found in the array specified by string1 shall be replaced by the character in the same relative position in the array specified by string2. When the array specified by string2 is shorter that the one specified by string1, the results are unspecified.

*
If the -C option is specified, the complements of the characters specified by string1 (the set of all characters in the current character set, as defined by the current setting of LC_CTYPE , except for those actually specified in the string1 operand) shall be placed in the array in ascending collation sequence, as defined by the current setting of LC_COLLATE .

*
If the -c option is specified, the complement of the values specified by string1 shall be placed in the array in ascending order by binary value.

*
Because the order in which characters specified by character class expressions or equivalence class expressions is undefined, such expressions should only be used if the intent is to map several characters into one. An exception is case conversion, as described previously.

When the -d option is specified:

*
Input characters found in the array specified by string1 shall be deleted.

*
When the -C option is specified with -d, all characters except those specified by string1 shall be deleted. The contents of string2 are ignored, unless the -s option is also specified.

*
When the -c option is specified with -d, all values except those specified by string1 shall be deleted. The contents of string2 shall be ignored, unless the -s option is also specified.

*
The same string cannot be used for both the -d and the -s option; when both options are specified, both string1 (used for deletion) and string2 (used for squeezing) shall be required.

When the -s option is specified, after any deletions or translations have taken place, repeated sequences of the same character shall be replaced by one occurrence of the same character, if the character is found in the array specified by the last operand. If the last operand contains a character class, such as the following example:

tr -s '[:space:]'

the last operand's array shall contain all of the characters in that character class. However, in a case conversion, as described previously, such as:

tr -s '[:upper:]' '[:lower:]'

the last operand's array shall contain only those characters defined as the second characters in each of the toupper or tolower character pairs, as appropriate.

An empty string used for string1 or string2 produces undefined results.

EXIT STATUS

The following exit values shall be returned:

0
All input was processed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

If necessary, string1 and string2 can be quoted to avoid pattern matching by the shell.

If an ordinary digit (representing itself) is to follow an octal sequence, the octal sequence must use the full three digits to avoid ambiguity.

When string2 is shorter than string1, a difference results between historical System V and BSD systems. A BSD system pads string2 with the last character found in string2. Thus, it is possible to do the following:

tr 0123456789 d

which would translate all digits to the letter 'd' . Since this area is specifically unspecified in this volume of IEEE Std 1003.1-2001, both the BSD and System V behaviors are allowed, but a conforming application cannot rely on the BSD behavior. It would have to code the example in the following way:

tr 0123456789 '[d*]'

It should be noted that, despite similarities in appearance, the string operands used by tr are not regular expressions.

Unlike some historical implementations, this definition of the tr utility correctly processes NUL characters in its input stream. NUL characters can be stripped by using:

tr -d '\000'

EXAMPLES

1.
The following example creates a list of all words in file1 one per line in file2, where a word is taken to be a maximal string of letters.

tr -cs "[:alpha:]" "[\n*]" <file1 >file2

2.
The next example translates all lowercase characters in file1 to uppercase and writes the results to standard output.

tr "[:lower:]" "[:upper:]" <file1

3.
This example uses an equivalence class to identify accented variants of the base character 'e' in file1, which are stripped of diacritical marks and written to file2.

tr "[=e=]" e <file1 >file2

RATIONALE

In some early proposals, an explicit option -n was added to disable the historical behavior of stripping NUL characters from the input. It was considered that automatically stripping NUL characters from the input was not correct functionality. However, the removal of -n in a later proposal does not remove the requirement that tr correctly process NUL characters in its input stream. NUL characters can be stripped by using tr -d '\000'.

Historical implementations of tr differ widely in syntax and behavior. For example, the BSD version has not needed the bracket characters for the repetition sequence. The tr utility syntax is based more closely on the System V and XPG3 model while attempting to accommodate historical BSD implementations. In the case of the short string2 padding, the decision was to unspecify the behavior and preserve System V and XPG3 scripts, which might find difficulty with the BSD method. The assumption was made that BSD users of tr have to make accommodations to meet the syntax defined here. Since it is possible to use the repetition sequence to duplicate the desired behavior, whereas there is no simple way to achieve the System V method, this was the correct, if not desirable, approach.

The use of octal values to specify control characters, while having historical precedents, is not portable. The introduction of escape sequences for control characters should provide the necessary portability. It is recognized that this may cause some historical scripts to break.

An early proposal included support for multi-character collating elements. It was pointed out that, while tr does employ some syntactical elements from REs, the aim of tr is quite different; ranges, for example, do not have a similar meaning (``any of the chars in the range matches", versus "translate each character in the range to the output counterpart"). As a result, the previously included support for multi-character collating elements has been removed. What remains are ranges in current collation order (to support, for example, accented characters), character classes, and equivalence classes.

In XPG3 the [: class:] and [= equiv=] conventions are shown with double brackets, as in RE syntax. However, tr does not implement RE principles; it just borrows part of the syntax. Consequently, [: class:] and [= equiv=] should be regarded as syntactical elements on a par with [ x* n], which is not an RE bracket expression.

The standard developers will consider changes to tr that allow it to translate characters between different character encodings, or they will consider providing a new utility to accomplish this.

On historical System V systems, a range expression requires enclosing square-brackets, such as:

tr '[a-z]' '[A-Z]'

However, BSD-based systems did not require the brackets, and this convention is used here to avoid breaking large numbers of BSD scripts:

tr a-z A-Z

The preceding System V script will continue to work because the brackets, treated as regular characters, are translated to themselves. However, any System V script that relied on "a-z" representing the three characters 'a' , '-' , and 'z' have to be rewritten as "az-" .

The ISO POSIX-2:1993 standard had a -c option that behaved similarly to the -C option, but did not supply functionality equivalent to the -c option specified in IEEE Std 1003.1-2001. This meant that historical practice of being able to specify tr -d\200-\377 (which would delete all bytes with the top bit set) would have no effect because, in the C locale, bytes with the values octal 200 to octal 377 are not characters.

The earlier version also said that octal sequences referred to collating elements and could be placed adjacent to each other to specify multi-byte characters. However, it was noted that this caused ambiguities because tr would not be able to tell whether adjacent octal sequences were intending to specify multi-byte characters or multiple single byte characters. IEEE Std 1003.1-2001 specifies that octal sequences always refer to single byte binary values.

FUTURE DIRECTIONS

None.

SEE ALSO

sed

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cflow(1p)

CFLOW

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cflow - generate a C-language flowgraph (DEVELOPMENT)

SYNOPSIS

cflow [-r][-d num][-D name[=def]] ... [-i incl][-I dir] ...
[-U dir] ... file ...

DESCRIPTION

The cflow utility shall analyze a collection of object files or assembler, C-language, lex, or yacc source files, and attempt to build a graph, written to standard output, charting the external references.

OPTIONS

The cflow utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the order of the -D, -I, and -U options (which are identical to their interpretation by c99) is significant.

The following options shall be supported:

-d num
Indicate the depth at which the flowgraph is cut off. The application shall ensure that the argument num is a decimal integer. By default this is a very large number (typically greater than 32000). Attempts to set the cut-off depth to a non-positive integer shall be ignored.
-i incl
Increase the number of included symbols. The incl option-argument is one of the following characters:
x
Include external and static data symbols. The default shall be to include only functions in the flowgraph.
_
(Underscore) Include names that begin with an underscore. The default shall be to exclude these functions (and data if -i x is used).

-r
Reverse the caller:callee relationship, producing an inverted listing showing the callers of each function. The listing shall also be sorted in lexicographical order by callee.

OPERANDS

The following operand is supported:

file
The pathname of a file for which a graph is to be generated. Filenames suffixed by .l shall shall be taken to be lex input, .y as yacc input, .c as c99 input, and .i as the output of c99 -E. Such files shall be processed as appropriate, determined by their suffix.

Files suffixed by .s (conventionally assembler source) may have more limited information extracted from them.

STDIN

Not used.

INPUT FILES

The input files shall be object files or assembler, C-language, lex, or yacc source files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cflow:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the ordering of the output when the -r option is used.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The flowgraph written to standard output shall be formatted as follows:

"%d %s:%s\n", <reference number>, <global>, <definition>

Each line of output begins with a reference (that is, line) number, followed by indentation of at least one column position per level. This is followed by the name of the global, a colon, and its definition. Normally globals are only functions not defined as an external or beginning with an underscore; see the OPTIONS section for the -i inclusion option. For information extracted from C-language source, the definition consists of an abstract type declaration (for example, char *) and, delimited by angle brackets, the name of the source file and the line number where the definition was found. Definitions extracted from object files indicate the filename and location counter under which the symbol appeared (for example, text).

Once a definition of a name has been written, subsequent references to that name contain only the reference number of the line where the definition can be found. For undefined references, only "<>" shall be written.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Files produced by lex and yacc cause the reordering of line number declarations, and this can confuse cflow. To obtain proper results, the input of yacc or lex must be directed to cflow.

EXAMPLES

Given the following in file.c:

int i;
int f();
int g();
int h();
int
main()
{
    f();
    g();
    f();
}
int
f()
{
    i = h();
}

The command:

cflow -i x file.c

produces the output:

1 main: int(), <file.c 6>
2    f: int(), <file.c 13>
3        h: <>
4        i: int, <file.c 1>
5    g: <>

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

c99 , lex , yacc

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vi(1p)

VI

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

vi - screen-oriented (visual) display editor

SYNOPSIS

vi [-rR][-c command][-t tagstring][-w size][file ...]

DESCRIPTION

This utility shall be provided on systems that both support the User Portability Utilities option and define the POSIX2_CHAR_TERM symbol. On other systems it is optional.

The vi (visual) utility is a screen-oriented text editor. Only the open and visual modes of the editor are described in IEEE Std 1003.1-2001; see the line editor ex for additional editing capabilities used in vi. The user can switch back and forth between vi and ex and execute ex commands from within vi.

This reference page uses the term edit buffer to describe the current working text. No specific implementation is implied by this term. All editing changes are performed on the edit buffer, and no changes to it shall affect any file until an editor command writes the file.

When using vi, the terminal screen acts as a window into the editing buffer. Changes made to the editing buffer shall be reflected in the screen display; the position of the cursor on the screen shall indicate the position within the editing buffer.

Certain terminals do not have all the capabilities necessary to support the complete vi definition. When these commands cannot be supported on such terminals, this condition shall not produce an error message such as "not an editor command" or report a syntax error. The implementation may either accept the commands and produce results on the screen that are the result of an unsuccessful attempt to meet the requirements of this volume of IEEE Std 1003.1-2001 or report an error describing the terminal-related deficiency.

OPTIONS

The vi utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c command
See the ex command description of the -c option.
-r
See the ex command description of the -r option.
-R
See the ex command description of the -R option.
-t tagstring
See the ex command description of the -t option.
-w size
See the ex command description of the -w option.

OPERANDS

See the OPERANDS section of the ex command for a description of the operands supported by the vi command.

STDIN

If standard input is not a terminal device, the results are undefined. The standard input consists of a series of commands and input text, as described in the EXTENDED DESCRIPTION section.

If a read from the standard input returns an error, or if the editor detects an end-of-file condition from the standard input, it shall be equivalent to a SIGHUP asynchronous event.

INPUT FILES

See the INPUT FILES section of the ex command for a description of the input files supported by the vi command.

ENVIRONMENT VARIABLES

See the ENVIRONMENT VARIABLES section of the ex command for the environment variables that affect the execution of the vi command.

ASYNCHRONOUS EVENTS

See the ASYNCHRONOUS EVENTS section of the ex for the asynchronous events that affect the execution of the vi command.

STDOUT

If standard output is not a terminal device, undefined results occur.

Standard output may be used for writing prompts to the user, for informational messages, and for writing lines from the file.

STDERR

If standard output is not a terminal device, undefined results occur.

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

See the OUTPUT FILES section of the ex command for a description of the output files supported by the vi command.

EXTENDED DESCRIPTION

If the terminal does not have the capabilities necessary to support an unspecified portion of the vi definition, implementations shall start initially in ex mode or open mode. Otherwise, after initialization, vi shall be in command mode; text input mode can be entered by one of several commands used to insert or change text. In text input mode, <ESC> can be used to return to command mode; other uses of <ESC> are described later in this section; see Terminate Command or Input Mode .

Initialization in ex and vi

See Initialization in ex and vi for a description of ex and vi initialization for the vi utility.

Command Descriptions in vi

The following symbols are used in this reference page to represent arguments to commands.

buffer
See the description of buffer in the EXTENDED DESCRIPTION section of the ex utility; see Command Descriptions in ex .

In open and visual mode, when a command synopsis shows both [ buffer] and [ count] preceding the command name, they can be specified in either order.

count
A positive integer used as an optional argument to most commands, either to give a repeat count or as a size. This argument is optional and shall default to 1 unless otherwise specified.

The Synopsis lines for the vi commands <control>-G, <control>-L, <control>-R, <control>-], %, &, ^, D, m, M, Q, u, U, and ZZ do not have count as an optional argument. Regardless, it shall not be an error to specify a count to these commands, and any specified count shall be ignored.

motion
An optional trailing argument used by the !, <, >, c, d, and y commands, which is used to indicate the region of text that shall be affected by the command. The motion can be either one of the command characters repeated or one of several other vi commands (listed in the following table). Each of the applicable commands specifies the region of text matched by repeating the command; each command that can be used as a motion command specifies the region of text it affects.

Commands that take motion arguments operate on either lines or characters, depending on the circumstances. When operating on lines, all lines that fall partially or wholly within the text region specified for the command shall be affected. When operating on characters, only the exact characters in the specified text region shall be affected. Each motion command specifies this individually.

When commands that may be motion commands are not used as motion commands, they shall set the current position to the current line and column as specified.

The following commands shall be valid cursor motion commands:

<apostrophe>       (    -    j    H
<carriage-return>  )    $    k    L
<comma>            [[   %    l    M
<control>-H        ]]   _    n    N
<control>-N        {    ;    t    T
<control>-P        }    ?    w    W
<grave accent>     ^    b    B
<newline>          +    e    E
<space>            |    f    F
<zero>             /    h    G

Any count that is specified to a command that has an associated motion command shall be applied to the motion command. If a count is applied to both the command and its associated motion command, the effect shall be multiplicative.

The following symbols are used in this section to specify locations in the edit buffer:

current character

The character that is currently indicated by the cursor.

end of a line

The point located between the last non- <newline> (if any) and the terminating <newline> of a line. For an empty line, this location coincides with the beginning of the line.

end of the edit buffer

The location corresponding to the end of the last line in the edit buffer.

The following symbols are used in this section to specify command actions:

bigword
In the POSIX locale, vi shall recognize four kinds of bigwords:
1.
A maximal sequence of non- <blank>s preceded and followed by <blank>s or the beginning or end of a line or the edit buffer

2.
One or more sequential blank lines

3.
The first character in the edit buffer

4.
The last non- <newline> in the edit buffer

word
In the POSIX locale, vi shall recognize five kinds of words:
1.
A maximal sequence of letters, digits, and underscores, delimited at both ends by:
*
Characters other than letters, digits, or underscores

*
The beginning or end of a line

*
The beginning or end of the edit buffer

2.
A maximal sequence of characters other than letters, digits, underscores, or <blank>s, delimited at both ends by:
*
A letter, digit, underscore

*
<blank>s

*
The beginning or end of a line

*
The beginning or end of the edit buffer

3.
One or more sequential blank lines

4.
The first character in the edit buffer

5.
The last non- <newline> in the edit buffer

section boundary

A section boundary is one of the following:

1.
A line whose first character is a <form-feed>

2.
A line whose first character is an open curly brace ( '{' )

3.
A line whose first character is a period and whose second and third characters match a two-character pair in the sections edit option (see ed)

4.
A line whose first character is a period and whose only other character matches the first character of a two-character pair in the sections edit option, where the second character of the two-character pair is a <space>

5.
The first line of the edit buffer

6.
The last line of the edit buffer if the last line of the edit buffer is empty or if it is a ]] or } command; otherwise, the last non- <newline> of the last line of the edit buffer

paragraph boundary

A paragraph boundary is one of the following:

1.
A section boundary

2.
A line whose first character is a period and whose second and third characters match a two-character pair in the paragraphs edit option (see ed)

3.
A line whose first character is a period and whose only other character matches the first character of a two-character pair in the paragraphs edit option, where the second character of the two-character pair is a <space>

4.
One or more sequential blank lines

remembered search direction

See the description of remembered search direction in ed.

sentence boundary

A sentence boundary is one of the following:

1.
A paragraph boundary

2.
The first non- <blank> that occurs after a paragraph boundary

3.
The first non- <blank> that occurs after a period ( '.' ), exclamation mark ( '!' ), or question mark ( '?' ), followed by two <space>s or the end of a line; any number of closing parenthesis ( ')' ), closing brackets ( ']' ), double quote ( ' ),' or single quote ( '" ) characters can appear between the punctuation mark and the two <space>s or end-of-line

In the remainder of the description of the vi utility, the term "buffer line" refers to a line in the edit buffer and the term "display line" refers to the line or lines on the display screen used to display one buffer line. The term "current line" refers to a specific "buffer line".

If there are display lines on the screen for which there are no corresponding buffer lines because they correspond to lines that would be after the end of the file, they shall be displayed as a single tilde ( '~' ) character, plus the terminating <newline>.

The last line of the screen shall be used to report errors or display informational messages. It shall also be used to display the input for "line-oriented commands" ( /, ?, :, and !). When a line-oriented command is executed, the editor shall enter text input mode on the last line on the screen, using the respective command characters as prompt characters. (In the case of the ! command, the associated motion shall be entered by the user before the editor enters text input mode.) The line entered by the user shall be terminated by a <newline>, a non- <control>-V-escaped <carriage-return>, or unescaped <ESC>. It is unspecified if more characters than require a display width minus one column number of screen columns can be entered.

If any command is executed that overwrites a portion of the screen other than the last line of the screen (for example, the ex suspend or ! commands), other than the ex shell command, the user shall be prompted for a character before the screen is refreshed and the edit session continued.

<tab>s shall take up the number of columns on the screen set by the tabstop edit option (see ed), unless there are less than that number of columns before the display margin that will cause the displayed line to be folded; in this case, they shall only take up the number of columns up to that boundary.

The cursor shall be placed on the current line and relative to the current column as specified by each command described in the following sections.

In open mode, if the current line is not already displayed, then it shall be displayed.

In visual mode, if the current line is not displayed, then the lines that are displayed shall be expanded, scrolled, or redrawn to cause an unspecified portion of the current line to be displayed. If the screen is redrawn, no more than the number of display lines specified by the value of the window edit option shall be displayed (unless the current line cannot be completely displayed in the number of display lines specified by the window edit option) and the current line shall be positioned as close to the center of the displayed lines as possible (within the constraints imposed by the distance of the line from the beginning or end of the edit buffer). If the current line is before the first line in the display and the screen is scrolled, an unspecified portion of the current line shall be placed on the first line of the display. If the current line is after the last line in the display and the screen is scrolled, an unspecified portion of the current line shall be placed on the last line of the display.

In visual mode, if a line from the edit buffer (other than the current line) does not entirely fit into the lines at the bottom of the display that are available for its presentation, the editor may choose not to display any portion of the line. The lines of the display that do not contain text from the edit buffer for this reason shall each consist of a single '@' character.

In visual mode, the editor may choose for unspecified reasons to not update lines in the display to correspond to the underlying edit buffer text. The lines of the display that do not correctly correspond to text from the edit buffer for this reason shall consist of a single '@' character (plus the terminating <newline>), and the <control>-R command shall cause the editor to update the screen to correctly represent the edit buffer.

Open and visual mode commands that set the current column set it to a column position in the display, and not a character position in the line. In this case, however, the column position in the display shall be calculated for an infinite width display; for example, the column related to a character that is part of a line that has been folded onto additional screen lines will be offset from the display line column where the buffer line begins, not from the beginning of a particular display line.

The display cursor column in the display is based on the value of the current column, as follows, with each rule applied in turn:

1.
If the current column is after the last display line column used by the displayed line, the display cursor column shall be set to the last display line column occupied by the last non- <newline> in the current line; otherwise, the display cursor column shall be set to the current column.

2.
If the character of which some portion is displayed in the display line column specified by the display cursor column requires more than a single display line column:
a.
If in text input mode, the display cursor column shall be adjusted to the first display line column in which any portion of that character is displayed.

b.
Otherwise, the display cursor column shall be adjusted to the last display line column in which any portion of that character is displayed.

The current column shall not be changed by these adjustments to the display cursor column.

If an error occurs during the parsing or execution of a vi command:

*
The terminal shall be alerted. Execution of the vi command shall stop, and the cursor (for example, the current line and column) shall not be further modified.

*
Unless otherwise specified by the following command sections, it is unspecified whether an informational message shall be displayed.

*
Any partially entered vi command shall be discarded.

*
If the vi command resulted from a map expansion, all characters from that map expansion shall be discarded, except as otherwise specified by the map command (see ed).

*
If the vi command resulted from the execution of a buffer, no further commands caused by the execution of the buffer shall be executed.

Page Backwards

Synopsis:

[count] <control>-B

If in open mode, the <control>-B command shall behave identically to the z command. Otherwise, if the current line is the first line of the edit buffer, it shall be an error.

If the window edit option is less than 3, display a screen where the last line of the display shall be some portion of:

(current first line) -1

otherwise, display a screen where the first line of the display shall be some portion of:

(current first line) - count x ((window edit option) -2)

If this calculation would result in a line that is before the first line of the edit buffer, the first line of the display shall display some portion of the first line of the edit buffer.

Current line: If no lines from the previous display remain on the screen, set to the last line of the display; otherwise, set to ( line - the number of new lines displayed on this screen).

Current column: Set to non- <blank>.

Scroll Forward

Synopsis:

[count] <control>-D

If the current line is the last line of the edit buffer, it shall be an error.

If no count is specified, count shall default to the count associated with the previous <control>-D or <control>-U command. If there was no previous <control>-D or <control>-U command, count shall default to the value of the scroll edit option.

If in open mode, write lines starting with the line after the current line, until count lines or the last line of the file have been written.

Current line: If the current line + count is past the last line of the edit buffer, set to the last line of the edit buffer; otherwise, set to the current line + count.

Current column: Set to non- <blank>.

Scroll Forward by Line

Synopsis:

[count] <control>-E

Display the line count lines after the last line currently displayed.

If the last line of the edit buffer is displayed, it shall be an error. If there is no line count lines after the last line currently displayed, the last line of the display shall display some portion of the last line of the edit buffer.

Current line: Unchanged if the previous current character is displayed; otherwise, set to the first line displayed.

Current column: Unchanged.

Page Forward

Synopsis:

[count] <control>-F

If in open mode, the <control>-F command shall behave identically to the z command. Otherwise, if the current line is the last line of the edit buffer, it shall be an error.

If the window edit option is less than 3, display a screen where the first line of the display shall be some portion of:

(current last line) +1

otherwise, display a screen where the first line of the display shall be some portion of:

(current first line) + count x ((window edit option) -2)

If this calculation would result in a line that is after the last line of the edit buffer, the last line of the display shall display some portion of the last line of the edit buffer.

Current line: If no lines from the previous display remain on the screen, set to the first line of the display; otherwise, set to ( line + the number of new lines displayed on this screen).

Current column: Set to non- <blank>.

Display Information

Synopsis:

<control>-G

This command shall be equivalent to the ex file command.

Move Cursor Backwards

Synopsis:

[count] <control>-H

[count] h

the current erase character (see stty)

If there are no characters before the current character on the current line, it shall be an error. If there are less than count previous characters on the current line, count shall be adjusted to the number of previous characters on the line.

If used as a motion command:

1.
The text region shall be from the character before the starting cursor up to and including the countth character before the starting cursor.

2.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: Set to ( column - the number of columns occupied by count characters ending with the previous current column).

Move Down

Synopsis:

[count] <newline>

[count] <control>-J

[count] <control>-M

[count] <control>-N

[count] j

[count] <carriage-return>

[count] +

If there are less than count lines after the current line in the edit buffer, it shall be an error.

If used as a motion command:

1.
The text region shall include the starting line and the next count - 1 lines.

2.
Any text copied to a buffer shall be in line mode.

If not used as a motion command:

Current line: Set to current line+ count.

Current column: Set to non- <blank> for the <carriage-return>, <control>-M, and + commands; otherwise, unchanged.

Clear and Redisplay

Synopsis:

<control>-L

If in open mode, clear the screen and redisplay the current line. Otherwise, clear and redisplay the screen.

Current line: Unchanged.

Current column: Unchanged.

Move Up

Synopsis:

[count] <control>-P

[count] k

[count] -

If there are less than count lines before the current line in the edit buffer, it shall be an error.

If used as a motion command:

1.
The text region shall include the starting line and the previous count lines.

2.
Any text copied to a buffer shall be in line mode.

If not used as a motion command:

Current line: Set to current line - count.

Current column: Set to non- <blank> for the - command; otherwise, unchanged.

Redraw Screen

Synopsis:

<control>-R

If any lines have been deleted from the display screen and flagged as deleted on the terminal using the @ convention (see the beginning of the EXTENDED DESCRIPTION section), they shall be redisplayed to match the contents of the edit buffer.

It is unspecified whether lines flagged with @ because they do not fit on the terminal display shall be affected.

Current line: Unchanged.

Current column: Unchanged.

Scroll Backward

Synopsis:

[count] <control>-U

If the current line is the first line of the edit buffer, it shall be an error.

If no count is specified, count shall default to the count associated with the previous <control>-D or <control>-U command. If there was no previous <control>-D or <control>-U command, count shall default to the value of the scroll edit option.

Current line: If count is greater than the current line, set to 1; otherwise, set to the current line - count.

Current column: Set to non- <blank>.

Scroll Backward by Line

Synopsis:

[count] <control>-Y

Display the line count lines before the first line currently displayed.

If the current line is the first line of the edit buffer, it shall be an error. If this calculation would result in a line that is before the first line of the edit buffer, the first line of the display shall display some portion of the first line of the edit buffer.

Current line: Unchanged if the previous current character is displayed; otherwise, set to the first line displayed.

Current column: Unchanged.

Edit the Alternate File

Synopsis:

<control>-^

This command shall be equivalent to the ex edit command, with the alternate pathname as its argument.

Terminate Command or Input Mode

Synopsis:

<ESC>

If a partial vi command (as defined by at least one, non- count character) has been entered, discard the count and the command character(s).

Otherwise, if no command characters have been entered, and the <ESC> was the result of a map expansion, the terminal shall be alerted and the <ESC> character shall be discarded, but it shall not be an error.

Otherwise, it shall be an error.

Current line: Unchanged.

Current column: Unchanged.

Search for tagstring

Synopsis:

<control>-]

If the current character is not a word or <blank>, it shall be an error.

This command shall be equivalent to the ex tag command, with the argument to that command defined as follows.

If the current character is a <blank>:

1.
Skip all <blank>s after the cursor up to the end of the line.

2.
If the end of the line is reached, it shall be an error.

Then, the argument to the ex tag command shall be the current character and all subsequent characters, up to the first non-word character or the end of the line.

Move Cursor Forward

Synopsis:

[count] <space>

[count] l  (ell)

If there are less than count non- <newline>s after the cursor on the current line, count shall be adjusted to the number of non- <newline>s after the cursor on the line.

If used as a motion command:

1.
If the current or countth character after the cursor is the last non- <newline> in the line, the text region shall be comprised of the current character up to and including the last non- <newline> in the line. Otherwise, the text region shall be from the current character up to, but not including, the countth character after the cursor.

2.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

If there are no non- <newline>s after the current character on the current line, it shall be an error.

Current line: Unchanged.

Current column: Set to the last column that displays any portion of the countth character after the current character.

Replace Text with Results from Shell Command

Synopsis:

[count] ! motion shell-commands <newline>

If the motion command is the ! command repeated:

1.
If the edit buffer is empty and no count was supplied, the command shall be the equivalent of the ex :read ! command, with the text input, and no text shall be copied to any buffer.

2.
Otherwise:
a.
If there are less than count -1 lines after the current line in the edit buffer, it shall be an error.

b.
The text region shall be from the current line up to and including the next count -1 lines.

Otherwise, the text region shall be the lines in which any character of the text region specified by the motion command appear.

Any text copied to a buffer shall be in line mode.

This command shall be equivalent to the ex ! command for the specified lines.

Move Cursor to End-of-Line

Synopsis:

[count] $

It shall be an error if there are less than ( count -1) lines after the current line in the edit buffer.

If used as a motion command:

1.
If count is 1:
a.
It shall be an error if the line is empty.

b.
Otherwise, the text region shall consist of all characters from the starting cursor to the last non- <newline> in the line, inclusive, and any text copied to a buffer shall be in character mode.

2.
Otherwise, if the starting cursor position is at or before the first non- <blank> in the line, the text region shall consist of the current and the next count -1 lines, and any text saved to a buffer shall be in line mode.

3.
Otherwise, the text region shall consist of all characters from the starting cursor to the last non- <newline> in the line that is count -1 lines forward from the current line, and any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Set to the current line + count-1.

Current column: The current column is set to the last display line column of the last non- <newline> in the line, or column position 1 if the line is empty.

The current column shall be adjusted to be on the last display line column of the last non- <newline> of the current line as subsequent commands change the current line, until a command changes the current column.

Move to Matching Character

Synopsis:

%

If the character at the current position is not a parenthesis, bracket, or curly brace, search forward in the line to the first one of those characters. If no such character is found, it shall be an error.

The matching character shall be the parenthesis, bracket, or curly brace matching the parenthesis, bracket, or curly brace, respectively, that was at the current position or that was found on the current line.

Matching shall be determined as follows, for an open parenthesis:

1.
Set a counter to 1.

2.
Search forwards until a parenthesis is found or the end of the edit buffer is reached.

3.
If the end of the edit buffer is reached, it shall be an error.

4.
If an open parenthesis is found, increment the counter by 1.

5.
If a close parenthesis is found, decrement the counter by 1.

6.
If the counter is zero, the current character is the matching character.

Matching for a close parenthesis shall be equivalent, except that the search shall be backwards, from the starting character to the beginning of the buffer, a close parenthesis shall increment the counter by 1, and an open parenthesis shall decrement the counter by 1.

Matching for brackets and curly braces shall be equivalent, except that searching shall be done for open and close brackets or open and close curly braces. It is implementation-defined whether other characters are searched for and matched as well.

If used as a motion command:

1.
If the matching cursor was after the starting cursor in the edit buffer, and the starting cursor position was at or before the first non- <blank> non- <newline> in the starting line, and the matching cursor position was at or after the last non- <blank> non- <newline> in the matching line, the text region shall consist of the current line to the matching line, inclusive, and any text copied to a buffer shall be in line mode.

2.
If the matching cursor was before the starting cursor in the edit buffer, and the starting cursor position was at or after the last non- <blank> non- <newline> in the starting line, and the matching cursor position was at or before the first non- <blank> non- <newline> in the matching line, the text region shall consist of the current line to the matching line, inclusive, and any text copied to a buffer shall be in line mode.

3.
Otherwise, the text region shall consist of the starting character to the matching character, inclusive, and any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Set to the line where the matching character is located.

Current column: Set to the last column where any portion of the matching character is displayed.

Repeat Substitution

Synopsis:

&

Repeat the previous substitution command. This command shall be equivalent to the ex & command with the current line as its addresses, and without options, count, or flags.

Return to Previous Context at Beginning of Line

Synopsis:

' character

It shall be an error if there is no line in the edit buffer marked by character.

If used as a motion command:

1.
If the starting cursor is after the marked cursor, then the locations of the starting cursor and the marked cursor in the edit buffer shall be logically swapped.

2.
The text region shall consist of the starting line up to and including the marked line, and any text copied to a buffer shall be in line mode.

If not used as a motion command:

Current line: Set to the line referenced by the mark.

Current column: Set to non- <blank>.

Return to Previous Context

Synopsis:

` character

It shall be an error if the marked line is no longer in the edit buffer. If the marked line no longer contains a character in the saved numbered character position, it shall be as if the marked position is the first non- <blank>.

If used as a motion command:

1.
It shall be an error if the marked cursor references the same character in the edit buffer as the starting cursor.

2.
If the starting cursor is after the marked cursor, then the locations of the starting cursor and the marked cursor in the edit buffer shall be logically swapped.

3.
If the starting line is empty or the starting cursor is at or before the first non- <blank> non- <newline> of the starting line, and the marked cursor line is empty or the marked cursor references the first character of the marked cursor line, the text region shall consist of all lines containing characters from the starting cursor to the line before the marked cursor line, inclusive, and any text copied to a buffer shall be in line mode.

4.
Otherwise, if the marked cursor line is empty or the marked cursor references a character at or before the first non- <blank> non- <newline> of the marked cursor line, the region of text shall be from the starting cursor to the last non- <newline> of the line before the marked cursor line, inclusive, and any text copied to a buffer shall be in character mode.

5.
Otherwise, the region of text shall be from the starting cursor (inclusive), to the marked cursor (exclusive), and any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Set to the line referenced by the mark.

Current column: Set to the last column in which any portion of the character referenced by the mark is displayed.

Return to Previous Section

Synopsis:

[count] [[

Move the cursor backward through the edit buffer to the first character of the previous section boundary, count times.

If used as a motion command:

1.
If the starting cursor was at the first character of the starting line or the starting line was empty, and the first character of the boundary was the first character of the boundary line, the text region shall consist of the current line up to and including the line where the countth next boundary starts, and any text copied to a buffer shall be in line mode.

2.
If the boundary was the last line of the edit buffer or the last non- <newline> of the last line of the edit buffer, the text region shall consist of the last character in the edit buffer up to and including the starting character, and any text saved to a buffer shall be in character mode.

3.
Otherwise, the text region shall consist of the starting character up to but not including the first character in the countth next boundary, and any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Set to the line where the countth next boundary in the edit buffer starts.

Current column: Set to the last column in which any portion of the first character of the countth next boundary is displayed, or column position 1 if the line is empty.

Move to Next Section

Synopsis:

[count] ]]

Move the cursor forward through the edit buffer to the first character of the next section boundary, count times.

If used as a motion command:

1.
If the starting cursor was at the first character of the starting line or the starting line was empty, and the first character of the boundary was the first character of the boundary line, the text region shall consist of the current line up to and including the line where the countth previous boundary starts, and any text copied to a buffer shall be in line mode.

2.
If the boundary was the first line of the edit buffer, the text region shall consist of the first character in the edit buffer up to but not including the starting character, and any text copied to a buffer shall be in character mode.

3.
Otherwise, the text region shall consist of the first character in the countth previous section boundary up to but not including the starting character, and any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Set to the line where the countth previous boundary in the edit buffer starts.

Current column: Set to the last column in which any portion of the first character of the countth previous boundary is displayed, or column position 1 if the line is empty.

Move to First Non-<blank> Position on Current Line

Synopsis:

^

If used as a motion command:

1.
If the line has no non- <blank> non- <newline>s, or if the cursor is at the first non- <blank> non- <newline> of the line, it shall be an error.

2.
If the cursor is before the first non- <blank> non- <newline> of the line, the text region shall be comprised of the current character, up to, but not including, the first non- <blank> non- <newline> of the line.

3.
If the cursor is after the first non- <blank> non- <newline> of the line, the text region shall be from the character before the starting cursor up to and including the first non- <blank> non- <newline> of the line.

4.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: Set to non- <blank>.

Current and Line Above

Synopsis:

[count] _

If there are less than count -1 lines after the current line in the edit buffer, it shall be an error.

If used as a motion command:

1.
If count is less than 2, the text region shall be the current line.

2.
Otherwise, the text region shall include the starting line and the next count -1 lines.

3.
Any text copied to a buffer shall be in line mode.

If not used as a motion command:

Current line: Set to current line + count -1.

Current column: Set to non- <blank>.

Move Back to Beginning of Sentence

Synopsis:

[count] (

Move backward to the beginning of a sentence. This command shall be equivalent to the [[ command, with the exception that sentence boundaries shall be used instead of section boundaries.

Move Forward to Beginning of Sentence

Synopsis:

[count] )

Move forward to the beginning of a sentence. This command shall be equivalent to the ]] command, with the exception that sentence boundaries shall be used instead of section boundaries.

Move Back to Preceding Paragraph

Synopsis:

[count] {

Move back to the beginning of the preceding paragraph. This command shall be equivalent to the [[ command, with the exception that paragraph boundaries shall be used instead of section boundaries.

Move Forward to Next Paragraph

Synopsis:

[count] }

Move forward to the beginning of the next paragraph. This command shall be equivalent to the ]] command, with the exception that paragraph boundaries shall be used instead of section boundaries.

Move to Specific Column Position

Synopsis:

[count] |

For the purposes of this command, lines that are too long for the current display and that have been folded shall be treated as having a single, 1-based, number of columns.

If there are less than count columns in which characters from the current line are displayed on the screen, count shall be adjusted to be the last column in which any portion of the line is displayed on the screen.

If used as a motion command:

1.
If the line is empty, or the cursor character is the same as the character on the countth column of the line, it shall be an error.

2.
If the cursor is before the countth column of the line, the text region shall be comprised of the current character, up to but not including the character on the countth column of the line.

3.
If the cursor is after the countth column of the line, the text region shall be from the character before the starting cursor up to and including the character on the countth column of the line.

4.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: Set to the last column in which any portion of the character that is displayed in the count column of the line is displayed.

Reverse Find Character

Synopsis:

[count] ,

If the last F, f, T, or t command was F, f, T, or t, this command shall be equivalent to an f, F, t, or T command, respectively, with the specified count and the same search character.

If there was no previous F, f, T, or t command, it shall be an error.

Repeat

Synopsis:

[count] .

Repeat the last !, <, >, A, C, D, I, J, O, P, R, S, X, Y, a, c, d, i, o, p, r, s, x, y, or ~ command. It shall be an error if none of these commands have been executed. Commands (other than commands that enter text input mode) executed as a result of map expansions, shall not change the value of the last repeatable command.

Repeated commands with associated motion commands shall repeat the motion command as well; however, any specified count shall replace the count(s) that were originally specified to the repeated command or its associated motion command.

If the motion component of the repeated command is f, F, t, or T, the repeated command shall not set the remembered search character for the ; and , commands.

If the repeated command is p or P, and the buffer associated with that command was a numeric buffer named with a number less than 9, the buffer associated with the repeated command shall be set to be the buffer named by the name of the previous buffer logically incremented by 1.

If the repeated character is a text input command, the input text associated with that command is repeated literally:

*
Input characters are neither macro or abbreviation-expanded.

*
Input characters are not interpreted in any special way with the exception that <newline>, <carriage-return>, and <control>-T behave as described in Input Mode Commands in vi .

Current line: Set as described for the repeated command.

Current column: Set as described for the repeated command.

Find Regular Expression

Synopsis:

/

If the input line contains no non- <newline>s, it shall be equivalent to a line containing only the last regular expression encountered. The enhanced regular expressions supported by vi are described in Regular Expressions in ex .

Otherwise, the line shall be interpreted as one or more regular expressions, optionally followed by an address offset or a vi z command.

If the regular expression is not the last regular expression on the line, or if a line offset or z command is specified, the regular expression shall be terminated by an unescaped '/' character, which shall not be used as part of the regular expression. If the regular expression is not the first regular expression on the line, it shall be preceded by zero or more <blank>s, a semicolon, zero or more <blank>s, and a leading '/' character, which shall not be interpreted as part of the regular expression. It shall be an error to precede any regular expression with any characters other than these.

Each search shall begin from the character after the first character of the last match (or, if it is the first search, after the cursor). If the wrapscan edit option is set, the search shall continue to the character before the starting cursor character; otherwise, to the end of the edit buffer. It shall be an error if any search fails to find a match, and an informational message to this effect shall be displayed.

An optional address offset (see Addressing in ex ) can be specified after the last regular expression by including a trailing '/' character after the regular expression and specifying the address offset. This offset will be from the line containing the match for the last regular expression specified. It shall be an error if the line offset would indicate a line address less than 1 or greater than the last line in the edit buffer. An address offset of zero shall be supported. It shall be an error to follow the address offset with any other characters than <blank>s.

If not used as a motion command, an optional z command (see Redraw Window ) can be specified after the last regular expression by including a trailing '/' character after the regular expression, zero or more <blank>s, a 'z' , zero or more <blank>s, an optional new window edit option value, zero or more <blank>s, and a location character. The effect shall be as if the z command was executed after the / command. It shall be an error to follow the z command with any other characters than <blank>s.

The remembered search direction shall be set to forward.

If used as a motion command:

1.
It shall be an error if the last match references the same character in the edit buffer as the starting cursor.

2.
If any address offset is specified, the last match shall be adjusted by the specified offset as described previously.

3.
If the starting cursor is after the last match, then the locations of the starting cursor and the last match in the edit buffer shall be logically swapped.

4.
If any address offset is specified, the text region shall consist of all lines containing characters from the starting cursor to the last match line, inclusive, and any text copied to a buffer shall be in line mode.

5.
Otherwise, if the starting line is empty or the starting cursor is at or before the first non- <blank> non- <newline> of the starting line, and the last match line is empty or the last match starts at the first character of the last match line, the text region shall consist of all lines containing characters from the starting cursor to the line before the last match line, inclusive, and any text copied to a buffer shall be in line mode.

6.
Otherwise, if the last match line is empty or the last match begins at a character at or before the first non- <blank> non- <newline> of the last match line, the region of text shall be from the current cursor to the last non- <newline> of the line before the last match line, inclusive, and any text copied to a buffer shall be in character mode.

7.
Otherwise, the region of text shall be from the current cursor (inclusive), to the first character of the last match (exclusive), and any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: If a match is found, set to the last matched line plus the address offset, if any; otherwise, unchanged.

Current column: Set to the last column on which any portion of the first character in the last matched string is displayed, if a match is found; otherwise, unchanged.

Move to First Character in Line

Synopsis:

0  (zero)

Move to the first character on the current line. The character '0' shall not be interpreted as a command if it is immediately preceded by a digit.

If used as a motion command:

1.
If the cursor character is the first character in the line, it shall be an error.

2.
The text region shall be from the character before the cursor character up to and including the first character in the line.

3.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: The last column in which any portion of the first character in the line is displayed, or if the line is empty, unchanged.

Execute an ex Command

Synopsis:

:

Execute one or more ex commands.

If any portion of the screen other than the last line of the screen was overwritten by any ex command (except shell), vi shall display a message indicating that it is waiting for an input from the user, and shall then read a character. This action may also be taken for other, unspecified reasons.

If the next character entered is a ':' , another ex command shall be accepted and executed. Any other character shall cause the screen to be refreshed and vi shall return to command mode.

Current line: As specified for the ex command.

Current column: As specified for the ex command.

Repeat Find

Synopsis:

[count] ;

This command shall be equivalent to the last F, f, T, or t command, with the specified count, and with the same search character used for the last F, f, T, or t command. If there was no previous F, f, T, or t command, it shall be an error.

Shift Left

Synopsis:

[count] < motion

If the motion command is the < command repeated:

1.
If there are less than count -1 lines after the current line in the edit buffer, it shall be an error.

2.
The text region shall be from the current line, up to and including the next count -1 lines.

Shift any line in the text region specified by the count and motion command one shiftwidth (see the ex shiftwidth option) toward the start of the line, as described by the ex < command. The unshifted lines shall be copied to the unnamed buffer in line mode.

Current line: If the motion was from the current cursor position toward the end of the edit buffer, unchanged. Otherwise, set to the first line in the edit buffer that is part of the text region specified by the motion command.

Current column: Set to non- <blank>.

Shift Right

Synopsis:

[count] > motion

If the motion command is the > command repeated:

1.
If there are less than count -1 lines after the current line in the edit buffer, it shall be an error.

2.
The text region shall be from the current line, up to and including the next count -1 lines.

Shift any line with characters in the text region specified by the count and motion command one shiftwidth (see the ex shiftwidth option) away from the start of the line, as described by the ex > command. The unshifted lines shall be copied into the unnamed buffer in line mode.

Current line: If the motion was from the current cursor position toward the end of the edit buffer, unchanged. Otherwise, set to the first line in the edit buffer that is part of the text region specified by the motion command.

Current column: Set to non- <blank>.

Scan Backwards for Regular Expression

Synopsis:

?

Scan backwards; the ? command shall be equivalent to the / command (see Find Regular Expression ) with the following exceptions:

1.
The input prompt shall be a '?' .

2.
Each search shall begin from the character before the first character of the last match (or, if it is the first search, the character before the cursor character).

3.
The search direction shall be from the cursor toward the beginning of the edit buffer, and the wrapscan edit option shall affect whether the search wraps to the end of the edit buffer and continues.

4.
The remembered search direction shall be set to backward.

Execute

Synopsis:

@buffer

If the buffer is specified as @, the last buffer executed shall be used. If no previous buffer has been executed, it shall be an error.

Behave as if the contents of the named buffer were entered as standard input. After each line of a line-mode buffer, and all but the last line of a character mode buffer, behave as if a <newline> were entered as standard input.

If an error occurs during this process, an error message shall be written, and no more characters resulting from the execution of this command shall be processed.

If a count is specified, behave as if that count were entered as user input before the characters from the @ buffer were entered.

Current line: As specified for the individual commands.

Current column: As specified for the individual commands.

Reverse Case

Synopsis:

[count] ~

Reverse the case of the current character and the next count -1 characters, such that lowercase characters that have uppercase counterparts shall be changed to uppercase characters, and uppercase characters that have lowercase counterparts shall be changed to lowercase characters, as prescribed by the current locale. No other characters shall be affected by this command.

If there are less than count -1 characters after the cursor in the edit buffer, count shall be adjusted to the number of characters after the cursor in the edit buffer minus 1.

For the purposes of this command, the next character after the last non- <newline> on the line shall be the next character in the edit buffer.

Current line: Set to the line including the ( count-1)th character after the cursor.

Current column: Set to the last column in which any portion of the ( count-1)th character after the cursor is displayed.

Append

Synopsis:

[count] a

Enter text input mode after the current cursor position. No characters already in the edit buffer shall be affected by this command. A count shall cause the input text to be appended count -1 more times to the end of the input.

Current line/column: As specified for the text input commands (see Input Mode Commands in vi ).

Append at End-of-Line

Synopsis:

[count] A

This command shall be equivalent to the vi command:

$ [ count ] a

(see Append ).

Move Backward to Preceding Word

Synopsis:

[count] b

With the exception that words are used as the delimiter instead of bigwords, this command shall be equivalent to the B command.

Move Backward to Preceding Bigword

Synopsis:

[count] B

If the edit buffer is empty or the cursor is on the first character of the edit buffer, it shall be an error. If less than count bigwords begin between the cursor and the start of the edit buffer, count shall be adjusted to the number of bigword beginnings between the cursor and the start of the edit buffer.

If used as a motion command:

1.
The text region shall be from the first character of the countth previous bigword beginning up to but not including the cursor character.

2.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Set to the line containing the current column.

Current column: Set to the last column upon which any part of the first character of the countth previous bigword is displayed.

Change

Synopsis:

[buffer][count] c motion

If the motion command is the c command repeated:

1.
The buffer text shall be in line mode.

2.
If there are less than count -1 lines after the current line in the edit buffer, it shall be an error.

3.
The text region shall be from the current line up to and including the next count -1 lines.

Otherwise, the buffer text mode and text region shall be as specified by the motion command.

The replaced text shall be copied into buffer, if specified, and into the unnamed buffer. If the text to be replaced contains characters from more than a single line, or the buffer text is in line mode, the replaced text shall be copied into the numeric buffers as well.

If the buffer text is in line mode:

1.
Any lines that contain characters in the region shall be deleted, and the editor shall enter text input mode at the beginning of a new line which shall replace the first line deleted.

2.
If the autoindent edit option is set, autoindent characters equal to the autoindent characters on the first line deleted shall be inserted as if entered by the user.

Otherwise, if characters from more than one line are in the region of text:

1.
The text shall be deleted.

2.
Any text remaining in the last line in the text region shall be appended to the first line in the region, and the last line in the region shall be deleted.

3.
The editor shall enter text input mode after the last character not deleted from the first line in the text region, if any; otherwise, on the first column of the first line in the region.

Otherwise:

1.
If the glyph for '$' is smaller than the region, the end of the region shall be marked with a '$' .

2.
The editor shall enter text input mode, overwriting the region of text.

Current line/column: As specified for the text input commands (see Input Mode Commands in vi ).

Change to End-of-Line

Synopsis:

[buffer][count] C

This command shall be equivalent to the vi command:

[buffer][count] c$

See the c command.

Delete

Synopsis:

[buffer][count] d motion

If the motion command is the d command repeated:

1.
The buffer text shall be in line mode.

2.
If there are less than count -1 lines after the current line in the edit buffer, it shall be an error.

3.
The text region shall be from the current line up to and including the next count -1 lines.

Otherwise, the buffer text mode and text region shall be as specified by the motion command.

If in open mode, and the current line is deleted, and the line remains on the display, an '@' character shall be displayed as the first glyph of that line.

Delete the region of text into buffer, if specified, and into the unnamed buffer. If the text to be deleted contains characters from more than a single line, or the buffer text is in line mode, the deleted text shall be copied into the numeric buffers, as well.

Current line: Set to the first text region line that appears in the edit buffer, unless that line has been deleted, in which case it shall be set to the last line in the edit buffer, or line 1 if the edit buffer is empty.

Current column:

1.
If the line is empty, set to column position 1.

2.
Otherwise, if the buffer text is in line mode or the motion was from the cursor toward the end of the edit buffer:
a.
If a character from the current line is displayed in the current column, set to the last column that displays any portion of that character.

b.
Otherwise, set to the last column in which any portion of any character in the line is displayed.

3.
Otherwise, if a character is displayed in the column that began the text region, set to the last column that displays any portion of that character.

4.
Otherwise, set to the last column in which any portion of any character in the line is displayed.

Delete to End-of-Line

Synopsis:

[buffer] D

Delete the text from the current position to the end of the current line; equivalent to the vi command:

[buffer] d$

Move to End-of-Word

Synopsis:

[count] e

With the exception that words are used instead of bigwords as the delimiter, this command shall be equivalent to the E command.

Move to End-of-Bigword

Synopsis:

[count] E

If the edit buffer is empty it shall be an error. If less than count bigwords end between the cursor and the end of the edit buffer, count shall be adjusted to the number of bigword endings between the cursor and the end of the edit buffer.

If used as a motion command:

1.
The text region shall be from the last character of the countth next bigword up to and including the cursor character.

2.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Set to the line containing the current column.

Current column: Set to the last column upon which any part of the last character of the countth next bigword is displayed.

Find Character in Current Line (Forward)

Synopsis:

[count] f character

It shall be an error if count occurrences of the character do not occur after the cursor in the line.

If used as a motion command:

1.
The text range shall be from the cursor character up to and including the countth occurrence of the specified character after the cursor.

2.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: Set to the last column in which any portion of the countth occurrence of the specified character after the cursor appears in the line.

Find Character in Current Line (Reverse)

Synopsis:

[count] F character

It shall be an error if count occurrences of the character do not occur before the cursor in the line.

If used as a motion command:

1.
The text region shall be from the countth occurrence of the specified character before the cursor, up to, but not including the cursor character.

2.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: Set to the last column in which any portion of the countth occurrence of the specified character before the cursor appears in the line.

Move to Line

Synopsis:

[count] G

If count is not specified, it shall default to the last line of the edit buffer. If count is greater than the last line of the edit buffer, it shall be an error.

If used as a motion command:

1.
The text region shall be from the cursor line up to and including the specified line.

2.
Any text copied to a buffer shall be in line mode.

If not used as a motion command:

Current line: Set to count if count is specified; otherwise, the last line.

Current column: Set to non- <blank>.

Move to Top of Screen

Synopsis:

[count] H

If the beginning of the line count greater than the first line of which any portion appears on the display does not exist, it shall be an error.

If used as a motion command:

1.
If in open mode, the text region shall be the current line.

2.
Otherwise, the text region shall be from the starting line up to and including (the first line of the display + count -1).

3.
Any text copied to a buffer shall be in line mode.

If not used as a motion command:

If in open mode, this command shall set the current column to non- <blank> and do nothing else.

Otherwise, it shall set the current line and current column as follows.

Current line: Set to (the first line of the display + count -1).

Current column: Set to non- <blank>.

Insert Before Cursor

Synopsis:

[count] i

Enter text input mode before the current cursor position. No characters already in the edit buffer shall be affected by this command. A count shall cause the input text to be appended count -1 more times to the end of the input.

Current line/column: As specified for the text input commands (see Input Mode Commands in vi ).

Insert at Beginning of Line

Synopsis:

[count] I

This command shall be equivalent to the vi command ^[ count] i.

Join

Synopsis:

[count] J

If the current line is the last line in the edit buffer, it shall be an error.

This command shall be equivalent to the ex join command with no addresses, and an ex command count value of 1 if count was not specified or if a count of 1 was specified, and an ex command count value of count -1 for any other value of count, except that the current line and column shall be set as follows.

Current line: Unchanged.

Current column: The last column in which any portion of the character following the last character in the initial line is displayed, or the last non- <newline> in the line if no characters were appended.

Move to Bottom of Screen

Synopsis:

[count] L

If the beginning of the line count less than the last line of which any portion appears on the display does not exist, it shall be an error.

If used as a motion command:

1.
If in open mode, the text region shall be the current line.

2.
Otherwise, the text region shall include all lines from the starting cursor line to (the last line of the display -( count -1)).

3.
Any text copied to a buffer shall be in line mode.

If not used as a motion command:

1.
If in open mode, this command shall set the current column to non- <blank> and do nothing else.

2.
Otherwise, it shall set the current line and current column as follows.

Current line: Set to (the last line of the display -( count -1)).

Current column: Set to non- <blank>.

Mark Position

Synopsis:

m letter

This command shall be equivalent to the ex mark command with the specified character as an argument.

Move to Middle of Screen

Synopsis:

M

The middle line of the display shall be calculated as follows:

(the top line of the display) + (((number of lines displayed) +1) /2) -1

If used as a motion command:

1.
If in open mode, the text region shall be the current line.

2.
Otherwise, the text region shall include all lines from the starting cursor line up to and including the middle line of the display.

3.
Any text copied to a buffer shall be in line mode.

If not used as a motion command:

If in open mode, this command shall set the current column to non- <blank> and do nothing else.

Otherwise, it shall set the current line and current column as follows.

Current line: Set to the middle line of the display.

Current column: Set to non- <blank>.

Repeat Regular Expression Find (Forward)

Synopsis:

n

If the remembered search direction was forward, the n command shall be equivalent to the vi / command with no characters entered by the user. Otherwise, it shall be equivalent to the vi ? command with no characters entered by the user.

If the n command is used as a motion command for the ! command, the editor shall not enter text input mode on the last line on the screen, and shall behave as if the user entered a single '!' character as the text input.

Repeat Regular Expression Find (Reverse)

Synopsis:

N

Scan for the next match of the last pattern given to / or ?, but in the reverse direction; this is the reverse of n.

If the remembered search direction was forward, the N command shall be equivalent to the vi ? command with no characters entered by the user. Otherwise, it shall be equivalent to the vi / command with no characters entered by the user. If the N command is used as a motion command for the ! command, the editor shall not enter text input mode on the last line on the screen, and shall behave as if the user entered a single ! character as the text input.

Insert Empty Line Below

Synopsis:

o

Enter text input mode in a new line appended after the current line. A count shall cause the input text to be appended count -1 more times to the end of the already added text, each time starting on a new, appended line.

Current line/column: As specified for the text input commands (see Input Mode Commands in vi ).

Insert Empty Line Above

Synopsis:

O

Enter text input mode in a new line inserted before the current line. A count shall cause the input text to be appended count -1 more times to the end of the already added text, each time starting on a new, appended line.

Current line/column: As specified for the text input commands (see Input Mode Commands in vi ).

Put from Buffer Following

Synopsis:

[buffer] p

If no buffer is specified, the unnamed buffer shall be used.

If the buffer text is in line mode, the text shall be appended below the current line, and each line of the buffer shall become a new line in the edit buffer. A count shall cause the buffer text to be appended count -1 more times to the end of the already added text, each time starting on a new, appended line.

If the buffer text is in character mode, the text shall be appended into the current line after the cursor, and each line of the buffer other than the first and last shall become a new line in the edit buffer. A count shall cause the buffer text to be appended count -1 more times to the end of the already added text, each time starting after the last added character.

Current line: If the buffer text is in line mode, set the line to line +1; otherwise, unchanged.

Current column: If the buffer text is in line mode:

1.
If there is a non- <blank> in the first line of the buffer, set to the last column on which any portion of the first non- <blank> in the line is displayed.

2.
If there is no non- <blank> in the first line of the buffer, set to the last column on which any portion of the last non- <newline> in the first line of the buffer is displayed.

If the buffer text is in character mode:

1.
If the text in the buffer is from more than a single line, then set to the last column on which any portion of the first character from the buffer is displayed.

2.
Otherwise, if the buffer is the unnamed buffer, set to the last column on which any portion of the last character from the buffer is displayed.

3.
Otherwise, set to the first column on which any portion of the first character from the buffer is displayed.

Put from Buffer Before

Synopsis:

[buffer] P

If no buffer is specified, the unnamed buffer shall be used.

If the buffer text is in line mode, the text shall be inserted above the current line, and each line of the buffer shall become a new line in the edit buffer. A count shall cause the buffer text to be appended count -1 more times to the end of the already added text, each time starting on a new, appended line.

If the buffer text is in character mode, the text shall be inserted into the current line before the cursor, and each line of the buffer other than the first and last shall become a new line in the edit buffer. A count shall cause the buffer text to be appended count -1 more times to the end of the already added text, each time starting after the last added character.

Current line: Unchanged.

Current column: If the buffer text is in line mode:

1.
If there is a non- <blank> in the first line of the buffer, set to the last column on which any portion of that character is displayed.

2.
If there is no non- <blank> in the first line of the buffer, set to the last column on which any portion of the last non- <newline> in the first line of the buffer is displayed.

If the buffer text is in character mode:

1.
If the buffer is the unnamed buffer, set to the last column on which any portion of the last character from the buffer is displayed.

2.
Otherwise, set to the first column on which any portion of the first character from the buffer is displayed.

Enter ex Mode

Synopsis:

Q

Leave visual or open mode and enter ex command mode.

Current line: Unchanged.

Current column: Unchanged.

Replace Character

Synopsis:

[count] r character

Replace the count characters at and after the cursor with the specified character. If there are less than count non- <newline>s at and after the cursor on the line, it shall be an error.

If character is <control>-V, any next character other than the <newline> shall be stripped of any special meaning and used as a literal character.

If character is <ESC>, no replacement shall be made and the current line and current column shall be unchanged.

If character is <carriage-return> or <newline>, count new lines shall be appended to the current line. All but the last of these lines shall be empty. count characters at and after the cursor shall be discarded, and any remaining characters after the cursor in the current line shall be moved to the last of the new lines. If the autoindent edit option is set, they shall be preceded by the same number of autoindent characters found on the line from which the command was executed.

Current line: Unchanged unless the replacement character is a <carriage-return> or <newline>, in which case it shall be set to line + count.

Current column: Set to the last column position on which a portion of the last replaced character is displayed, or if the replacement character caused new lines to be created, set to non- <blank>.

Replace Characters

Synopsis:

R

Enter text input mode at the current cursor position possibly replacing text on the current line. A count shall cause the input text to be appended count -1 more times to the end of the input.

Current line/column: As specified for the text input commands (see Input Mode Commands in vi ).

Substitute Character

Synopsis:

[buffer][count] s

This command shall be equivalent to the vi command:

[buffer][count] c<space>

Substitute Lines

Synopsis:

[buffer][count] S

This command shall be equivalent to the vi command:

[buffer][count] c_

Move Cursor to Before Character (Forward)

Synopsis:

[count] t character

It shall be an error if count occurrences of the character do not occur after the cursor in the line.

If used as a motion command:

1.
The text region shall be from the cursor up to but not including the countth occurrence of the specified character after the cursor.

2.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: Set to the last column in which any portion of the character before the countth occurrence of the specified character after the cursor appears in the line.

Move Cursor to After Character (Reverse)

Synopsis:

[count] T character

It shall be an error if count occurrences of the character do not occur before the cursor in the line.

If used as a motion command:

1.
If the character before the cursor is the specified character, it shall be an error.

2.
The text region shall be from the character before the cursor up to but not including the countth occurrence of the specified character before the cursor.

3.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

Current line: Unchanged.

Current column: Set to the last column in which any portion of the character after the countth occurrence of the specified character before the cursor appears in the line.

Undo

Synopsis:

u

This command shall be equivalent to the ex undo command except that the current line and current column shall be set as follows:

Current line: Set to the first line added or changed if any; otherwise, move to the line preceding any deleted text if one exists; otherwise, move to line 1.

Current column: If undoing an ex command, set to the first non- <blank>.

Otherwise, if undoing a text input command:

1.
If the command was a C, c, O, o, R, S, or s command, the current column shall be set to the value it held when the text input command was entered.

2.
Otherwise, set to the last column in which any portion of the first character after the deleted text is displayed, or, if no non- <newline>s follow the text deleted from this line, set to the last column in which any portion of the last non- <newline> in the line is displayed, or 1 if the line is empty.

Otherwise, if a single line was modified (that is, not added or deleted) by the u command:

1.
If text was added or changed, set to the last column in which any portion of the first character added or changed is displayed.

2.
If text was deleted, set to the last column in which any portion of the first character after the deleted text is displayed, or, if no non- <newline>s follow the deleted text, set to the last column in which any portion of the last non- <newline> in the line is displayed, or 1 if the line is empty.

Otherwise, set to non- <blank>.

Undo Current Line

Synopsis:

U

Restore the current line to its state immediately before the most recent time that it became the current line.

Current line: Unchanged.

Current column: Set to the first column in the line in which any portion of the first character in the line is displayed.

Move to Beginning of Word

Synopsis:

[count] w

With the exception that words are used as the delimiter instead of bigwords, this command shall be equivalent to the W command.

Move to Beginning of Bigword

Synopsis:

[count] W

If the edit buffer is empty, it shall be an error. If there are less than count bigwords between the cursor and the end of the edit buffer, count shall be adjusted to move the cursor to the last bigword in the edit buffer.

If used as a motion command:

1.
If the associated command is c, count is 1, and the cursor is on a <blank>, the region of text shall be the current character and no further action shall be taken.

2.
If there are less than count bigwords between the cursor and the end of the edit buffer, then the command shall succeed, and the region of text shall include the last character of the edit buffer.

3.
If there are <blank>s or an end-of-line that precede the countth bigword, and the associated command is c, the region of text shall be up to and including the last character before the preceding <blank>s or end-of-line.

4.
If there are <blank>s or an end-of-line that precede the bigword, and the associated command is d or y, the region of text shall be up to and including the last <blank> before the start of the bigword or end-of-line.

5.
Any text copied to a buffer shall be in character mode.

If not used as a motion command:

1.
If the cursor is on the last character of the edit buffer, it shall be an error.

Current line: Set to the line containing the current column.

Current column: Set to the last column in which any part of the first character of the countth next bigword is displayed.

Delete Character at Cursor

Synopsis:

[buffer][count] x

Delete the count characters at and after the current character into buffer, if specified, and into the unnamed buffer.

If the line is empty, it shall be an error. If there are less than count non- <newline>s at and after the cursor on the current line, count shall be adjusted to the number of non- <newline>s at and after the cursor.

Current line: Unchanged.

Current column: If the line is empty, set to column position 1. Otherwise, if there were count or less non- <newline>s at and after the cursor on the current line, set to the last column that displays any part of the last non- <newline> of the line. Otherwise, unchanged.

Delete Character Before Cursor

Synopsis:

[buffer][count] X

Delete the count characters before the current character into buffer, if specified, and into the unnamed buffer.

If there are no characters before the current character on the current line, it shall be an error. If there are less than count previous characters on the current line, count shall be adjusted to the number of previous characters on the line.

Current line: Unchanged.

Current column: Set to (current column - the width of the deleted characters).

Yank

Synopsis:

[buffer][count] y motion

Copy (yank) the region of text into buffer, if specified, and into the unnamed buffer.

If the motion command is the y command repeated:

1.
The buffer shall be in line mode.

2.
If there are less than count -1 lines after the current line in the edit buffer, it shall be an error.

3.
The text region shall be from the current line up to and including the next count -1 lines.

Otherwise, the buffer text mode and text region shall be as specified by the motion command.

Current line: If the motion was from the current cursor position toward the end of the edit buffer, unchanged. Otherwise, set to the first line in the edit buffer that is part of the text region specified by the motion command.

Current column:

1.
If the motion was from the current cursor position toward the end of the edit buffer, unchanged.

2.
Otherwise, if the current line is empty, set to column position 1.

3.
Otherwise, set to the last column that displays any part of the first character in the file that is part of the text region specified by the motion command.

Yank Current Line

Synopsis:

[buffer][count] Y

This command shall be equivalent to the vi command:

[buffer][count] y_

Redraw Window

If in open mode, the z command shall have the Synopsis:

Synopsis:

[count] z

If count is not specified, it shall default to the window edit option -1. The z command shall be equivalent to the ex z command, with a type character of = and a count of count -2, except that the current line and current column shall be set as follows, and the window edit option shall not be affected. If the calculation for the count argument would result in a negative number, the count argument to the ex z command shall be zero. A blank line shall be written after the last line is written.

Current line: Unchanged.

Current column: Unchanged.

If not in open mode, the z command shall have the following Synopsis:

Synopsis:

[line] z [count] character

If line is not specified, it shall default to the current line. If line is specified, but is greater than the number of lines in the edit buffer, it shall default to the number of lines in the edit buffer.

If count is specified, the value of the window edit option shall be set to count (as described in the ex window command), and the screen shall be redrawn.

line shall be placed as specified by the following characters:

<newline>, <carriage-return>

Place the beginning of the line on the first line of the display.

.
Place the beginning of the line in the center of the display. The middle line of the display shall be calculated as described for the M command.
-
Place an unspecified portion of the line on the last line of the display.
+
If line was specified, equivalent to the <newline> case. If line was not specified, display a screen where the first line of the display shall be (current last line) +1. If there are no lines after the last line in the display, it shall be an error.
^
If line was specified, display a screen where the last line of the display shall contain an unspecified portion of the first line of a display that had an unspecified portion of the specified line on the last line of the display. If this calculation results in a line before the beginning of the edit buffer, display the first screen of the edit buffer.

Otherwise, display a screen where the last line of the display shall contain an unspecified portion of (current first line -1). If this calculation results in a line before the beginning of the edit buffer, it shall be an error.

Current line: If line and the '^' character were specified:

1.
If the first screen was displayed as a result of the command attempting to display lines before the beginning of the edit buffer: if the first screen was already displayed, unchanged; otherwise, set to (current first line -1).

2.
Otherwise, set to the last line of the display.

If line and the '+' character were specified, set to the first line of the display.

Otherwise, if line was specified, set to line.

Otherwise, unchanged.

Current column: Set to non- <blank>.

Exit

Synopsis:

ZZ

This command shall be equivalent to the ex xit command with no addresses, trailing !, or filename (see the ex xit command).

Input Mode Commands in vi

In text input mode, the current line shall consist of zero or more of the following categories, plus the terminating <newline>:

1.
Characters preceding the text input entry point

Characters in this category shall not be modified during text input mode.

2.
autoindent characters

autoindent characters shall be automatically inserted into each line that is created in text input mode, either as a result of entering a <newline> or <carriage-return> while in text input mode, or as an effect of the command itself; for example, O or o (see the ex autoindent command), as if entered by the user.

It shall be possible to erase autoindent characters with the <control>-D command; it is unspecified whether they can be erased by <control>-H, <control>-U, and <control>-W characters. Erasing any autoindent character turns the glyph into erase-columns and deletes the character from the edit buffer, but does not change its representation on the screen.

3.
Text input characters

Text input characters are the characters entered by the user. Erasing any text input character turns the glyph into erase-columns and deletes the character from the edit buffer, but does not change its representation on the screen.

Each text input character entered by the user (that does not have a special meaning) shall be treated as follows:

a.
The text input character shall be appended to the last character in the edit buffer from the first, second, or third categories.

b.
If there are no erase-columns on the screen, the text input command was the R command, and characters in the fifth category from the original line follow the cursor, the next such character shall be deleted from the edit buffer. If the slowopen edit option is not set, the corresponding glyph on the screen shall become erase-columns.

c.
If there are erase-columns on the screen, as many columns as they occupy, or as are necessary, shall be overwritten to display the text input character. (If only part of a multi-column glyph is overwritten, the remainder shall be left on the screen, and continue to be treated as erase-columns; it is unspecified whether the remainder of the glyph is modified in any way.)

d.
If additional display line columns are needed to display the text input character:
1.
If the slowopen edit option is set, the text input characters shall be displayed on subsequent display line columns, overwriting any characters displayed in those columns.

2.
Otherwise, any characters currently displayed on or after the column on the display line where the text input character is to be displayed shall be pushed ahead the number of display line columns necessary to display the rest of the text input character.

4.
Erase-columns

Erase-columns are not logically part of the edit buffer, appearing only on the screen, and may be overwritten on the screen by subsequent text input characters. When text input mode ends, all erase-columns shall no longer appear on the screen.

Erase-columns are initially the region of text specified by the c command (see Change ); however, erasing autoindent or text input characters causes the glyphs of the erased characters to be treated as erase-columns.

5.
Characters following the text region for the c command, or the text input entry point for all other commands

Characters in this category shall not be modified during text input mode, except as specified in category 3.b. for the R text input command, or as <blank>s deleted when a <newline> or <carriage-return> is entered.

It is unspecified whether it is an error to attempt to erase past the beginning of a line that was created by the entry of a <newline> or <carriage-return> during text input mode. If it is not an error, the editor shall behave as if the erasing character was entered immediately after the last text input character entered on the previous line, and all of the non- <newline>s on the current line shall be treated as erase-columns.

When text input mode is entered, or after a text input mode character is entered (except as specified for the special characters below), the cursor shall be positioned as follows:

1.
On the first column that displays any part of the first erase-column, if one exists

2.
Otherwise, if the slowopen edit option is set, on the first display line column after the last character in the first, second, or third categories, if one exists

3.
Otherwise, the first column that displays any part of the first character in the fifth category, if one exists

4.
Otherwise, the display line column after the last character in the first, second, or third categories, if one exists

5.
Otherwise, on column position 1

The characters that are updated on the screen during text input mode are unspecified, other than that the last text input character shall always be updated, and, if the slowopen edit option is not set, the current cursor character shall always be updated.

The following specifications are for command characters entered during text input mode.

NUL

Synopsis:

NUL

If the first character of the text input is a NUL, the most recently input text shall be input as if entered by the user, and then text input mode shall be exited. The text shall be input literally; that is, characters are neither macro or abbreviation expanded, nor are any characters interpreted in any special manner. It is unspecified whether implementations shall support more than 256 bytes of remembered input text.

<control>-D

Synopsis:

<control>-D

The <control>-D character shall have no special meaning when in text input mode for a line-oriented command (see Command Descriptions in vi ).

This command need not be supported on block-mode terminals.

If the cursor does not follow an autoindent character, or an autoindent character and a '0' or '^' character:

1.
If the cursor is in column position 1, the <control>-D character shall be discarded and no further action taken.

2.
Otherwise, the <control>-D character shall have no special meaning.

If the last input character was a '0' , the cursor shall be moved to column position 1.

Otherwise, if the last input character was a '^' , the cursor shall be moved to column position 1. In addition, the autoindent level for the next input line shall be derived from the same line from which the autoindent level for the current input line was derived.

Otherwise, the cursor shall be moved back to the column after the previous shiftwidth (see the ex shiftwidth command) boundary.

All of the glyphs on columns between the starting cursor position and (inclusively) the ending cursor position shall become erase-columns as described in Input Mode Commands in vi .

Current line: Unchanged.

Current column: Set to 1 if the <control>-D was preceded by a '^' or '0' ; otherwise, set to (column -1) -((column -2) % shiftwidth).

<control>-H

Synopsis:

<control>-H

If in text input mode for a line-oriented command, and there are no characters to erase, text input mode shall be terminated, no further action shall be done for this command, and the current line and column shall be unchanged.

If there are characters other than autoindent characters that have been input on the current line before the cursor, the cursor shall move back one character.

Otherwise, if there are autoindent characters on the current line before the cursor, it is implementation-defined whether the <control>-H command is an error or if the cursor moves back one autoindent character.

Otherwise, if the cursor is in column position 1 and there are previous lines that have been input, it is implementation-defined whether the <control>-H command is an error or if it is equivalent to entering <control>-H after the last input character on the previous input line.

Otherwise, it shall be an error.

All of the glyphs on columns between the starting cursor position and (inclusively) the ending cursor position shall become erase-columns as described in Input Mode Commands in vi .

The current erase character (see stty) shall cause an equivalent action to the <control>-H command, unless the previously inserted character was a backslash, in which case it shall be as if the literal current erase character had been inserted instead of the backslash.

Current line: Unchanged, unless previously input lines are erased, in which case it shall be set to line -1.

Current column: Set to the first column that displays any portion of the character backed up over.

<newline>

Synopsis:

<newline>

<carriage-return>

<control>-J

<control>-M

If input was part of a line-oriented command, text input mode shall be terminated and the command shall continue execution with the input provided.

Otherwise, terminate the current line. If there are no characters other than autoindent characters on the line, all characters on the line shall be discarded. Otherwise, it is unspecified whether the autoindent characters in the line are modified by entering these characters.

Continue text input mode on a new line appended after the current line. If the slowopen edit option is set, the lines on the screen below the current line shall not be pushed down, but the first of them shall be cleared and shall appear to be overwritten. Otherwise, the lines of the screen below the current line shall be pushed down.

If the autoindent edit option is set, an appropriate number of autoindent characters shall be added as a prefix to the line as described by the ex autoindent edit option.

All columns after the cursor that are erase-columns (as described in Input Mode Commands in vi ) shall be discarded.

If the autoindent edit option is set, all <blank>s immediately following the cursor shall be discarded.

All remaining characters after the cursor shall be transferred to the new line, positioned after any autoindent characters.

Current line: Set to current line +1.

Current column: Set to the first column that displays any portion of the first character after the autoindent characters on the new line, if any, or the first column position after the last autoindent character, if any, or column position 1.

<control>-T

Synopsis:

<control>-T

The <control>-T character shall have no special meaning when in text input mode for a line-oriented command (see Command Descriptions in vi ).

This command need not be supported on block-mode terminals.

Behave as if the user entered the minimum number of <blank>s necessary to move the cursor forward to the column position after the next shiftwidth (see the ex shiftwidth command) boundary.

Current line: Unchanged.

Current column: Set to column + shiftwidth - ((column -1) % shiftwidth).

<control>-U

Synopsis:

<control>-U

If there are characters other than autoindent characters that have been input on the current line before the cursor, the cursor shall move to the first character input after the autoindent characters.

Otherwise, if there are autoindent characters on the current line before the cursor, it is implementation-defined whether the <control>-U command is an error or if the cursor moves to the first column position on the line.

Otherwise, if the cursor is in column position 1 and there are previous lines that have been input, it is implementation-defined whether the <control>-U command is an error or if it is equivalent to entering <control>-U after the last input character on the previous input line.

Otherwise, it shall be an error.

All of the glyphs on columns between the starting cursor position and (inclusively) the ending cursor position shall become erase-columns as described in Input Mode Commands in vi .

The current kill character (see stty) shall cause an equivalent action to the <control>-U command, unless the previously inserted character was a backslash, in which case it shall be as if the literal current kill character had been inserted instead of the backslash.

Current line: Unchanged, unless previously input lines are erased, in which case it shall be set to line -1.

Current column: Set to the first column that displays any portion of the last character backed up over.

<control>-V

Synopsis:

<control>-V

<control>-Q

Allow the entry of any subsequent character, other than <control>-J or the <newline>, as a literal character, removing any special meaning that it may have to the editor in text input mode. If a <control>-V or <control>-Q is entered before a <control>-J or <newline>, the <control>-V or <control>-Q character shall be discarded, and the <control>-J or <newline> shall behave as described in the <newline> command character during input mode.

For purposes of the display only, the editor shall behave as if a '^' character was entered, and the cursor shall be positioned as if overwriting the '^' character. When a subsequent character is entered, the editor shall behave as if that character was entered instead of the original <control>-V or <control>-Q character.

Current line: Unchanged.

Current column: Unchanged.

<control>-W

Synopsis:

<control>-W

If there are characters other than autoindent characters that have been input on the current line before the cursor, the cursor shall move back over the last word preceding the cursor (including any <blank>s between the end of the last word and the current cursor); the cursor shall not move to before the first character after the end of any autoindent characters.

Otherwise, if there are autoindent characters on the current line before the cursor, it is implementation-defined whether the <control>-W command is an error or if the cursor moves to the first column position on the line.

Otherwise, if the cursor is in column position 1 and there are previous lines that have been input, it is implementation-defined whether the <control>-W command is an error or if it is equivalent to entering <control>-W after the last input character on the previous input line.

Otherwise, it shall be an error.

All of the glyphs on columns between the starting cursor position and (inclusively) the ending cursor position shall become erase-columns as described in Input Mode Commands in vi .

Current line: Unchanged, unless previously input lines are erased, in which case it shall be set to line -1.

Current column: Set to the first column that displays any portion of the last character backed up over.

<ESC>

Synopsis:

<ESC>

If input was part of a line-oriented command:

1.
If interrupt was entered, text input mode shall be terminated and the editor shall return to command mode. The terminal shall be alerted.

2.
If <ESC> was entered, text input mode shall be terminated and the command shall continue execution with the input provided.

Otherwise, terminate text input mode and return to command mode.

Any autoindent characters entered on newly created lines that have no other non- <newline>s shall be deleted.

Any leading autoindent and <blank>s on newly created lines shall be rewritten to be the minimum number of <blank>s possible.

The screen shall be redisplayed as necessary to match the contents of the edit buffer.

Current line: Unchanged.

Current column:

1.
If there are text input characters on the current line, the column shall be set to the last column where any portion of the last text input character is displayed.

2.
Otherwise, if a character is displayed in the current column, unchanged.

3.
Otherwise, set to column position 1.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

When any error is encountered and the standard input is not a terminal device file, vi shall not write the file or return to command or text input mode, and shall terminate with a non-zero exit status.

Otherwise, when an unrecoverable error is encountered it shall be equivalent to a SIGHUP asynchronous event.

Otherwise, when an error is encountered, the editor shall behave as specified in Command Descriptions in vi .

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

See the RATIONALE for ex for more information on vi. Major portions of the vi utility specification point to ex to avoid inadvertent divergence. While ex and vi have historically been implemented as a single utility, this is not required by IEEE Std 1003.1-2001.

It is recognized that portions of vi would be difficult, if not impossible, to implement satisfactorily on a block-mode terminal, or a terminal without any form of cursor addressing, thus it is not a mandatory requirement that such features should work on all terminals. It is the intention, however, that a vi implementation should provide the full set of capabilities on all terminals capable of supporting them.

Historically, vi exited immediately if the standard input was not a terminal. IEEE Std 1003.1-2001 permits, but does not require, this behavior. An end-of-file condition is not equivalent to an end-of-file character. A common end-of-file character, <control>-D, is historically a vi command.

The text in the STDOUT section reflects the usage of the verb display in this section; some implementations of vi use standard output to write to the terminal, but IEEE Std 1003.1-2001 does not require that to be the case.

Historically, implementations reverted to open mode if the terminal was incapable of supporting full visual mode. IEEE Std 1003.1-2001 requires this behavior. Historically, the open mode of vi behaved roughly equivalently to the visual mode, with the exception that only a single line from the edit buffer (one "buffer line") was kept current at any time. This line was normally displayed on the next-to-last line of a terminal with cursor addressing (and the last line performed its normal visual functions for line-oriented commands and messages). In addition, some few commands behaved differently in open mode than in visual mode. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, ex and vi implementations have expected text to proceed in the usual European/Latin order of left to right, top to bottom. There is no requirement in IEEE Std 1003.1-2001 that this be the case. The specification was deliberately written using words like "before", "after", "first", and "last" in order to permit implementations to support the natural text order of the language.

Historically, lines past the end of the edit buffer were marked with single tilde ( '~' ) characters; that is, if the one-based display was 20 lines in length, and the last line of the file was on line one, then lines 2-20 would contain only a single '~' character.

Historically, the vi editor attempted to display only complete lines at the bottom of the screen (it did display partial lines at the top of the screen). If a line was too long to fit in its entirety at the bottom of the screen, the screen lines where the line would have been displayed were displayed as single '@' characters, instead of displaying part of the line. IEEE Std 1003.1-2001 permits, but does not require, this behavior. Implementations are encouraged to attempt always to display a complete line at the bottom of the screen when doing scrolling or screen positioning by buffer lines.

Historically, lines marked with '@' were also used to minimize output to dumb terminals over slow lines; that is, changes local to the cursor were updated, but changes to lines on the screen that were not close to the cursor were simply marked with an '@' sign instead of being updated to match the current text. IEEE Std 1003.1-2001 permits, but does not require this feature because it is used ever less frequently as terminals become smarter and connections are faster.

Initialization in ex and vi

Historically, vi always had a line in the edit buffer, even if the edit buffer was "empty". For example:

1.
The ex command = executed from visual mode wrote "1" when the buffer was empty.

2.
Writes from visual mode of an empty edit buffer wrote files of a single character (a <newline>), while writes from ex mode of an empty edit buffer wrote empty files.

3.
Put and read commands into an empty edit buffer left an empty line at the top of the edit buffer.

For consistency, IEEE Std 1003.1-2001 does not permit any of these behaviors.

Historically, vi did not always return the terminal to its original modes; for example, ICRNL was modified if it was not originally set. IEEE Std 1003.1-2001 does not permit this behavior.

Command Descriptions in vi

Motion commands are among the most complicated aspects of vi to describe. With some exceptions, the text region and buffer type effect of a motion command on a vi command are described on a case-by-case basis. The descriptions of text regions in IEEE Std 1003.1-2001 are not intended to imply direction; that is, an inclusive region from line n to line n+5 is identical to a region from line n+5 to line n. This is of more than academic interest-movements to marks can be in either direction, and, if the wrapscan option is set, so can movements to search points. Historically, lines are always stored into buffers in text order; that is, from the start of the edit buffer to the end. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, command counts were applied to any associated motion, and were multiplicative to any supplied motion count. For example, 2cw is the same as c2w, and 2c3w is the same as c6w. IEEE Std 1003.1-2001 requires this behavior. Historically, vi commands that used bigwords, words, paragraphs, and sentences as objects treated groups of empty lines, or lines that contained only <blank>s, inconsistently. Some commands treated them as a single entity, while others treated each line separately. For example, the w, W, and B commands treated groups of empty lines as individual words; that is, the command would move the cursor to each new empty line. The e and E commands treated groups of empty lines as a single word; that is, the first use would move past the group of lines. The b command would just beep at the user, or if done from the start of the line as a motion command, fail in unexpected ways. If the lines contained only (or ended with) <blank>s, the w and W commands would just beep at the user, the E and e commands would treat the group as a single word, and the B and b commands would treat the lines as individual words. For consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that all vi commands treat groups of empty or blank lines as a single entity, and that movement through lines ending with <blank>s be consistent with other movements.

Historically, vi documentation indicated that any number of double quotes were skipped after punctuation marks at sentence boundaries; however, implementations only skipped single quotes. IEEE Std 1003.1-2001 requires both to be skipped.

Historically, the first and last characters in the edit buffer were word boundaries. This historical practice is required by IEEE Std 1003.1-2001.

Historically, vi attempted to update the minimum number of columns on the screen possible, which could lead to misleading information being displayed. IEEE Std 1003.1-2001 makes no requirements other than that the current character being entered is displayed correctly, leaving all other decisions in this area up to the implementation.

Historically, lines were arbitrarily folded between columns of any characters that required multiple column positions on the screen, with the exception of tabs, which terminated at the right-hand margin. IEEE Std 1003.1-2001 permits the former and requires the latter. Implementations that do not arbitrarily break lines between columns of characters that occupy multiple column positions should not permit the cursor to rest on a column that does not contain any part of a character.

The historical vi had a problem in that all movements were by buffer lines, not by display or screen lines. This is often the right thing to do; for example, single line movements, such as j or k, should work on buffer lines. Commands like dj, or j., where . is a change command, only make sense for buffer lines. It is not, however, the right thing to do for screen motion or scrolling commands like <control>-D, <control>-F, and H. If the window is fairly small, using buffer lines in these cases can result in completely random motion; for example, 1 <control>-D can result in a completely changed screen, without any overlap. This is clearly not what the user wanted. The problem is even worse in the case of the H, L, and M commands-as they position the cursor at the first non- <blank> of the line, they may all refer to the same location in large lines, and will result in no movement at all.

In addition, if the line is larger than the screen, using buffer lines can make it impossible to display parts of the line-there are not any commands that do not display the beginning of the line in historical vi, and if both the beginning and end of the line cannot be on the screen at the same time, the user suffers. Finally, the page and half-page scrolling commands historically moved to the first non- <blank> in the new line. If the line is approximately the same size as the screen, this is inadequate because the cursor before and after a <control>-D command will refer to the same location on the screen.

Implementations of ex and vi exist that do not have these problems because the relevant commands ( <control>-B, <control>-D, <control>-F, <control>-U, <control>-Y, <control>-E, H, L, and M) operate on display (screen) lines, not (edit) buffer lines.

IEEE Std 1003.1-2001 does not permit this behavior by default because the standard developers believed that users would find it too confusing. However, historical practice has been relaxed. For example, ex and vi historically attempted, albeit sometimes unsuccessfully, to never put part of a line on the last lines of a screen; for example, if a line would not fit in its entirety, no part of the line was displayed, and the screen lines corresponding to the line contained single '@' characters. This behavior is permitted, but not required by IEEE Std 1003.1-2001, so that it is possible for implementations to support long lines in small screens more reasonably without changing the commands to be oriented to the display (instead of oriented to the buffer). IEEE Std 1003.1-2001 also permits implementations to refuse to edit any edit buffer containing a line that will not fit on the screen in its entirety.

The display area (for example, the value of the window edit option) has historically been "grown", or expanded, to display new text when local movements are done in displays where the number of lines displayed is less than the maximum possible. Expansion has historically been the first choice, when the target line is less than the maximum possible expansion value away. Scrolling has historically been the next choice, done when the target line is less than half a display away, and otherwise, the screen was redrawn. There were exceptions, however, in that ex commands generally always caused the screen to be redrawn. IEEE Std 1003.1-2001 does not specify a standard behavior because there may be external issues, such as connection speed, the number of characters necessary to redraw as opposed to scroll, or terminal capabilities that implementations will have to accommodate.

The current line in IEEE Std 1003.1-2001 maps one-to-one to a buffer line in the file. The current column does not. There are two different column values that are described by IEEE Std 1003.1-2001. The first is the current column value as set by many of the vi commands. This value is remembered for the lifetime of the editor. The second column value is the actual position on the screen where the cursor rests. The two are not always the same. For example, when the cursor is backed by a multi-column character, the actual cursor position on the screen has historically been the last column of the character in command mode, and the first column of the character in input mode.

Commands that set the current line, but that do not set the current cursor value (for example, j and k) attempt to get as close as possible to the remembered column position, so that the cursor tends to restrict itself to a vertical column as the user moves around in the edit buffer. IEEE Std 1003.1-2001 requires conformance to historical practice, requiring that the display location of the cursor on the display line be adjusted from the current column value as necessary to support this historical behavior.

Historically, only a single line (and for some terminals, a single line minus 1 column) of characters could be entered by the user for the line-oriented commands; that is, :, !, /, or ?. IEEE Std 1003.1-2001 permits, but does not require, this limitation.

Historically, "soft" errors in vi caused the terminal to be alerted, but no error message was displayed. As a general rule, no error message was displayed for errors in command execution in vi, when the error resulted from the user attempting an invalid or impossible action, or when a searched-for object was not found. Examples of soft errors included h at the left margin, <control>-B or [[ at the beginning of the file, 2G at the end of the file, and so on. In addition, errors such as %, ]], }, ), N, n, f, F, t, and T failing to find the searched-for object were soft as well. Less consistently, / and ? displayed an error message if the pattern was not found, /, ?, N, and n displayed an error message if no previous regular expression had been specified, and ; did not display an error message if no previous f, F, t, or T command had occurred. Also, behavior in this area might reasonably be based on a runtime evaluation of the speed of a network connection. Finally, some implementations have provided error messages for soft errors in order to assist naive users, based on the value of a verbose edit option. IEEE Std 1003.1-2001 does not list specific errors for which an error message shall be displayed. Implementations should conform to historical practice in the absence of any strong reason to diverge.

Page Backwards

The <control>-B and <control>-F commands historically considered it an error to attempt to page past the beginning or end of the file, whereas the <control>-D and <control>-U commands simply moved to the beginning or end of the file. For consistency, IEEE Std 1003.1-2001 requires the latter behavior for all four commands. All four commands still consider it an error if the current line is at the beginning ( <control>-B, <control>-U) or end ( <control>-F, <control>-D) of the file. Historically, the <control>-B and <control>-F commands skip two lines in order to include overlapping lines when a single command is entered. This makes less sense in the presence of a count, as there will be, by definition, no overlapping lines. The actual calculation used by historical implementations of the vi editor for <control>-B was:

((current first line) - count x (window edit option)) +2

and for <control>-F was:

((current first line) + count x (window edit option)) -2

This calculation does not work well when intermixing commands with and without counts; for example, 3 <control>-F is not equivalent to entering the <control>-F command three times, and is not reversible by entering the <control>-B command three times. For consistency with other vi commands that take counts, IEEE Std 1003.1-2001 requires a different calculation.

Scroll Forward

The 4BSD and System V implementations of vi differed on the initial value used by the scroll command. 4BSD used:

((window edit option) +1) /2

while System V used the value of the scroll edit option. The System V version is specified by IEEE Std 1003.1-2001 because the standard developers believed that it was more intuitive and permitted the user a method of setting the scroll value initially without also setting the number of lines that are displayed.

Scroll Forward by Line

Historically, the <control>-E and <control>-Y commands considered it an error if the last and first lines, respectively, were already on the screen. IEEE Std 1003.1-2001 requires conformance to historical practice. Historically, the <control>-E and <control>-Y commands had no effect in open mode. For simplicity and consistency of specification, IEEE Std 1003.1-2001 requires that they behave as usual, albeit with a single line screen.

Clear and Redisplay

The historical <control>-L command refreshed the screen exactly as it was supposed to be currently displayed, replacing any '@' characters for lines that had been deleted but not updated on the screen with refreshed '@' characters. The intent of the <control>-L command is to refresh when the screen has been accidentally overwritten; for example, by a write command from another user, or modem noise.

Redraw Screen

The historical <control>-R command redisplayed only when necessary to update lines that had been deleted but not updated on the screen and that were flagged with '@' characters. There is no requirement that the screen be in any way refreshed if no lines of this form are currently displayed. IEEE Std 1003.1-2001 permits implementations to extend this command to refresh lines on the screen flagged with '@' characters because they are too long to be displayed in the current framework; however, the current line and column need not be modified.

Search for tagstring

Historically, the first non- <blank> at or after the cursor was the first character, and all subsequent characters that were word characters, up to the end of the line, were included. For example, with the cursor on the leading space or on the '#' character in the text "#bar@" , the tag was "#bar" . On the character 'b' it was "bar" , and on the 'a' it was "ar" . IEEE Std 1003.1-2001 requires this behavior.

Replace Text with Results from Shell Command

Historically, the <, >, and ! commands considered most cursor motions other than line-oriented motions an error; for example, the command >/foo<CR> succeeded, while the command >l failed, even though the text region described by the two commands might be identical. For consistency, all three commands only consider entire lines and not partial lines, and the region is defined as any line that contains a character that was specified by the motion.

Move to Matching Character

Other matching characters have been left implementation-defined in order to allow extensions such as matching '<' and '>' for searching HTML, or #ifdef, #else, and #endif for searching C source.

Repeat Substitution

IEEE Std 1003.1-2001 requires that any c and g flags specified to the previous substitute command be ignored; however, the r flag may still apply, if supported by the implementation.

Return to Previous (Context or Section)

The [[, ]], (, ), {, and } commands are all affected by "section boundaries", but in some historical implementations not all of the commands recognize the same section boundaries. This is a bug, not a feature, and a unique section-boundary algorithm was not described for each command. One special case that is preserved is that the sentence command moves to the end of the last line of the edit buffer while the other commands go to the beginning, in order to preserve the traditional character cut semantics of the sentence command. Historically, vi section boundaries at the beginning and end of the edit buffer were the first non- <blank> on the first and last lines of the edit buffer if one exists; otherwise, the last character of the first and last lines of the edit buffer if one exists. To increase consistency with other section locations, this has been simplified by IEEE Std 1003.1-2001 to the first character of the first and last lines of the edit buffer, or the first and the last lines of the edit buffer if they are empty.

Sentence boundaries were problematic in the historical vi. They were not only the boundaries as defined for the section and paragraph commands, but they were the first non- <blank> that occurred after those boundaries, as well. Historically, the vi section commands were documented as taking an optional window size as a count preceding the command. This was not implemented in historical versions, so IEEE Std 1003.1-2001 requires that the count repeat the command, for consistency with other vi commands.

Repeat

Historically, mapped commands other than text input commands could not be repeated using the period command. IEEE Std 1003.1-2001 requires conformance to historical practice.

The restrictions on the interpretation of special characters (for example, <control>-H) in the repetition of text input mode commands is intended to match historical practice. For example, given the input sequence:

iab<control>-H<control>-H<control>-Hdef<escape>

the user should be informed of an error when the sequence is first entered, but not during a command repetition. The character <control>-T is specifically exempted from this restriction. Historical implementations of vi ignored <control>-T characters that were input in the original command during command repetition. IEEE Std 1003.1-2001 prohibits this behavior.

Find Regular Expression

Historically, commands did not affect the line searched to or from if the motion command was a search ( /, ?, N, n) and the final position was the start/end of the line. There were some special cases and vi was not consistent. IEEE Std 1003.1-2001 does not permit this behavior, for consistency. Historical implementations permitted but were unable to handle searches as motion commands that wrapped (that is, due to the edit option wrapscan) to the original location. IEEE Std 1003.1-2001 requires that this behavior be treated as an error.

Historically, the syntax "/RE/0" was used to force the command to cut text in line mode. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, in open mode, a z specified to a search command redisplayed the current line instead of displaying the current screen with the current line highlighted. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, trailing z commands were permitted and ignored if entered as part of a search used as a motion command. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Execute an ex Command

Historically, vi implementations restricted the commands that could be entered on the colon command line (for example, append and change), and some other commands were known to cause them to fail catastrophically. For consistency, IEEE Std 1003.1-2001 does not permit these restrictions. When executing an ex command by entering :, it is not possible to enter a <newline> as part of the command because it is considered the end of the command. A different approach is to enter ex command mode by using the vi Q command (and later resuming visual mode with the ex vi command). In ex command mode, the single-line limitation does not exist. So, for example, the following is valid:

Q
s/break here/break\
here/
vi

IEEE Std 1003.1-2001 requires that, if the ex command overwrites any part of the screen that would be erased by a refresh, vi pauses for a character from the user. Historically, this character could be any character; for example, a character input by the user before the message appeared, or even a mapped character. This is probably a bug, but implementations that have tried to be more rigorous by requiring that the user enter a specific character, or that the user enter a character after the message was displayed, have been forced by user indignation back into historical behavior. IEEE Std 1003.1-2001 requires conformance to historical practice.

Shift Left (Right)

Refer to the Rationale for the ! and / commands. Historically, the < and > commands sometimes moved the cursor to the first non- <blank> (for example if the command was repeated or with _ as the motion command), and sometimes left it unchanged. IEEE Std 1003.1-2001 does not permit this inconsistency, requiring instead that the cursor always move to the first non- <blank>. Historically, the < and > commands did not support buffer arguments, although some implementations allow the specification of an optional buffer. This behavior is neither required nor disallowed by IEEE Std 1003.1-2001.

Execute

Historically, buffers could execute other buffers, and loops, infinite and otherwise, were possible. IEEE Std 1003.1-2001 requires conformance to historical practice. The * buffer syntax of ex is not required in vi, because it is not historical practice and has been used in some vi implementations to support additional scripting languages.

Reverse Case

Historically, the ~ command ignored any associated count, and acted only on the characters in the current line. For consistency with other vi commands, IEEE Std 1003.1-2001 requires that an associated count act on the next count characters, and that the command move to subsequent lines if warranted by count, to make it possible to modify large pieces of text in a reasonably efficient manner. There exist vi implementations that optionally require an associated motion command for the ~ command. Implementations supporting this functionality are encouraged to base it on the tildedop edit option and handle the text regions and cursor positioning identically to the yank command.

Append

Historically, counts specified to the A, a, I, and i commands repeated the input of the first line count times, and did not repeat the subsequent lines of the input text. IEEE Std 1003.1-2001 requires that the entire text input be repeated count times.

Move Backward to Preceding Word

Historically, vi became confused if word commands were used as motion commands in empty files. IEEE Std 1003.1-2001 requires that this be an error. Historical implementations of vi had a large number of bugs in the word movement commands, and they varied greatly in behavior in the presence of empty lines, "words" made up of a single character, and lines containing only <blank>s. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Change to End-of-Line

Some historical implementations of the C command did not behave as described by IEEE Std 1003.1-2001 when the $ key was remapped because they were implemented by pushing the $ key onto the input queue and reprocessing it. IEEE Std 1003.1-2001 does not permit this behavior. Historically, the C, S, and s commands did not copy replaced text into the numeric buffers. For consistency and simplicity of specification, IEEE Std 1003.1-2001 requires that they behave like their respective c commands in all respects.

Delete

Historically, lines in open mode that were deleted were scrolled up, and an @ glyph written over the beginning of the line. In the case of terminals that are incapable of the necessary cursor motions, the editor erased the deleted line from the screen. IEEE Std 1003.1-2001 requires conformance to historical practice; that is, if the terminal cannot display the '@' character, the line cannot remain on the screen.

Delete to End-of-Line

Some historical implementations of the D command did not behave as described by IEEE Std 1003.1-2001 when the $ key was remapped because they were implemented by pushing the $ key onto the input queue and reprocessing it. IEEE Std 1003.1-2001 does not permit this behavior.

Join

An historical oddity of vi is that the commands J, 1J, and 2J are all equivalent. IEEE Std 1003.1-2001 requires conformance to historical practice. The vi J command is specified in terms of the ex join command with an ex command count value. The address correction for a count that is past the end of the edit buffer is necessary for historical compatibility for both ex and vi.

Mark Position

Historical practice is that only lowercase letters, plus '`' and '" , could be used to mark a cursor position. IEEE Std 1003.1-2001 requires conformance to historical practice, but encourages implementations to support other characters as marks as well.

Repeat Regular Expression Find (Forward and Reverse)

Historically, the N and n commands could not be used as motion components for the c command. With the exception of the cN command, which worked if the search crossed a line boundary, the text region would be discarded, and the user would not be in text input mode. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Insert Empty Line (Below and Above)

Historically, counts to the O and o commands were used as the number of physical lines to open, if the terminal was dumb and the slowopen option was not set. This was intended to minimize traffic over slow connections and repainting for dumb terminals. IEEE Std 1003.1-2001 does not permit this behavior, requiring that a count to the open command behave as for other text input commands. This change to historical practice was made for consistency, and because a superset of the functionality is provided by the slowopen edit option.

Put from Buffer (Following and Before)

Historically, counts to the p and P commands were ignored if the buffer was a line mode buffer, but were (mostly) implemented as described in IEEE Std 1003.1-2001 if the buffer was a character mode buffer. Because implementations exist that do not have this limitation, and because pasting lines multiple times is generally useful, IEEE Std 1003.1-2001 requires that count be supported for all p and P commands.

Historical implementations of vi were widely known to have major problems in the p and P commands, particularly when unusual regions of text were copied into the edit buffer. The standard developers viewed these as bugs, and they are not permitted for consistency and simplicity of specification.

Historically, a P or p command (or an ex put command executed from open or visual mode) executed in an empty file, left an empty line as the first line of the file. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Replace Character

Historically, the r command did not correctly handle the erase and word erase characters as arguments, nor did it handle an associated count greater than 1 with a <carriage-return> argument, for which it replaced count characters with a single <newline>. IEEE Std 1003.1-2001 does not permit these inconsistencies.

Historically, the r command permitted the <control>-V escaping of entered characters, such as <ESC> and the <carriage-return>; however, it required two leading <control>-V characters instead of one. IEEE Std 1003.1-2001 requires that this be changed for consistency with the other text input commands of vi.

Historically, it is an error to enter the r command if there are less than count characters at or after the cursor in the line. While a reasonable and unambiguous extension would be to permit the r command on empty lines, it would require that too large a count be adjusted to match the number of characters at or after the cursor for consistency, which is sufficiently different from historical practice to be avoided. IEEE Std 1003.1-2001 requires conformance to historical practice.

Replace Characters

Historically, if there were autoindent characters in the line on which the R command was run, and autoindent was set, the first <newline> would be properly indented and no characters would be replaced by the <newline>. Each additional <newline> would replace n characters, where n was the number of characters that were needed to indent the rest of the line to the proper indentation level. This behavior is a bug and is not permitted by IEEE Std 1003.1-2001.

Undo

Historical practice for cursor positioning after undoing commands was mixed. In most cases, when undoing commands that affected a single line, the cursor was moved to the start of added or changed text, or immediately after deleted text. However, if the user had moved from the line being changed, the column was either set to the first non- <blank>, returned to the origin of the command, or remained unchanged. When undoing commands that affected multiple lines or entire lines, the cursor was moved to the first character in the first line restored. As an example of how inconsistent this was, a search, followed by an o text input command, followed by an undo would return the cursor to the location where the o command was entered, but a cw command followed by an o command followed by an undo would return the cursor to the first non- <blank> of the line. IEEE Std 1003.1-2001 requires the most useful of these behaviors, and discards the least useful, in the interest of consistency and simplicity of specification.

Yank

Historically, the yank command did not move to the end of the motion if the motion was in the forward direction. It moved to the end of the motion if the motion was in the backward direction, except for the _ command, or for the G and ' commands when the end of the motion was on the current line. This was further complicated by the fact that for a number of motion commands, the yank command moved the cursor but did not update the screen; for example, a subsequent command would move the cursor from the end of the motion, even though the cursor on the screen had not reflected the cursor movement for the yank command. IEEE Std 1003.1-2001 requires that all yank commands associated with backward motions move the cursor to the end of the motion for consistency, and specifically, to make ' commands as motions consistent with search patterns as motions.

Yank Current Line

Some historical implementations of the Y command did not behave as described by IEEE Std 1003.1-2001 when the '_' key was remapped because they were implemented by pushing the '_' key onto the input queue and reprocessing it. IEEE Std 1003.1-2001 does not permit this behavior.

Redraw Window

Historically, the z command always redrew the screen. This is permitted but not required by IEEE Std 1003.1-2001, because of the frequent use of the z command in macros such as map n nz. for screen positioning, instead of its use to change the screen size. The standard developers believed that expanding or scrolling the screen offered a better interface for users. The ability to redraw the screen is preserved if the optional new window size is specified, and in the <control>-L and <control>-R commands.

The semantics of z^ are confusing at best. Historical practice is that the screen before the screen that ended with the specified line is displayed. IEEE Std 1003.1-2001 requires conformance to historical practice.

Historically, the z command would not display a partial line at the top or bottom of the screen. If the partial line would normally have been displayed at the bottom of the screen, the command worked, but the partial line was replaced with '@' characters. If the partial line would normally have been displayed at the top of the screen, the command would fail. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, the z command with a line specification of 1 ignored the command. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Historically, the z command did not set the cursor column to the first non- <blank> for the character if the first screen was to be displayed, and was already displayed. For consistency and simplicity of specification, IEEE Std 1003.1-2001 does not permit this behavior.

Input Mode Commands in vi

Historical implementations of vi did not permit the user to erase more than a single line of input, or to use normal erase characters such as line erase, worderase, and erase to erase autoindent characters. As there exist implementations of vi that do not have these limitations, both behaviors are permitted, but only historical practice is required. In the case of these extensions, vi is required to pause at the autoindent and previous line boundaries.

Historical implementations of vi updated only the portion of the screen where the current cursor character was displayed. For example, consider the vi input keystrokes:

iabcd<escape>0C<tab>

Historically, the <tab> would overwrite the characters "abcd" when it was displayed. Other implementations replace only the 'a' character with the <tab>, and then push the rest of the characters ahead of the cursor. Both implementations have problems. The historical implementation is probably visually nicer for the above example; however, for the keystrokes:

iabcd<ESC>0R<tab><ESC>

the historical implementation results in the string "bcd" disappearing and then magically reappearing when the <ESC> character is entered. IEEE Std 1003.1-2001 requires the former behavior when overwriting erase-columns-that is, overwriting characters that are no longer logically part of the edit buffer-and the latter behavior otherwise.

Historical implementations of vi discarded the <control>-D and <control>-T characters when they were entered at places where their command functionality was not appropriate. IEEE Std 1003.1-2001 requires that the <control>-T functionality always be available, and that <control>-D be treated as any other key when not operating on autoindent characters.

NUL

Some historical implementations of vi limited the number of characters entered using the NUL input character to 256 bytes. IEEE Std 1003.1-2001 permits this limitation; however, implementations are encouraged to remove this limit.

<control>-D

See also Rationale for the input mode command <newline>. The hidden assumptions in the <control>-D command (and in the vi autoindent specification in general) is that <space>s take up a single column on the screen and that <tab>s are comprised of an integral number of <space>s.

<newline>

Implementations are permitted to rewrite autoindent characters in the line when <newline>, <carriage-return>, <control>-D, and <control>-T are entered, or when the shift commands are used, because historical implementations have both done so and found it necessary to do so. For example, a <control>-D when the cursor is preceded by a single <tab>, with tabstop set to 8, and shiftwidth set to 3, will result in the <tab> being replaced by several <space>s.

<control>-T

See also the Rationale for the input mode command <newline>. Historically, <control>-T only worked if no non- <blank>s had yet been input in the current input line. In addition, the characters inserted by <control>-T were treated as autoindent characters, and could not be erased using normal user erase characters. Because implementations exist that do not have these limitations, and as moving to a column boundary is generally useful, IEEE Std 1003.1-2001 requires that both limitations be removed.

<control>-V

Historically, vi used ^V, regardless of the value of the literal-next character of the terminal. IEEE Std 1003.1-2001 requires conformance to historical practice.

The uses described for <control>-V can also be accomplished with <control>-Q, which is useful on terminals that use <control>-V for the down-arrow function. However, most historical implementations use <control>-Q for the termios START character, so the editor will generally not receive the <control>-Q unless stty ixon mode is set to off. (In addition, some historical implementations of vi explicitly set ixon mode to on, so it was difficult for the user to set it to off.) Any of the command characters described in IEEE Std 1003.1-2001 can be made ineffective by their selection as termios control characters, using the stty utility or other methods described in the System Interfaces volume of IEEE Std 1003.1-2001.

<ESC>

Historically, SIGINT alerted the terminal when used to end input mode. This behavior is permitted, but not required, by IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

ed , ex , stty

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wc(1p)

WC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wc - word, line, and byte or character count

SYNOPSIS

wc [-c|-m][-lw][file...]

DESCRIPTION

The wc utility shall read one or more input files and, by default, write the number of <newline>s, words, and bytes contained in each input file to the standard output.

The utility also shall write a total count for all named files, if more than one input file is specified.

The wc utility shall consider a word to be a non-zero-length string of characters delimited by white space.

OPTIONS

The wc utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Write to the standard output the number of bytes in each input file.
-l
Write to the standard output the number of <newline>s in each input file.
-m
Write to the standard output the number of characters in each input file.
-w
Write to the standard output the number of words in each input file.

When any option is specified, wc shall report only the information requested by the specified options.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If no file operands are specified, the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

The input files may be of any type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of wc:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and which characters are defined as white space characters.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

By default, the standard output shall contain an entry for each input file of the form:

"%d %d %d %s\n", <newlines>, <words>, <bytes>, <file>

If the -m option is specified, the number of characters shall replace the <bytes> field in this format.

If any options are specified and the -l option is not specified, the number of <newline>s shall not be written.

If any options are specified and the -w option is not specified, the number of words shall not be written.

If any options are specified and neither -c nor -m is specified, the number of bytes or characters shall not be written.

If no input file operands are specified, no name shall be written and no <blank>s preceding the pathname shall be written.

If more than one input file operand is specified, an additional line shall be written, of the same format as the other lines, except that the word total (in the POSIX locale) shall be written instead of a pathname and the total of each column shall be written as appropriate. Such an additional line, if any, is written at the end of the output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The -m option is not a switch, but an option at the same level as -c. Thus, to produce the full default output with character counts instead of bytes, the command required is:

wc -mlw

EXAMPLES

None.

RATIONALE

The output file format pseudo- printf() string differs from the System V version of wc:

"%7d%7d%7d %s\n"

which produces possibly ambiguous and unparsable results for very large files, as it assumes no number shall exceed six digits.

Some historical implementations use only <space>, <tab>, and <newline> as word separators. The equivalent of the ISO C standard isspace() function is more appropriate.

The -c option stands for "character" count, even though it counts bytes. This stems from the sometimes erroneous historical view that bytes and characters are the same size. Due to international requirements, the -m option (reminiscent of "multi-byte") was added to obtain actual character counts.

Early proposals only specified the results when input files were text files. The current specification more closely matches historical practice. (Bytes, words, and <newline>s are counted separately and the results are written when an end-of-file is detected.)

Historical implementations of the wc utility only accepted one argument to specify the options -c, -l, and -w. Some of them also had multiple occurrences of an option cause the corresponding count to be written multiple times and had the order of specification of the options affect the order of the fields on output, but did not document either of these. Because common usage either specifies no options or only one option, and because none of this was documented, the changes required by this volume of IEEE Std 1003.1-2001 should not break many historical applications (and do not break any historical conforming applications).

FUTURE DIRECTIONS

None.

SEE ALSO

cksum

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


echo(1p)

ECHO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

echo - write arguments to standard output

SYNOPSIS

echo [string ...]

DESCRIPTION

The echo utility writes its arguments to standard output, followed by a <newline>. If there are no arguments, only the <newline> is written.

OPTIONS

The echo utility shall not recognize the "--" argument in the manner specified by Guideline 10 of the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines; "--" shall be recognized as a string operand.

Implementations shall not support any options.

OPERANDS

The following operands shall be supported:

string
A string to be written to standard output. If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined.

On XSI-conformant systems, if the first operand is -n, it shall be treated as a string, not an option. The following character sequences shall be recognized on XSI-conformant systems within any of the arguments:

\a
Write an <alert>.
\b
Write a <backspace>.
\c
Suppress the <newline> that otherwise follows the final argument in the output. All characters following the '\c' in the arguments shall be ignored.
\f
Write a <form-feed>.
\n
Write a <newline>.
\r
Write a <carriage-return>.
\t
Write a <tab>.
\v
Write a <vertical-tab>.
\\
Write a backslash character.
\0 num
Write an 8-bit value that is the zero, one, two, or three-digit octal number num.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of echo:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The echo utility arguments shall be separated by single <space>s and a <newline> shall follow the last argument. Output transformations shall occur based on the escape sequences in the input. See the OPERANDS section.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

It is not possible to use echo portably across all POSIX systems unless both -n (as the first argument) and escape sequences are omitted.

The printf utility can be used portably to emulate any of the traditional behaviors of the echo utility as follows (assuming that IFS has its standard value or is unset):

*
The historic System V echo and the requirements on XSI implementations in this volume of IEEE Std 1003.1-2001 are equivalent to:

printf "%b\n" "$*"

*
The BSD echo is equivalent to:

if [ "X$1" = "X-n" ]
then
    shift
    printf "%s" "$*"
else
    printf "%s\n" "$*"
fi

New applications are encouraged to use printf instead of echo.

EXAMPLES

None.

RATIONALE

The echo utility has not been made obsolescent because of its extremely widespread use in historical applications. Conforming applications that wish to do prompting without <newline>s or that could possibly be expecting to echo a -n, should use the printf utility derived from the Ninth Edition system.

As specified, echo writes its arguments in the simplest of ways. The two different historical versions of echo vary in fatally incompatible ways.

The BSD echo checks the first argument for the string -n which causes it to suppress the <newline> that would otherwise follow the final argument in the output.

The System V echo does not support any options, but allows escape sequences within its operands, as described for XSI implementations in the OPERANDS section.

The echo utility does not support Utility Syntax Guideline 10 because historical applications depend on echo to echo all of its arguments, except for the -n option in the BSD version.

FUTURE DIRECTIONS

None.

SEE ALSO

printf

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sact(1p)

SACT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sact - print current SCCS file-editing activity (DEVELOPMENT)

SYNOPSIS

sact file...

DESCRIPTION

The sact utility shall inform the user of any impending deltas to a named SCCS file by writing a list to standard output. This situation occurs when get -e has been executed previously without a subsequent execution of delta, unget, or sccs unedit.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

file
A pathname of an existing SCCS file or a directory. If file is a directory, the sact utility shall behave as though each file in the directory were specified as a named file, except that non-SCCS files (last component of the pathname does not begin with s.) and unreadable files shall be silently ignored.

If exactly one file operand appears, and it is '-' , the standard input shall be read; each line of the standard input shall be taken to be the name of an SCCS file to be processed. Non-SCCS files and unreadable files shall be silently ignored.

STDIN

The standard input shall be a text file used only when the file operand is specified as '-' . Each line of the text file shall be interpreted as an SCCS pathname.

INPUT FILES

Any SCCS files interrogated are files of an unspecified format.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of sact:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The output for each named file shall consist of a line in the following format:

"%s %s %s %s %s\n", <SID>, <new SID>, <login>, <date>, <time>
<SID>
Specifies the SID of a delta that currently exists in the SCCS file to which changes are made to make the new delta.
<new SID>
Specifies the SID for the new delta to be created.
<login>
Contains the login name of the user who makes the delta (that is, who executed a get for editing).
<date>
Contains the date that get -e was executed, in the format used by the prs :D: data keyword.
<time>
Contains the time that get -e was executed, in the format used by the prs :T: data keyword.

If there is more than one named file or if a directory or standard input is named, each pathname shall be written before each of the preceding lines:

"\n%s:\n", <pathname>

STDERR

The standard error shall be used only for optional informative messages concerning SCCS files with no impending deltas, and for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

delta , get , sccs , unget

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


break(1p)

BREAK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

break - exit from for, while, or until loop

SYNOPSIS

break [n]

DESCRIPTION

The break utility shall exit from the smallest enclosing for, while, or until loop, if any; or from the nth enclosing loop if n is specified. The value of n is an unsigned decimal integer greater than or equal to 1. The default shall be equivalent to n=1. If n is greater than the number of enclosing loops, the outermost enclosing loop shall be exited. Execution shall continue with the command immediately following the loop.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

0
Successful completion.
>0
The n value was not an unsigned decimal integer greater than or equal to 1.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

for i in * do
    if test -d "$i" then break fi done

RATIONALE

In early proposals, consideration was given to expanding the syntax of break and continue to refer to a label associated with the appropriate loop as a preferable alternative to the n method. However, this volume of IEEE Std 1003.1-2001 does reserve the name space of command names ending with a colon. It is anticipated that a future implementation could take advantage of this and provide something like:

outofloop: for i in a b c d e
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do
        if test -r "${i}${j}"
        then break outofloop
        fi
    done
done

and that this might be standardized after implementation experience is achieved.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sccs(1p)

SCCS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sccs - front end for the SCCS subsystem (DEVELOPMENT)

SYNOPSIS

sccs [-r][-d path][-p path] command [options...][operands...]

DESCRIPTION

The sccs utility is a front end to the SCCS programs. It also includes the capability to run set-user-id to another user to provide additional protection.

The sccs utility shall invoke the specified command with the specified options and operands. By default, each of the operands shall be modified by prefixing it with the string "SCCS/s." .

The command can be the name of one of the SCCS utilities in this volume of IEEE Std 1003.1-2001 ( admin, delta, get, prs, rmdel, sact, unget, val, or what) or one of the pseudo-utilities listed in the EXTENDED DESCRIPTION section.

OPTIONS

The sccs utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that options operands are actually options to be passed to the utility named by command. When the portion of the command:

command [options ... ] [operands ... ]

is considered, all of the pseudo-utilities used as command shall support the Utility Syntax Guidelines. Any of the other SCCS utilities that can be invoked in this manner support the Guidelines to the extent indicated by their individual OPTIONS sections.

The following options shall be supported preceding the command operand:

-d path
A pathname of a directory to be used as a root directory for the SCCS files. The default shall be the current directory. The -d option shall take precedence over the PROJECTDIR variable. See -p.
-p path
A pathname of a directory in which the SCCS files are located. The default shall be the SCCS directory.

The -p option differs from the -d option in that the -d option-argument shall be prefixed to the entire pathname and the -p option-argument shall be inserted before the final component of the pathname. For example:

sccs -d /x -p y get a/b

converts to:

get /x/a/y/s.b

This allows the creation of aliases such as:

alias syssccs="sccs -d /usr/src"

which is used as:

syssccs get cmd/who.c
-r
Invoke command with the real user ID of the process, not any effective user ID that the sccs utility is set to. Certain commands ( admin, check, clean, diffs, info, rmdel, and tell) cannot be run set-user-ID by all users, since this would allow anyone to change the authorizations. These commands are always run as the real user.

OPERANDS

The following operands shall be supported:

command
An SCCS utility name or the name of one of the pseudo-utilities listed in the EXTENDED DESCRIPTION section.
options
An option or option-argument to be passed to command.
operands
An operand to be passed to command.

STDIN

See the utility description for the specified command.

INPUT FILES

See the utility description for the specified command.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of sccs:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PROJECTDIR

Provide a default value for the -d path option. If the value of PROJECTDIR begins with a slash, it shall be considered an absolute pathname; otherwise, the value of PROJECTDIR is treated as a user name and that user's initial working directory shall be examined for a subdirectory src or source. If such a directory is found, it shall be used. Otherwise, the value shall be used as a relative pathname.

Additional environment variable effects may be found in the utility description for the specified command.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the utility description for the specified command.

STDERR

See the utility description for the specified command.

OUTPUT FILES

See the utility description for the specified command.

EXTENDED DESCRIPTION

The following pseudo-utilities shall be supported as command operands. All options referred to in the following list are values given in the options operands following command.

check
Equivalent to info, except that nothing shall be printed if nothing is being edited, and a non-zero exit status shall be returned if anything is being edited. The intent is to have this included in an "install" entry in a makefile to ensure that everything is included into the SCCS file before a version is installed.
clean
Remove everything from the current directory that can be recreated from SCCS files, but do not remove any files being edited. If the -b option is given, branches shall be ignored in the determination of whether they are being edited; this is dangerous if branches are kept in the same directory.
create
Create an SCCS file, taking the initial contents from the file of the same name. Any options to admin are accepted. If the creation is successful, the original files shall be renamed by prefixing the basenames with a comma. These renamed files should be removed after it has been verified that the SCCS files have been created successfully.
delget
Perform a delta on the named files and then get new versions. The new versions shall have ID keywords expanded and shall not be editable. Any -m, -p, -r, -s, and -y options shall be passed to delta, and any -b, -c, -e, -i, -k, -l, -s, and -x options shall be passed to get.
deledit
Equivalent to delget, except that the get phase shall include the -e option. This option is useful for making a checkpoint of the current editing phase. The same options shall be passed to delta as described above, and all the options listed for get above except -e shall be passed to edit.
diffs
Write a difference listing between the current version of the files checked out for editing and the versions in SCCS format. Any -r, -c, -i, -x, and -t options shall be passed to get; any -l, -s, -e, -f, -h, and -b options shall be passed to diff. A -C option shall be passed to diff as -c.
edit
Equivalent to get -e.
fix
Remove the named delta, but leave a copy of the delta with the changes that were in it. It is useful for fixing small compiler bugs, and so on. The application shall ensure that it is followed by a -r SID option. Since fix does not leave audit trails, it should be used carefully.
info
Write a listing of all files being edited. If the -b option is given, branches (that is, SIDs with two or fewer components) shall be ignored. If a -u user option is given, then only files being edited by the named user shall be listed. A -U option shall be equivalent to -u< current user>.
print
Write out verbose information about the named files, equivalent to sccs prs.
tell
Write a <newline>-separated list of the files being edited to standard output. Takes the -b, -u, and -U options like info and check.
unedit
This is the opposite of an edit or a get -e. It should be used with caution, since any changes made since the get are lost.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Many of the SCCS utilities take directory names as operands as well as specific filenames. The pseudo-utilities supported by sccs are not described as having this capability, but are not prohibited from doing so.

EXAMPLES

1.
To get a file for editing, edit it and produce a new delta:

sccs get -e file.c
ex file.c
sccs delta file.c

2.
To get a file from another directory:

sccs -p /usr/src/sccs/s. get cc.c

or:

sccs get /usr/src/sccs/s.cc.c

3.
To make a delta of a large number of files in the current directory:

sccs delta *.c

4.
To get a list of files being edited that are not on branches:

sccs info -b

5.
To delta everything being edited by the current user:

sccs delta $(sccs tell -U)

6.
In a makefile, to get source files from an SCCS file if it does not already exist:

SRCS = <list of source files>
$(SRCS):
    sccs get $(REL) $@

RATIONALE

SCCS and its associated utilities are part of the XSI Development Utilities option within the XSI extension.

SCCS is an abbreviation for Source Code Control System. It is a maintenance and enhancement tracking tool. When a file is put under SCCS, the source code control system maintains the file and, when changes are made, identifies and stores them in the file with the original source code and/or documentation. As other changes are made, they too are identified and retained in the file.

Retrieval of the original and any set of changes is possible. Any version of the file as it develops can be reconstructed for inspection or additional modification. History data can be stored with each version, documenting why the changes were made, who made them, and when they were made.

FUTURE DIRECTIONS

None.

SEE ALSO

admin , delta , get , make , prs , rmdel , sact , unget , val , what

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fuser(1p)

FUSER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fuser - list process IDs of all processes that have one or more files open

SYNOPSIS

fuser [ -cfu ] file ...

DESCRIPTION

The fuser utility shall write to standard output the process IDs of processes running on the local system that have one or more named files open. For block special devices, all processes using any file on that device are listed.

The fuser utility shall write to standard error additional information about the named files indicating how the file is being used.

Any output for processes running on remote systems that have a named file open is unspecified.

A user may need appropriate privilege to invoke the fuser utility.

OPTIONS

The fuser utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
The file is treated as a mount point and the utility shall report on any files open in the file system.
-f
The report shall be only for the named files.
-u
The user name, in parentheses, associated with each process ID written to standard output shall be written to standard error.

OPERANDS

The following operand shall be supported:

file
A pathname on which the file or file system is to be reported.

STDIN

Not used.

INPUT FILES

The user database.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of fuser:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The fuser utility shall write the process ID for each process using each file given as an operand to standard output in the following format:

"%d", <process_id>

STDERR

The fuser utility shall write diagnostic messages to standard error.

The fuser utility also shall write the following to standard error:

*
The pathname of each named file is written followed immediately by a colon.

*
For each process ID written to standard output, the character 'c' shall be written to standard error if the process is using the file as its current directory and the character 'r' shall be written to standard error if the process is using the file as its root directory. Implementations may write other alphabetic characters to indicate other uses of files.

*
When the -u option is specified, characters indicating the use of the file shall be followed immediately by the user name, in parentheses, corresponding to the process' real user ID. If the user name cannot be resolved from the process' real user ID, the process' real user ID shall be written instead of the user name.

When standard output and standard error are directed to the same file, the output shall be interleaved so that the filename appears at the start of each line, followed by the process ID and characters indicating the use of the file. Then, if the -u option is specified, the user name or user ID for each process using that file shall be written.

A <newline> shall be written to standard error after the last output described above for each file operand.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

The command:

fuser -fu .

writes to standard output the process IDs of processes that are using the current directory and writes to standard error an indication of how those processes are using the directory and the user names associated with the processes that are using the current directory.

RATIONALE

The definition of the fuser utility follows existing practice.

FUTURE DIRECTIONS

None.

SEE ALSO

None.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


continue(1p)

CONTINUE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

continue - continue for, while, or until loop

SYNOPSIS

continue [n]

DESCRIPTION

The continue utility shall return to the top of the smallest enclosing for, while, or until loop, or to the top of the nth enclosing loop, if n is specified. This involves repeating the condition list of a while or until loop or performing the next assignment of a for loop, and re-executing the loop if appropriate.

The value of n is a decimal integer greater than or equal to 1. The default shall be equivalent to n=1. If n is greater than the number of enclosing loops, the outermost enclosing loop shall be used.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

0
Successful completion.
>0
The n value was not an unsigned decimal integer greater than or equal to 1.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

for i in *
do
    if test -d "$i"
    then continue
    fi
    echo "\"$i\"" is not a directory.
done

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


zcat(1p)

ZCAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

zcat - expand and concatenate data

SYNOPSIS

zcat [file...]

DESCRIPTION

The zcat utility shall write to standard output the uncompressed form of files that have been compressed using the compress utility. It is the equivalent of uncompress -c. Input files are not affected.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

file
The pathname of a file previously processed by the compress utility. If file already has the .Z suffix specified, it is used as submitted. Otherwise, the .Z suffix is appended to the filename prior to processing.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' .

INPUT FILES

Input files shall be compressed files that are in the format produced by the compress utility.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of zcat:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The compressed files given as input shall be written on standard output in their uncompressed form.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

compress , uncompress

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


false(1p)

FALSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

false - return false value

SYNOPSIS

false

DESCRIPTION

The false utility shall return with a non-zero exit code.

OPTIONS

None.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

Not used.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The false utility shall always exit with a value other than zero.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

true

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


unexpand(1p)

UNEXPAND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unexpand - convert spaces to tabs

SYNOPSIS

unexpand [ -a| -t tablist][file...]

DESCRIPTION

The unexpand utility shall copy files or standard input to standard output, converting <blank>s at the beginning of each line into the maximum number of <tab>s followed by the minimum number of <space>s needed to fill the same column positions originally filled by the translated <blank>s. By default, tabstops shall be set at every eighth column position. Each <backspace> shall be copied to the output, and shall cause the column position count for tab calculations to be decremented; the count shall never be decremented to a value less than one.

OPTIONS

The unexpand utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
In addition to translating <blank>s at the beginning of each line, translate all sequences of two or more <blank>s immediately preceding a tab stop to the maximum number of <tab>s followed by the minimum number of <space>s needed to fill the same column positions originally filled by the translated <blank>s.
-t tablist
Specify the tab stops. The application shall ensure that the tablist option-argument is a single argument consisting of a single positive decimal integer or multiple positive decimal integers, separated by <blank>s or commas, in ascending order. If a single number is given, tabs shall be set tablist column positions apart instead of the default 8. If multiple numbers are given, the tabs shall be set at those specific column positions.

The application shall ensure that each tab-stop position N is an integer value greater than zero, and the list shall be in strictly ascending order. This is taken to mean that, from the start of a line of output, tabbing to position N shall cause the next character output to be in the ( N+1)th column position on that line. When the -t option is not specified, the default shall be the equivalent of specifying -t 8 (except for the interaction with -a, described below).

No <space>-to- <tab> conversions shall occur for characters at positions beyond the last of those specified in a multiple tab-stop list.

When -t is specified, the presence or absence of the -a option shall be ignored; conversion shall not be limited to the processing of leading <blank>s.

OPERANDS

The following operand shall be supported:

file
A pathname of a text file to be used as input.

STDIN

See the INPUT FILES section.

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of unexpand:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the processing of <tab>s and <space>s, and for the determination of the width in column positions each character would occupy on an output device.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be equivalent to the input files with the specified <space>-to- <tab> conversions.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

One non-intuitive aspect of unexpand is its restriction to leading spaces when neither -a nor -t is specified. Users who always want to convert all spaces in a file can easily alias unexpand to use the -a or -t 8 option.

EXAMPLES

None.

RATIONALE

On several occasions, consideration was given to adding a -t option to the unexpand utility to complement the -t in expand (see expand ). The historical intent of unexpand was to translate multiple <blank>s into tab stops, where tab stops were a multiple of eight column positions on most UNIX systems. An early proposal omitted -t because it seemed outside the scope of the User Portability Utilities option; it was not described in any of the base documents. However, hard-coding tab stops every eight columns was not suitable for the international community and broke historical precedents for some vendors in the FORTRAN community, so -t was restored in conjunction with the list of valid extension categories considered by the standard developers. Thus, unexpand is now the logical converse of expand.

FUTURE DIRECTIONS

None.

SEE ALSO

expand , tabs

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


unset(1p)

UNSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unset - unset values and attributes of variables and functions

SYNOPSIS

unset [-fv] name ...

DESCRIPTION

Each variable or function specified by name shall be unset.

If -v is specified, name refers to a variable name and the shell shall unset it and remove it from the environment. Read-only variables cannot be unset.

If -f is specified, name refers to a function and the shell shall unset the function definition.

If neither -f nor -v is specified, name refers to a variable; if a variable by that name does not exist, it is unspecified whether a function by that name, if any, shall be unset.

Unsetting a variable or function that was not previously set shall not be considered an error and does not cause the shell to abort.

The unset special built-in shall support the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

Note that:

VARIABLE=

is not equivalent to an unset of VARIABLE; in the example, VARIABLE is set to "" . Also, the variables that can be unset should not be misinterpreted to include the special parameters (see Special Parameters ).

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

0
All name operands were successfully unset.
>0
At least one name could not be unset.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Unset VISUAL variable:

unset -v VISUAL

Unset the functions foo and bar:

unset -f foo bar

RATIONALE

Consideration was given to omitting the -f option in favor of an unfunction utility, but the standard developers decided to retain historical practice.

The -v option was introduced because System V historically used one name space for both variables and functions. When unset is used without options, System V historically unset either a function or a variable, and there was no confusion about which one was intended. A portable POSIX application can use unset without an option to unset a variable, but not a function; the -f option must be used.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uuencode(1p)

UUENCODE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uuencode - encode a binary file

SYNOPSIS

uuencode [-m][file] decode_pathname

DESCRIPTION

The uuencode utility shall write an encoded version of the named input file, or standard input if no file is specified, to standard output. The output shall be encoded using one of the algorithms described in the STDOUT section and shall include the file access permission bits (in chmod octal or symbolic notation) of the input file and the decode_pathname, for re-creation of the file on another system that conforms to this volume of IEEE Std 1003.1-2001.

OPTIONS

The uuencode utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported by the implementation:

-m
Encode the output using the MIME Base64 algorithm described in STDOUT. If -m is not specified, the historical algorithm described in STDOUT shall be used.

OPERANDS

The following operands shall be supported:

decode_pathname

The pathname of the file into which the uudecode utility shall place the decoded file. Specifying a decode_pathname operand of /dev/stdout shall indicate that uudecode is to use standard output. If there are characters in decode_pathname that are not in the portable filename character set the results are unspecified.

file
A pathname of the file to be encoded.

STDIN

See the INPUT FILES section.

INPUT FILES

Input files can be files of any type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uuencode:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

uuencode Base64 Algorithm

The standard output shall be a text file (encoded in the character set of the current locale) that begins with the line:

"begin-base64 %s %s\n", <mode>, <decode_pathname>

and ends with the line:

"====\n"

In both cases, the lines shall have no preceding or trailing <blank>s.

The encoding process represents 24-bit groups of input bits as output strings of four encoded characters. Proceeding from left to right, a 24-bit input group shall be formed by concatenating three 8-bit input groups. Each 24-bit input group then shall be treated as four concatenated 6-bit groups, each of which shall be translated into a single digit in the Base64 alphabet. When encoding a bit stream via the Base64 encoding, the bit stream shall be presumed to be ordered with the most-significant bit first. That is, the first bit in the stream shall be the high-order bit in the first byte, and the eighth bit shall be the low-order bit in the first byte, and so on. Each 6-bit group is used as an index into an array of 64 printable characters, as shown in uuencode Base64 Values .

Table: uuencode Base64 Values
Value | Encoding | Value | Encoding | Value | Encoding | Value | Encoding
0 | A | 17 | R | 34 | i | 51 | z
1 | B | 18 | S | 35 | j | 52 | 0
2 | C | 19 | T | 36 | k | 53 | 1
3 | D | 20 | U | 37 | l | 54 | 2
4 | E | 21 | V | 38 | m | 55 | 3
5 | F | 22 | W | 39 | n | 56 | 4
6 | G | 23 | X | 40 | o | 57 | 5
7 | H | 24 | Y | 41 | p | 58 | 6
8 | I | 25 | Z | 42 | q | 59 | 7
9 | J | 26 | a | 43 | r | 60 | 8
10 | K | 27 | b | 44 | s | 61 | 9
11 | L | 28 | c | 45 | t | 62 | +
12 | M | 29 | d | 46 | u | 63 | /
13 | N | 30 | e | 47 | v |  |
14 | O | 31 | f | 48 | w | (pad) |
15 | P | 32 | g | 49 | x |  |
16 | Q | 33 | h | 50 | y |  |

The character referenced by the index shall be placed in the output string.

The output stream (encoded bytes) shall be represented in lines of no more than 76 characters each. All line breaks or other characters not found in the table shall be ignored by decoding software (see uudecode ).

Special processing shall be performed if fewer than 24 bits are available at the end of a message or encapsulated part of a message. A full encoding quantum shall always be completed at the end of a message. When fewer than 24 input bits are available in an input group, zero bits shall be added (on the right) to form an integral number of 6-bit groups. Output character positions that are not required to represent actual input data shall be set to the character '=' . Since all Base64 input is an integral number of octets, only the following cases can arise:

1.
The final quantum of encoding input is an integral multiple of 24 bits; here, the final unit of encoded output shall be an integral multiple of 4 characters with no '=' padding.

2.
The final quantum of encoding input is exactly 16 bits; here, the final unit of encoded output shall be three characters followed by one '=' padding character.

3.
The final quantum of encoding input is exactly 8 bits; here, the final unit of encoded output shall be two characters followed by two '=' padding characters.

A terminating "====" evaluates to nothing and denotes the end of the encoded data.

uuencode Historical Algorithm

The standard output shall be a text file (encoded in the character set of the current locale) that begins with the line:

"begin %s %s\n" <mode>, <decode_pathname>

and ends with the line:

"end\n"

In both cases, the lines shall have no preceding or trailing <blank>s.

The algorithm that shall be used for lines in between begin and end takes three octets as input and writes four characters of output by splitting the input at six-bit intervals into four octets, containing data in the lower six bits only. These octets shall be converted to characters by adding a value of 0x20 to each octet, so that each octet is in the range [0x20,0x5f], and then it shall be assumed to represent a printable character in the ISO/IEC 646:1991 standard encoded character set. It then shall be translated into the corresponding character codes for the codeset in use in the current locale. (For example, the octet 0x41, representing 'A' , would be translated to 'A' in the current codeset, such as 0xc1 if it were EBCDIC.)

Where the bits of two octets are combined, the least significant bits of the first octet shall be shifted left and combined with the most significant bits of the second octet shifted right. Thus the three octets A, B, C shall be converted into the four octets:

0x20 + (( A >> 2                    ) & 0x3F)
0x20 + (((A << 4) | ((B >> 4) & 0xF)) & 0x3F)
0x20 + (((B << 2) | ((C >> 6) & 0x3)) & 0x3F)
0x20 + (( C                         ) & 0x3F)

These octets then shall be translated into the local character set.

Each encoded line contains a length character, equal to the number of characters to be decoded plus 0x20 translated to the local character set as described above, followed by the encoded characters. The maximum number of octets to be encoded on each line shall be 45.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The file is expanded by 35 percent (each three octets become four, plus control information) causing it to take longer to transmit.

Since this utility is intended to create files to be used for data interchange between systems with possibly different codesets, and to represent binary data as a text file, the ISO/IEC 646:1991 standard was chosen for a midpoint in the algorithm as a known reference point. The output from uuencode is a text file on the local system. If the output were in the ISO/IEC 646:1991 standard codeset, it might not be a text file (at least because the <newline>s might not match), and the goal of creating a text file would be defeated. If this text file was then carried to another machine with the same codeset, it would be perfectly compatible with that system's uudecode. If it was transmitted over a mail system or sent to a machine with a different codeset, it is assumed that, as for every other text file, some translation mechanism would convert it (by the time it reached a user on the other system) into an appropriate codeset. This translation only makes sense from the local codeset, not if the file has been put into a ISO/IEC 646:1991 standard representation first. Similarly, files processed by uuencode can be placed in pax archives, intermixed with other text files in the same codeset.

EXAMPLES

None.

RATIONALE

A new algorithm was added at the request of the international community to parallel work in RFC 2045 (MIME). As with the historical uuencode format, the Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that is not humanly readable. A 65-character subset of the ISO/IEC 646:1991 standard is used, enabling 6 bits to be represented per printable character. (The extra 65th character, '=' , is used to signify a special processing function.)

This subset has the important property that it is represented identically in all versions of the ISO/IEC 646:1991 standard, including US ASCII, and all characters in the subset are also represented identically in all versions of EBCDIC. The historical uuencode algorithm does not share this property, which is the reason that a second algorithm was added to the ISO POSIX-2 standard.

The string "====" was used for the termination instead of the end used in the original format because the latter is a string that could be valid encoded input.

In an early draft, the -m option was named -b (for Base64), but it was renamed to reflect its relationship to the RFC 2045. A -u was also present to invoke the default algorithm, but since this was not historical practice, it was omitted as being unnecessary.

See the RATIONALE section in uudecode for the derivation of the /dev/stdout symbol.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , mailx , uudecode

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


split(1p)

SPLIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

split - split files into pieces

SYNOPSIS

split [-l line_count][-a suffix_length][file[name]]

split -b n[k|m][-a suffix_length][file[name]]

DESCRIPTION

The split utility shall read an input file and write one or more output files. The default size of each output file shall be 1000 lines. The size of the output files can be modified by specification of the -b or -l options. Each output file shall be created with a unique suffix. The suffix shall consist of exactly suffix_length lowercase letters from the POSIX locale. The letters of the suffix shall be used as if they were a base-26 digit system, with the first suffix to be created consisting of all 'a' characters, the second with a 'b' replacing the last 'a' , and so on, until a name of all 'z' characters is created. By default, the names of the output files shall be 'x' , followed by a two-character suffix from the character set as described above, starting with "aa" , "ab" , "ac" , and so on, and continuing until the suffix "zz" , for a maximum of 676 files.

If the number of files required exceeds the maximum allowed by the suffix length provided, such that the last allowable file would be larger than the requested size, the split utility shall fail after creating the last file with a valid suffix; split shall not delete the files it created with valid suffixes. If the file limit is not exceeded, the last file created shall contain the remainder of the input file, and may be smaller than the requested size.

OPTIONS

The split utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a suffix_length

Use suffix_length letters to form the suffix portion of the filenames of the split file. If -a is not specified, the default suffix length shall be two. If the sum of the name operand and the suffix_length option-argument would create a filename exceeding {NAME_MAX} bytes, an error shall result; split shall exit with a diagnostic message and no files shall be created.

-b n
Split a file into pieces n bytes in size.
-b n k
Split a file into pieces n*1024 bytes in size.
-b n m
Split a file into pieces n*1048576 bytes in size.
-l line_count
Specify the number of lines in each resulting file piece. The line_count argument is an unsigned decimal integer. The default is 1000. If the input does not end with a <newline>, the partial line shall be included in the last output file.

OPERANDS

The following operands shall be supported:

file
The pathname of the ordinary file to be split. If no input file is given or file is '-' , the standard input shall be used.
name
The prefix to be used for each of the files resulting from the split operation. If no name argument is given, 'x' shall be used as the prefix of the output files. The combined length of the basename of prefix and suffix_length cannot exceed {NAME_MAX} bytes. See the OPTIONS section.

STDIN

See the INPUT FILES section.

INPUT FILES

Any file can be used as input.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of split:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output files contain portions of the original input file; otherwise, unchanged.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

In the following examples foo is a text file that contains 5000 lines.

1.
Create five files, xaa, xab, xac, xad, and xae:

split foo

2.
Create five files, but the suffixed portion of the created files consists of three letters, xaaa, xaab, xaac, xaad, and xaae:

split -a 3 foo

3.
Create three files with four-letter suffixes and a supplied prefix, bar_aaaa, bar_aaab, and bar_aaac:

split -a 4 -l 2000 foo bar_

4.
Create as many files as are necessary to contain at most 20*1024 bytes, each with the default prefix of x and a five-letter suffix:

split -a 5 -b 20k foo

RATIONALE

The -b option was added to provide a mechanism for splitting files other than by lines. While most uses of the -b option are for transmitting files over networks, some believed it would have additional uses.

The -a option was added to overcome the limitation of being able to create only 676 files.

Consideration was given to deleting this utility, using the rationale that the functionality provided by this utility is available via the csplit utility (see csplit ). Upon reconsideration of the purpose of the User Portability Extension, it was decided to retain both this utility and the csplit utility because users use both utilities and have historical expectations of their behavior. Furthermore, the splitting on byte boundaries in split cannot be duplicated with the historical csplit.

The text " split shall not delete the files it created with valid suffixes" would normally be assumed, but since the related utility, csplit, does delete files under some circumstances, the historical behavior of split is made explicit to avoid misinterpretation.

FUTURE DIRECTIONS

None.

SEE ALSO

csplit

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


export(1p)

EXPORT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

export - set the export attribute for variables

SYNOPSIS

export name[=word]...

export -p

DESCRIPTION

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

The export special built-in shall support the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

When -p is specified, export shall write to the standard output the names and values of all exported variables, in the following format:

"export %s=%s\n", <name>, <value>

if name is set, and:

"export %s\n", <name>

if name is unset.

The shell shall format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same exporting results, except:

1.
Read-only variables with values cannot be reset.

2.
Variables that were unset at the time they were output need not be reset to the unset state if a value is assigned to the variable between the time the state was saved and the time at which the saved output is reinput to the shell.

When no arguments are given, the results are unspecified.

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Zero.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Export PWD and HOME variables:

export PWD HOME

Set and export the PATH variable:

export PATH=/local/bin:$PATH

Save and restore all exported variables:

export -p > temp-fileunset a lot of variables... processing. temp-file

RATIONALE

Some historical shells use the no-argument case as the functional equivalent of what is required here with -p. This feature was left unspecified because it is not historical practice in all shells, and some scripts may rely on the now-unspecified results on their implementations. Attempts to specify the -p output as the default case were unsuccessful in achieving consensus. The -p option was added to allow portable access to the values that can be saved and then later restored using; for example, a dot script.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


link(1p)

LINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

link - call link function

SYNOPSIS

link file1 file2

DESCRIPTION

The link utility shall perform the function call:

link(file1, file2);

A user may need appropriate privilege to invoke the link utility.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

file1
The pathname of an existing file.
file2
The pathname of the new directory entry to be created.

STDIN

Not used.

INPUT FILES

Not used.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of link:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES

Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ln , unlink() , the System Interfaces volume of IEEE Std 1003.1-2001, link()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uudecode(1p)

UUDECODE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uudecode - decode a binary file

SYNOPSIS

uudecode [-o outfile][file]

DESCRIPTION

The uudecode utility shall read a file, or standard input if no file is specified, that includes data created by the uuencode utility. The uudecode utility shall scan the input file, searching for data compatible with one of the formats specified in uuencode, and attempt to create or overwrite the file described by the data (or overridden by the -o option). The pathname shall be contained in the data or specified by the -o option. The file access permission bits and contents for the file to be produced shall be contained in that data. The mode bits of the created file (other than standard output) shall be set from the file access permission bits contained in the data; that is, other attributes of the mode, including the file mode creation mask (see umask() ), shall not affect the file being produced.

If the pathname of the file to be produced exists, and the user does not have write permission on that file, uudecode shall terminate with an error. If the pathname of the file to be produced exists, and the user has write permission on that file, the existing file shall be overwritten.

If the input data was produced by uuencode on a system with a different number of bits per byte than on the target system, the results of uudecode are unspecified.

OPTIONS

The uudecode utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported by the implementation:

-o outfile
A pathname of a file that shall be used instead of any pathname contained in the input data. Specifying an outfile option-argument of /dev/stdout shall indicate standard output.

OPERANDS

The following operand shall be supported:

file
The pathname of a file containing the output of uuencode.

STDIN

See the INPUT FILES section.

INPUT FILES

The input files shall be files containing the output of uuencode.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uudecode:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If the file data header encoded by uuencode is - or /dev/stdout, or the -o /dev/stdout option overrides the file data, the standard output shall be in the same format as the file originally encoded by uuencode. Otherwise, the standard output shall not be used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output file shall be in the same format as the file originally encoded by uuencode.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The user who is invoking uudecode must have write permission on any file being created.

The output of uuencode is essentially an encoded bit stream that is not cognizant of byte boundaries. It is possible that a 9-bit byte target machine can process input from an 8-bit source, if it is aware of the requirement, but the reverse is unlikely to be satisfying. Of course, the only data that is meaningful for such a transfer between architectures is generally character data.

EXAMPLES

None.

RATIONALE

Input files are not necessarily text files, as stated by an early proposal. Although the uuencode output is a text file, that output could have been wrapped within another file or mail message that is not a text file.

The -o option is not historical practice, but was added at the request of WG15 so that the user could override the target pathname without having to edit the input data itself.

In early drafts, the [ -o outfile] option-argument allowed the use of - to mean standard output. The symbol - has only been used previously in IEEE Std 1003.1-2001 as a standard input indicator. The developers of the standard did not wish to overload the meaning of - in this manner. The /dev/stdout concept exists on most modern systems. The /dev/stdout syntax does not refer to a new special file. It is just a magic cookie to specify standard output.

FUTURE DIRECTIONS

None.

SEE ALSO

umask() , uuencode

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


make(1p)

MAKE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

make - maintain, update, and regenerate groups of programs (DEVELOPMENT)

SYNOPSIS

make [-einpqrst][-f makefile]...[ -k| -S][macro=value]...
[target_name...]

DESCRIPTION

The make utility shall update files that are derived from other files. A typical case is one where object files are derived from the corresponding source files. The make utility examines time relationships and shall update those derived files (called targets) that have modified times earlier than the modified times of the files (called prerequisites) from which they are derived. A description file (makefile) contains a description of the relationships between files, and the commands that need to be executed to update the targets to reflect changes in their prerequisites. Each specification, or rule, shall consist of a target, optional prerequisites, and optional commands to be executed when a prerequisite is newer than the target. There are two types of rule:

1.
Inference rules, which have one target name with at least one period ( '.' ) and no slash ( '/' )

2.
Target rules, which can have more than one target name

In addition, make shall have a collection of built-in macros and inference rules that infer prerequisite relationships to simplify maintenance of programs.

To receive exactly the behavior described in this section, the user shall ensure that a portable makefile shall:

*
Include the special target .POSIX

*
Omit any special target reserved for implementations (a leading period followed by uppercase letters) that has not been specified by this section

The behavior of make is unspecified if either or both of these conditions are not met.

OPTIONS

The make utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-e
Cause environment variables, including those with null values, to override macro assignments within makefiles.
-f makefile
Specify a different makefile. The argument makefile is a pathname of a description file, which is also referred to as the makefile. A pathname of '-' shall denote the standard input. There can be multiple instances of this option, and they shall be processed in the order specified. The effect of specifying the same option-argument more than once is unspecified.
-i
Ignore error codes returned by invoked commands. This mode is the same as if the special target .IGNORE were specified without prerequisites.
-k
Continue to update other targets that do not depend on the current target if a non-ignored error occurs while executing the commands to bring a target up-to-date.
-n
Write commands that would be executed on standard output, but do not execute them. However, lines with a plus sign ( '+' ) prefix shall be executed. In this mode, lines with an at sign ( '@' ) character prefix shall be written to standard output.
-p
Write to standard output the complete set of macro definitions and target descriptions. The output format is unspecified.
-q
Return a zero exit value if the target file is up-to-date; otherwise, return an exit value of 1. Targets shall not be updated if this option is specified. However, a makefile command line (associated with the targets) with a plus sign ( '+' ) prefix shall be executed.
-r
Clear the suffix list and do not use the built-in rules.
-S
Terminate make if an error occurs while executing the commands to bring a target up-to-date. This shall be the default and the opposite of -k.
-s
Do not write makefile command lines or touch messages (see -t) to standard output before executing. This mode shall be the same as if the special target .SILENT were specified without prerequisites.
-t
Update the modification time of each target as though a touch target had been executed. Targets that have prerequisites but no commands (see Target Rules ), or that are already up-to-date, shall not be touched in this manner. Write messages to standard output for each target file indicating the name of the file and that it was touched. Normally, the makefile command lines associated with each target are not executed. However, a command line with a plus sign ( '+' ) prefix shall be executed.

Any options specified in the MAKEFLAGS environment variable shall be evaluated before any options specified on the make utility command line. If the -k and -S options are both specified on the make utility command line or by the MAKEFLAGS environment variable, the last option specified shall take precedence. If the -f or -p options appear in the MAKEFLAGS environment variable, the result is undefined.

OPERANDS

The following operands shall be supported:

target_name
Target names, as defined in the EXTENDED DESCRIPTION section. If no target is specified, while make is processing the makefiles, the first target that make encounters that is not a special target or an inference rule shall be used.
macro=value
Macro definitions, as defined in Macros .

If the target_name and macro= value operands are intermixed on the make utility command line, the results are unspecified.

STDIN

The standard input shall be used only if the makefile option-argument is '-' . See the INPUT FILES section.

INPUT FILES

The input file, otherwise known as the makefile, is a text file containing rules, macro definitions, and comments. See the EXTENDED DESCRIPTION section.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of make:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
MAKEFLAGS

This variable shall be interpreted as a character string representing a series of option characters to be used as the default options. The implementation shall accept both of the following formats (but need not accept them when intermixed):

*
The characters are option letters without the leading hyphens or <blank> separation used on a make utility command line.

*
The characters are formatted in a manner similar to a portion of the make utility command line: options are preceded by hyphens and <blank>-separated as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. The macro= value macro definition operands can also be included. The difference between the contents of MAKEFLAGS and the make utility command line is that the contents of the variable shall not be subjected to the word expansions (see Word Expansions ) associated with parsing the command line values.

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PROJECTDIR

Provide a directory to be used to search for SCCS files not found in the current directory. In all of the following cases, the search for SCCS files is made in the directory SCCS in the identified directory. If the value of PROJECTDIR begins with a slash, it shall be considered an absolute pathname; otherwise, the value of PROJECTDIR is treated as a user name and that user's initial working directory shall be examined for a subdirectory src or source. If such a directory is found, it shall be used. Otherwise, the value is used as a relative pathname.

If PROJECTDIR is not set or has a null value, the search for SCCS files shall be made in the directory SCCS in the current directory.

The setting of PROJECTDIR affects all files listed in the remainder of this utility description for files with a component named SCCS.

The value of the SHELL environment variable shall not be used as a macro and shall not be modified by defining the SHELL macro in a makefile or on the command line. All other environment variables, including those with null values, shall be used as macros, as defined in Macros .

ASYNCHRONOUS EVENTS

If not already ignored, make shall trap SIGHUP, SIGTERM, SIGINT, and SIGQUIT and remove the current target unless the target is a directory or the target is a prerequisite of the special target .PRECIOUS or unless one of the -n, -p, or -q options was specified. Any targets removed in this manner shall be reported in diagnostic messages of unspecified format, written to standard error. After this cleanup process, if any, make shall take the standard action for all other signals.

STDOUT

The make utility shall write all commands to be executed to standard output unless the -s option was specified, the command is prefixed with an at sign, or the special target .SILENT has either the current target as a prerequisite or has no prerequisites. If make is invoked without any work needing to be done, it shall write a message to standard output indicating that no action was taken. If the -t option is present and a file is touched, make shall write to standard output a message of unspecified format indicating that the file was touched, including the filename of the file.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

Files can be created when the -t option is present. Additional files can also be created by the utilities invoked by make.

EXTENDED DESCRIPTION

The make utility attempts to perform the actions required to ensure that the specified targets are up-to-date. A target is considered out-of-date if it is older than any of its prerequisites or if it does not exist. The make utility shall treat all prerequisites as targets themselves and recursively ensure that they are up-to-date, processing them in the order in which they appear in the rule. The make utility shall use the modification times of files to determine whether the corresponding targets are out-of-date.

After make has ensured that all of the prerequisites of a target are up-to-date and if the target is out-of-date, the commands associated with the target entry shall be executed. If there are no commands listed for the target, the target shall be treated as up-to-date.

Makefile Syntax

A makefile can contain rules, macro definitions (see Macros ), and comments. There are two kinds of rules: inference rules and target rules. The make utility shall contain a set of built-in inference rules. If the -r option is present, the built-in rules shall not be used and the suffix list shall be cleared. Additional rules of both types can be specified in a makefile. If a rule is defined more than once, the value of the rule shall be that of the last one specified. Macros can also be defined more than once, and the value of the macro is specified in Macros . Comments start with a number sign ( '#' ) and continue until an unescaped <newline> is reached.

By default, the following files shall be tried in sequence: ./makefile and ./Makefile. If neither ./makefile or ./Makefile are found, other implementation-defined files may also be tried. On XSI-conformant systems, the additional files ./s.makefile, SCCS/s.makefile, ./s.Makefile, and SCCS/s.Makefile shall also be tried.

The -f option shall direct make to ignore any of these default files and use the specified argument as a makefile instead. If the '-' argument is specified, standard input shall be used.

The term makefile is used to refer to any rules provided by the user, whether in ./makefile or its variants, or specified by the -f option.

The rules in makefiles shall consist of the following types of lines: target rules, including special targets (see Target Rules ), inference rules (see Inference Rules ), macro definitions (see Macros ), empty lines, and comments.

When an escaped <newline> (one preceded by a backslash) is found anywhere in the makefile except in a command line, it shall be replaced, along with any leading white space on the following line, with a single <space>. When an escaped <newline> is found in a command line in a makefile, the command line shall contain the backslash, the <newline>, and the next line, except that the first character of the next line shall not be included if it is a <tab>.

Makefile Execution

Makefile command lines shall be processed one at a time by writing the makefile command line to the standard output (unless one of the conditions listed under '@' suppresses the writing) and executing the command(s) in the line. A <tab> may precede the command to standard output. Command execution shall be as if the makefile command line were the argument to the system() function. The environment for the command being executed shall contain all of the variables in the environment of make.

By default, when make receives a non-zero status from the execution of a command, it shall terminate with an error message to standard error.

Makefile command lines can have one or more of the following prefixes: a hyphen ( '-' ), an at sign ( '@' ), or a plus sign ( '+' ). These shall modify the way in which make processes the command. When a command is written to standard output, the prefix shall not be included in the output.

-
If the command prefix contains a hyphen, or the -i option is present, or the special target .IGNORE has either the current target as a prerequisite or has no prerequisites, any error found while executing the command shall be ignored.
@
If the command prefix contains an at sign and the make utility command line -n option is not specified, or the -s option is present, or the special target .SILENT has either the current target as a prerequisite or has no prerequisites, the command shall not be written to standard output before it is executed.
+
If the command prefix contains a plus sign, this indicates a makefile command line that shall be executed even if -n, -q, or -t is specified.

Target Rules

Target rules are formatted as follows:

target [target...]: [prerequisite...][;command]
[<tab>command<tab>command...]

line that does not begin with <tab>

Target entries are specified by a <blank>-separated, non-null list of targets, then a colon, then a <blank>-separated, possibly empty list of prerequisites. Text following a semicolon, if any, and all following lines that begin with a <tab>, are makefile command lines to be executed to update the target. The first non-empty line that does not begin with a <tab> or '#' shall begin a new entry. An empty or blank line, or a line beginning with '#' , may begin a new entry.

Applications shall select target names from the set of characters consisting solely of periods, underscores, digits, and alphabetics from the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set). Implementations may allow other characters in target names as extensions. The interpretation of targets containing the characters '%' and '' is implementation-defined.

A target that has prerequisites, but does not have any commands, can be used to add to the prerequisite list for that target. Only one target rule for any given target can contain commands.

Lines that begin with one of the following are called special targets and control the operation of make:

.DEFAULT
If the makefile uses this special target, the application shall ensure that it is specified with commands, but without prerequisites. The commands shall be used by make if there are no other rules available to build a target.
.IGNORE
Prerequisites of this special target are targets themselves; this shall cause errors from commands associated with them to be ignored in the same manner as specified by the -i option. Subsequent occurrences of .IGNORE shall add to the list of targets ignoring command errors. If no prerequisites are specified, make shall behave as if the -i option had been specified and errors from all commands associated with all targets shall be ignored.
.POSIX
The application shall ensure that this special target is specified without prerequisites or commands. If it appears as the first non-comment line in the makefile, make shall process the makefile as specified by this section; otherwise, the behavior of make is unspecified.
.PRECIOUS
Prerequisites of this special target shall not be removed if make receives one of the asynchronous events explicitly described in the ASYNCHRONOUS EVENTS section. Subsequent occurrences of .PRECIOUS shall add to the list of precious files. If no prerequisites are specified, all targets in the makefile shall be treated as if specified with .PRECIOUS.
.SCCS_GET
The application shall ensure that this special target is specified without prerequisites. If this special target is included in a makefile, the commands specified with this target shall replace the default commands associated with this special target (see Default Rules ). The commands specified with this target are used to get all SCCS files that are not found in the current directory.

When source files are named in a dependency list, make shall treat them just like any other target. Because the source file is presumed to be present in the directory, there is no need to add an entry for it to the makefile. When a target has no dependencies, but is present in the directory, make shall assume that that file is up-to-date. If, however, an SCCS file named SCCS/s. source_file is found for a target source_file, make compares the timestamp of the target file with that of the SCCS/s.source_file to ensure the target is up-to-date. If the target is missing, or if the SCCS file is newer, make shall automatically issue the commands specified for the .SCCS_GET special target to retrieve the most recent version. However, if the target is writable by anyone, make shall not retrieve a new version.

.SILENT
Prerequisites of this special target are targets themselves; this shall cause commands associated with them not to be written to the standard output before they are executed. Subsequent occurrences of .SILENT shall add to the list of targets with silent commands. If no prerequisites are specified, make shall behave as if the -s option had been specified and no commands or touch messages associated with any target shall be written to standard output.
.SUFFIXES
Prerequisites of .SUFFIXES shall be appended to the list of known suffixes and are used in conjunction with the inference rules (see Inference Rules ). If .SUFFIXES does not have any prerequisites, the list of known suffixes shall be cleared.

The special targets .IGNORE, .POSIX, .PRECIOUS, .SILENT, and .SUFFIXES shall be specified without commands.

Targets with names consisting of a leading period followed by the uppercase letters "POSIX" and then any other characters are reserved for future standardization. Targets with names consisting of a leading period followed by one or more uppercase letters are reserved for implementation extensions.

Macros

Macro definitions are in the form:

string1 = [string2]

The macro named string1 is defined as having the value of string2, where string2 is defined as all characters, if any, after the equal sign, up to a comment character ( '#' ) or an unescaped <newline>. Any <blank>s immediately before or after the equal sign shall be ignored.

Applications shall select macro names from the set of characters consisting solely of periods, underscores, digits, and alphabetics from the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set). A macro name shall not contain an equals sign. Implementations may allow other characters in macro names as extensions.

Macros can appear anywhere in the makefile. Macro expansions using the forms $( string1) or ${ string1} shall be replaced by string2, as follows:

*
Macros in target lines shall be evaluated when the target line is read.

*
Macros in makefile command lines shall be evaluated when the command is executed.

*
Macros in the string before the equals sign in a macro definition shall be evaluated when the macro assignment is made.

*
Macros after the equals sign in a macro definition shall not be evaluated until the defined macro is used in a rule or command, or before the equals sign in a macro definition.

The parentheses or braces are optional if string1 is a single character. The macro $$ shall be replaced by the single character '$' . If string1 in a macro expansion contains a macro expansion, the results are unspecified.

Macro expansions using the forms $( string1 [: subst1 =[ subst2 ]]) or ${ string1 [: subst1 =[ subst2 ]]} can be used to replace all occurrences of subst1 with subst2 when the macro substitution is performed. The subst1 to be replaced shall be recognized when it is a suffix at the end of a word in string1 (where a word, in this context, is defined to be a string delimited by the beginning of the line, a <blank>, or a <newline>). If string1 in a macro expansion contains a macro expansion, the results are unspecified.

Macro expansions in string1 of macro definition lines shall be evaluated when read. Macro expansions in string2 of macro definition lines shall be performed when the macro identified by string1 is expanded in a rule or command.

Macro definitions shall be taken from the following sources, in the following logical order, before the makefile(s) are read.

1.
Macros specified on the make utility command line, in the order specified on the command line. It is unspecified whether the internal macros defined in Internal Macros are accepted from this source.

2.
Macros defined by the MAKEFLAGS environment variable, in the order specified in the environment variable. It is unspecified whether the internal macros defined in Internal Macros are accepted from this source.

3.
The contents of the environment, excluding the MAKEFLAGS and SHELL variables and including the variables with null values.

4.
Macros defined in the inference rules built into make.

Macro definitions from these sources shall not override macro definitions from a lower-numbered source. Macro definitions from a single source (for example, the make utility command line, the MAKEFLAGS environment variable, or the other environment variables) shall override previous macro definitions from the same source.

Macros defined in the makefile(s) shall override macro definitions that occur before them in the makefile(s) and macro definitions from source 4. If the -e option is not specified, macros defined in the makefile(s) shall override macro definitions from source 3. Macros defined in the makefile(s) shall not override macro definitions from source 1 or source 2.

Before the makefile(s) are read, all of the make utility command line options (except -f and -p) and make utility command line macro definitions (except any for the MAKEFLAGS macro), not already included in the MAKEFLAGS macro, shall be added to the MAKEFLAGS macro, quoted in an implementation-defined manner such that when MAKEFLAGS is read by another instance of the make command, the original macro's value is recovered. Other implementation-defined options and macros may also be added to the MAKEFLAGS macro. If this modifies the value of the MAKEFLAGS macro, or, if the MAKEFLAGS macro is modified at any subsequent time, the MAKEFLAGS environment variable shall be modified to match the new value of the MAKEFLAGS macro. The result of setting MAKEFLAGS in the Makefile is unspecified.

Before the makefile(s) are read, all of the make utility command line macro definitions (except the MAKEFLAGS macro or the SHELL macro) shall be added to the environment of make. Other implementation-defined variables may also be added to the environment of make.

The SHELL macro shall be treated specially. It shall be provided by make and set to the pathname of the shell command language interpreter (see sh ). The SHELL environment variable shall not affect the value of the SHELL macro. If SHELL is defined in the makefile or is specified on the command line, it shall replace the original value of the SHELL macro, but shall not affect the SHELL environment variable. Other effects of defining SHELL in the makefile or on the command line are implementation-defined.

Inference Rules

Inference rules are formatted as follows:

target:
<tab>command
[<tab>command]...

line that does not begin with <tab> or #

The application shall ensure that the target portion is a valid target name (see Target Rules ) of the form .s2 or .s1.s2 (where .s1 and .s2 are suffixes that have been given as prerequisites of the .SUFFIXES special target and s1 and s2 do not contain any slashes or periods.) If there is only one period in the target, it is a single-suffix inference rule. Targets with two periods are double-suffix inference rules. Inference rules can have only one target before the colon.

The application shall ensure that the makefile does not specify prerequisites for inference rules; no characters other than white space shall follow the colon in the first line, except when creating the empty rule, described below. Prerequisites are inferred, as described below.

Inference rules can be redefined. A target that matches an existing inference rule shall overwrite the old inference rule. An empty rule can be created with a command consisting of simply a semicolon (that is, the rule still exists and is found during inference rule search, but since it is empty, execution has no effect). The empty rule can also be formatted as follows:

rule: ;

where zero or more <blank>s separate the colon and semicolon.

The make utility uses the suffixes of targets and their prerequisites to infer how a target can be made up-to-date. A list of inference rules defines the commands to be executed. By default, make contains a built-in set of inference rules. Additional rules can be specified in the makefile.

The special target .SUFFIXES contains as its prerequisites a list of suffixes that shall be used by the inference rules. The order in which the suffixes are specified defines the order in which the inference rules for the suffixes are used. New suffixes shall be appended to the current list by specifying a .SUFFIXES special target in the makefile. A .SUFFIXES target with no prerequisites shall clear the list of suffixes. An empty .SUFFIXES target followed by a new .SUFFIXES list is required to change the order of the suffixes.

Normally, the user would provide an inference rule for each suffix. The inference rule to update a target with a suffix .s1 from a prerequisite with a suffix .s2 is specified as a target .s2.s1. The internal macros provide the means to specify general inference rules (see Internal Macros ).

When no target rule is found to update a target, the inference rules shall be checked. The suffix of the target ( .s1) to be built is compared to the list of suffixes specified by the .SUFFIXES special targets. If the .s1 suffix is found in .SUFFIXES, the inference rules shall be searched in the order defined for the first .s2.s1 rule whose prerequisite file ( $*.s2) exists. If the target is out-of-date with respect to this prerequisite, the commands for that inference rule shall be executed.

If the target to be built does not contain a suffix and there is no rule for the target, the single suffix inference rules shall be checked. The single-suffix inference rules define how to build a target if a file is found with a name that matches the target name with one of the single suffixes appended. A rule with one suffix .s2 is the definition of how to build target from target.s2. The other suffix ( .s1) is treated as null.

A tilde ( '~' ) in the above rules refers to an SCCS file in the current directory. Thus, the rule .c~.o would transform an SCCS C-language source file into an object file ( .o). Because the s. of the SCCS files is a prefix, it is incompatible with make's suffix point of view. Hence, the '~' is a way of changing any file reference into an SCCS file reference.

Libraries

If a target or prerequisite contains parentheses, it shall be treated as a member of an archive library. For the lib( member .o) expression lib refers to the name of the archive library and member .o to the member name. The application shall ensure that the member is an object file with the .o suffix. The modification time of the expression is the modification time for the member as kept in the archive library; see ar . The .a suffix shall refer to an archive library. The .s2.a rule shall be used to update a member in the library from a file with a suffix .s2.

Internal Macros

The make utility shall maintain five internal macros that can be used in target and inference rules. In order to clearly define the meaning of these macros, some clarification of the terms target rule, inference rule, target, and prerequisite is necessary.

Target rules are specified by the user in a makefile for a particular target. Inference rules are user-specified or make-specified rules for a particular class of target name. Explicit prerequisites are those prerequisites specified in a makefile on target lines. Implicit prerequisites are those prerequisites that are generated when inference rules are used. Inference rules are applied to implicit prerequisites or to explicit prerequisites that do not have target rules defined for them in the makefile. Target rules are applied to targets specified in the makefile.

Before any target in the makefile is updated, each of its prerequisites (both explicit and implicit) shall be updated. This shall be accomplished by recursively processing each prerequisite. Upon recursion, each prerequisite shall become a target itself. Its prerequisites in turn shall be processed recursively until a target is found that has no prerequisites, at which point the recursion stops. The recursion shall then back up, updating each target as it goes.

In the definitions that follow, the word target refers to one of:

*
A target specified in the makefile

*
An explicit prerequisite specified in the makefile that becomes the target when make processes it during recursion

*
An implicit prerequisite that becomes a target when make processes it during recursion

In the definitions that follow, the word prerequisite refers to one of the following:

*
An explicit prerequisite specified in the makefile for a particular target

*
An implicit prerequisite generated as a result of locating an appropriate inference rule and corresponding file that matches the suffix of the target

The five internal macros are:

$@
The $@ shall evaluate to the full target name of the current target, or the archive filename part of a library archive target. It shall be evaluated for both target and inference rules.

For example, in the .c.a inference rule, $@ represents the out-of-date .a file to be built. Similarly, in a makefile target rule to build lib.a from file.c, $@ represents the out-of-date lib.a.

$%
The $% macro shall be evaluated only when the current target is an archive library member of the form libname( member .o). In these cases, $@ shall evaluate to libname and $% shall evaluate to member .o. The $% macro shall be evaluated for both target and inference rules.

For example, in a makefile target rule to build lib.a( file.o), $% represents file.o, as opposed to $@, which represents lib.a.

$?
The $? macro shall evaluate to the list of prerequisites that are newer than the current target. It shall be evaluated for both target and inference rules.

For example, in a makefile target rule to build prog from file1.o, file2.o, and file3.o, and where prog is not out-of-date with respect to file1.o, but is out-of-date with respect to file2.o and file3.o, $? represents file2.o and file3.o.

$<
In an inference rule, the $< macro shall evaluate to the filename whose existence allowed the inference rule to be chosen for the target. In the .DEFAULT rule, the $< macro shall evaluate to the current target name. The meaning of the $< macro shall be otherwise unspecified.

For example, in the .c.a inference rule, $< represents the prerequisite .c file.

$*
The $* macro shall evaluate to the current target name with its suffix deleted. It shall be evaluated at least for inference rules.

For example, in the .c.a inference rule, $*.o represents the out-of-date .o file that corresponds to the prerequisite .c file.

Each of the internal macros has an alternative form. When an uppercase 'D' or 'F' is appended to any of the macros, the meaning shall be changed to the directory part for 'D' and filename part for 'F' . The directory part is the path prefix of the file without a trailing slash; for the current directory, the directory part is '.' . When the $? macro contains more than one prerequisite filename, the $(?D) and $(?F) (or ${?D} and ${?F}) macros expand to a list of directory name parts and filename parts respectively.

For the target lib( member .o) and the s2.a rule, the internal macros shall be defined as:

$<
member .s2
$*
member
$@
lib
$?
member .s2
$%
member .o

Default Rules

The default rules for make shall achieve results that are the same as if the following were used. Implementations that do not support the C-Language Development Utilities option may omit CC, CFLAGS, YACC, YFLAGS, LEX, LFLAGS, LDFLAGS, and the .c, .y, and .l inference rules. Implementations that do not support FORTRAN may omit FC, FFLAGS, and the .f inference rules. Implementations may provide additional macros and rules.

SPECIAL TARGETS

.SCCS_GET: sccs $(SCCSFLAGS) get $(SCCSGETFLAGS) $@

.SUFFIXES: .o .c .y .l .a .sh .f .c~ .y~ .l~ .sh~ .f~

MACROS

MAKE=make
AR=ar
ARFLAGS=-rv
YACC=yacc
YFLAGS=
LEX=lex
LFLAGS=
LDFLAGS=
CC=c99
CFLAGS=-O
FC=fort77
FFLAGS=-O 1

GET=get
GFLAGS=
SCCSFLAGS=
SCCSGETFLAGS=-s

SINGLE SUFFIX RULES

.c:
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $<

.f:
    $(FC) $(FFLAGS) $(LDFLAGS) -o $@ $<

.sh:
    cp $< $@
    chmod a+x $@

.c~:
    $(GET) $(GFLAGS) -p $< > $*.c
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $*.c

.f~:
    $(GET) $(GFLAGS) -p $< > $*.f
    $(FC) $(FFLAGS) $(LDFLAGS) -o $@ $*.f

.sh~:
    $(GET) $(GFLAGS) -p $< > $*.sh
    cp $*.sh $@
    chmod a+x $@

DOUBLE SUFFIX RULES

.c.o:
    $(CC) $(CFLAGS) -c $<

.f.o:
    $(FC) $(FFLAGS) -c $<

.y.o:
    $(YACC) $(YFLAGS) $<
    $(CC) $(CFLAGS) -c y.tab.c
    rm -f y.tab.c
    mv y.tab.o $@

.l.o:
    $(LEX) $(LFLAGS) $<
    $(CC) $(CFLAGS) -c lex.yy.c
    rm -f lex.yy.c
    mv lex.yy.o $@

.y.c:
    $(YACC) $(YFLAGS) $<
    mv y.tab.c $@

.l.c:
    $(LEX) $(LFLAGS) $<
    mv lex.yy.c $@

.c~.o:
    $(GET) $(GFLAGS) -p $< > $*.c
    $(CC) $(CFLAGS) -c $*.c

.f~.o:
    $(GET) $(GFLAGS) -p $< > $*.f
    $(FC) $(FFLAGS) -c $*.f

.y~.o:
    $(GET) $(GFLAGS) -p $< > $*.y
    $(YACC) $(YFLAGS) $*.y
    $(CC) $(CFLAGS) -c y.tab.c
    rm -f y.tab.c
    mv y.tab.o $@

.l~.o:
    $(GET) $(GFLAGS) -p $< > $*.l
    $(LEX) $(LFLAGS) $*.l
    $(CC) $(CFLAGS) -c lex.yy.c
    rm -f lex.yy.c
    mv lex.yy.o $@

.y~.c:
    $(GET) $(GFLAGS) -p $< > $*.y
    $(YACC) $(YFLAGS) $*.y
    mv y.tab.c $@

.l~.c:
    $(GET) $(GFLAGS) -p $< > $*.l
    $(LEX) $(LFLAGS) $*.l
    mv lex.yy.c $@

.c.a:
    $(CC) -c $(CFLAGS) $<
    $(AR) $(ARFLAGS) $@ $*.o
    rm -f $*.o

.f.a:
    $(FC) -c $(FFLAGS) $<
    $(AR) $(ARFLAGS) $@ $*.o
    rm -f $*.o

EXIT STATUS

When the -q option is specified, the make utility shall exit with one of the following values:

0
Successful completion.
1
The target was not up-to-date.
>1
An error occurred.

When the -q option is not specified, the make utility shall exit with one of the following values:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

If there is a source file (such as ./source.c) and there are two SCCS files corresponding to it ( ./s.source.c and ./SCCS/s.source.c), on XSI-conformant systems make uses the SCCS file in the current directory. However, users are advised to use the underlying SCCS utilities ( admin, delta, get, and so on) or the sccs utility for all source files in a given directory. If both forms are used for a given source file, future developers are very likely to be confused.

It is incumbent upon portable makefiles to specify the .POSIX special target in order to guarantee that they are not affected by local extensions.

The -k and -S options are both present so that the relationship between the command line, the MAKEFLAGS variable, and the makefile can be controlled precisely. If the k flag is passed in MAKEFLAGS and a command is of the form:

$(MAKE) -S foo

then the default behavior is restored for the child make.

When the -n option is specified, it is always added to MAKEFLAGS . This allows a recursive make -n target to be used to see all of the action that would be taken to update target.

Because of widespread historical practice, interpreting a '#' number sign inside a variable as the start of a comment has the unfortunate side effect of making it impossible to place a number sign in a variable, thus forbidding something like:

CFLAGS = "-D COMMENT_CHAR='#'"

Many historical make utilities stop chaining together inference rules when an intermediate target is nonexistent. For example, it might be possible for a make to determine that both .y.c and .c.o could be used to convert a .y to a .o. Instead, in this case, make requires the use of a .y.o rule.

The best way to provide portable makefiles is to include all of the rules needed in the makefile itself. The rules provided use only features provided by other parts of this volume of IEEE Std 1003.1-2001. The default rules include rules for optional commands in this volume of IEEE Std 1003.1-2001. Only rules pertaining to commands that are provided are needed in an implementation's default set.

Macros used within other macros are evaluated when the new macro is used rather than when the new macro is defined. Therefore:

MACRO = value1NEW   = $(MACRO)
MACRO = value2

target:
    echo $(NEW)

would produce value2 and not value1 since NEW was not expanded until it was needed in the echo command line.

Some historical applications have been known to intermix target_name and macro=name operands on the command line, expecting that all of the macros are processed before any of the targets are dealt with. Conforming applications do not do this, although some backwards-compatibility support may be included in some implementations.

The following characters in filenames may give trouble: '=' , ':' , '`' , '" , and '@' . For inference rules, the description of $< and $? seem similar. However, an example shows the minor difference. In a makefile containing:

foo.o: foo.h

if foo.h is newer than foo.o, yet foo.c is older than foo.o, the built-in rule to make foo.o from foo.c is used, with $< equal to foo.c and $? equal to foo.h. If foo.c is also newer than foo.o, $< is equal to foo.c and $? is equal to foo.h foo.c.

EXAMPLES

1.
The following command:

make

makes the first target found in the makefile.

2.
The following command:

make junk

makes the target junk.

3.
The following makefile says that pgm depends on two files, a.o and b.o, and that they in turn depend on their corresponding source files ( a.c and b.c), and a common file incl.h:

pgm: a.o b.o
    c99 a.o b.o -o pgm
a.o: incl.h a.c
    c99 -c a.c
b.o: incl.h b.c
    c99 -c b.c

4.
An example for making optimized .o files from .c files is:

.c.o:
    c99 -c -O $*.c

or:

.c.o:
    c99 -c -O $<

5.
The most common use of the archive interface follows. Here, it is assumed that the source files are all C-language source:

lib: lib(file1.o) lib(file2.o) lib(file3.o)
    @echo lib is now up-to-date

The .c.a rule is used to make file1.o, file2.o, and file3.o and insert them into lib.

The treatment of escaped <newline>s throughout the makefile is historical practice. For example, the inference rule:

.c.o\
:

works, and the macro:

f=  bar baz\
    biz
a:
    echo ==$f==

echoes "==bar baz biz==" .

If $? were:

/usr/include/stdio.h /usr/include/unistd.h foo.h

then $(?D) would be:

/usr/include /usr/include .

and $(?F) would be:

stdio.h unistd.h foo.h

6.
The contents of the built-in rules can be viewed by running:

make -p -f /dev/null 2>/dev/null

RATIONALE

The make utility described in this volume of IEEE Std 1003.1-2001 is intended to provide the means for changing portable source code into executables that can be run on an IEEE Std 1003.1-2001-conforming system. It reflects the most common features present in System V and BSD makes.

Historically, the make utility has been an especially fertile ground for vendor and research organization-specific syntax modifications and extensions. Examples include:

*
Syntax supporting parallel execution (such as from various multi-processor vendors, GNU, and others)

*
Additional "operators" separating targets and their prerequisites (System V, BSD, and others)

*
Specifying that command lines containing the strings "${MAKE}" and "$(MAKE)" are executed when the -n option is specified (GNU and System V)

*
Modifications of the meaning of internal macros when referencing libraries (BSD and others)

*
Using a single instance of the shell for all of the command lines of the target (BSD and others)

*
Allowing spaces as well as tabs to delimit command lines (BSD)

*
Adding C preprocessor-style "include" and "ifdef" constructs (System V, GNU, BSD, and others)

*
Remote execution of command lines (Sprite and others)

*
Specifying additional special targets (BSD, System V, and most others)

Additionally, many vendors and research organizations have rethought the basic concepts of make, creating vastly extended, as well as completely new, syntaxes. Each of these versions of make fulfills the needs of a different community of users; it is unreasonable for this volume of IEEE Std 1003.1-2001 to require behavior that would be incompatible (and probably inferior) to historical practice for such a community.

In similar circumstances, when the industry has enough sufficiently incompatible formats as to make them irreconcilable, this volume of IEEE Std 1003.1-2001 has followed one or both of two courses of action. Commands have been renamed ( cksum, echo, and pax) and/or command line options have been provided to select the desired behavior ( grep, od, and pax).

Because the syntax specified for the make utility is, by and large, a subset of the syntaxes accepted by almost all versions of make, it was decided that it would be counter-productive to change the name. And since the makefile itself is a basic unit of portability, it would not be completely effective to reserve a new option letter, such as make -P, to achieve the portable behavior. Therefore, the special target .POSIX was added to the makefile, allowing users to specify "standard" behavior. This special target does not preclude extensions in the make utility, nor does it preclude such extensions being used by the makefile specifying the target; it does, however, preclude any extensions from being applied that could alter the behavior of previously valid syntax; such extensions must be controlled via command line options or new special targets. It is incumbent upon portable makefiles to specify the .POSIX special target in order to guarantee that they are not affected by local extensions.

The portable version of make described in this reference page is not intended to be the state-of-the-art software generation tool and, as such, some newer and more leading-edge features have not been included. An attempt has been made to describe the portable makefile in a manner that does not preclude such extensions as long as they do not disturb the portable behavior described here.

When the -n option is specified, it is always added to MAKEFLAGS . This allows a recursive make -n target to be used to see all of the action that would be taken to update target.

The definition of MAKEFLAGS allows both the System V letter string and the BSD command line formats. The two formats are sufficiently different to allow implementations to support both without ambiguity.

Early proposals stated that an "unquoted" number sign was treated as the start of a comment. The make utility does not pay any attention to quotes. A number sign starts a comment regardless of its surroundings.

The text about "other implementation-defined pathnames may also be tried" in addition to ./makefile and ./Makefile is to allow such extensions as SCCS/s.Makefile and other variations. It was made an implementation-defined requirement (as opposed to unspecified behavior) to highlight surprising implementations that might select something unexpected like /etc/Makefile. XSI-conformant systems also try ./s.makefile, SCCS/s.makefile, ./s.Makefile, and SCCS/s.Makefile.

Early proposals contained the macro NPROC as a means of specifying that make should use n processes to do the work required. While this feature is a valuable extension for many systems, it is not common usage and could require other non-trivial extensions to makefile syntax. This extension is not required by this volume of IEEE Std 1003.1-2001, but could be provided as a compatible extension. The macro PARALLEL is used by some historical systems with essentially the same meaning (but without using a name that is a common system limit value). It is suggested that implementors recognize the existing use of NPROC and/or PARALLEL as extensions to make.

The default rules are based on System V. The default CC= value is c99 instead of cc because this volume of IEEE Std 1003.1-2001 does not standardize the utility named cc. Thus, every conforming application would be required to define CC= c99 to expect to run. There is no advantage conferred by the hope that the makefile might hit the "preferred" compiler because this cannot be guaranteed to work. Also, since the portable makescript can only use the c99 options, no advantage is conferred in terms of what the script can do. It is a quality-of-implementation issue as to whether c99 is as valuable as cc.

The -d option to make is frequently used to produce debugging information, but is too implementation-defined to add to this volume of IEEE Std 1003.1-2001.

The -p option is not passed in MAKEFLAGS on most historical implementations and to change this would cause many implementations to break without sufficiently increased portability.

Commands that begin with a plus sign ( '+' ) are executed even if the -n option is present. Based on the GNU version of make, the behavior of -n when the plus-sign prefix is encountered has been extended to apply to -q and -t as well. However, the System V convention of forcing command execution with -n when the command line of a target contains either of the strings "$(MAKE)" or "${MAKE}" has not been adopted. This functionality appeared in early proposals, but the danger of this approach was pointed out with the following example of a portion of a makefile:

subdir:
    cd subdir; rm all_the_files; $(MAKE)

The loss of the System V behavior in this case is well-balanced by the safety afforded to other makefiles that were not aware of this situation. In any event, the command line plus-sign prefix can provide the desired functionality.

The double colon in the target rule format is supported in BSD systems to allow more than one target line containing the same target name to have commands associated with it. Since this is not functionality described in the SVID or XPG3 it has been allowed as an extension, but not mandated.

The default rules are provided with text specifying that the built-in rules shall be the same as if the listed set were used. The intent is that implementations should be able to use the rules without change, but will be allowed to alter them in ways that do not affect the primary behavior.

The best way to provide portable makefiles is to include all of the rules needed in the makefile itself. The rules provided use only features provided by other portions of this volume of IEEE Std 1003.1-2001. The default rules include rules for optional commands in this volume of IEEE Std 1003.1-2001. Only rules pertaining to commands that are provided are needed in the default set of an implementation.

One point of discussion was whether to drop the default rules list from this volume of IEEE Std 1003.1-2001. They provide convenience, but do not enhance portability of applications. The prime benefit is in portability of users who wish to type make command and have the command build from a command.c file.

The historical MAKESHELL feature was omitted. In some implementations it is used to let a user override the shell to be used to run make commands. This was confusing; for a portable make, the shell should be chosen by the makefile writer or specified on the make command line and not by a user running make.

The make utilities in most historical implementations process the prerequisites of a target in left-to-right order, and the makefile format requires this. It supports the standard idiom used in many makefiles that produce yacc programs; for example:

foo: y.tab.o lex.o main.o
    $(CC) $(CFLAGS) -o $@ t.tab.o lex.o main.o

In this example, if make chose any arbitrary order, the lex.o might not be made with the correct y.tab.h. Although there may be better ways to express this relationship, it is widely used historically. Implementations that desire to update prerequisites in parallel should require an explicit extension to make or the makefile format to accomplish it, as described previously.

The algorithm for determining a new entry for target rules is partially unspecified. Some historical makes allow blank, empty, or comment lines within the collection of commands marked by leading <tab>s. A conforming makefile must ensure that each command starts with a <tab>, but implementations are free to ignore blank, empty, and comment lines without triggering the start of a new entry.

The ASYNCHRONOUS EVENTS section includes having SIGTERM and SIGHUP, along with the more traditional SIGINT and SIGQUIT, remove the current target unless directed not to do so. SIGTERM and SIGHUP were added to parallel other utilities that have historically cleaned up their work as a result of these signals. When make receives any signal other than SIGQUIT, it is required to resend itself the signal it received so that it exits with a status that reflects the signal. The results from SIGQUIT are partially unspecified because, on systems that create core files upon receipt of SIGQUIT, the core from make would conflict with a core file from the command that was running when the SIGQUIT arrived. The main concern was to prevent damaged files from appearing up-to-date when make is rerun.

The .PRECIOUS special target was extended to affect all targets globally (by specifying no prerequisites). The .IGNORE and .SILENT special targets were extended to allow prerequisites; it was judged to be more useful in some cases to be able to turn off errors or echoing for a list of targets than for the entire makefile. These extensions to make in System V were made to match historical practice from the BSD make.

Macros are not exported to the environment of commands to be run. This was never the case in any historical make and would have serious consequences. The environment is the same as the environment to make except that MAKEFLAGS and macros defined on the make command line are added.

Some implementations do not use system() for all command lines, as required by the portable makefile format; as a performance enhancement, they select lines without shell metacharacters for direct execution by execve(). There is no requirement that system() be used specifically, but merely that the same results be achieved. The metacharacters typically used to bypass the direct execve() execution have been any of:

=  |  ^  (  )  ;  &  <  >  *  ?  [  ]  :  $  `  '  "  \  \n

The default in some advanced versions of make is to group all the command lines for a target and execute them using a single shell invocation; the System V method is to pass each line individually to a separate shell. The single-shell method has the advantages in performance and the lack of a requirement for many continued lines. However, converting to this newer method has caused portability problems with many historical makefiles, so the behavior with the POSIX makefile is specified to be the same as that of System V. It is suggested that the special target .ONESHELL be used as an implementation extension to achieve the single-shell grouping for a target or group of targets.

Novice users of make have had difficulty with the historical need to start commands with a <tab>. Since it is often difficult to discern differences between <tab>s and <space>s on terminals or printed listings, confusing bugs can arise. In early proposals, an attempt was made to correct this problem by allowing leading <blank>s instead of <tab>s. However, implementors reported many makefiles that failed in subtle ways following this change, and it is difficult to implement a make that unambiguously can differentiate between macro and command lines. There is extensive historical practice of allowing leading spaces before macro definitions. Forcing macro lines into column 1 would be a significant backwards-compatibility problem for some makefiles. Therefore, historical practice was restored.

The System V INCLUDE feature was considered, but not included. This would treat a line that began in the first column and contained INCLUDE <filename> as an indication to read <filename> at that point in the makefile. This is difficult to use in a portable way, and it raises concerns about nesting levels and diagnostics. System V, BSD, GNU, and others have used different methods for including files.

The System V dynamic dependency feature was not included. It would support:

cat: $$@.c

that would expand to;

cat: cat.c

This feature exists only in the new version of System V make and, while useful, is not in wide usage. This means that macros are expanded twice for prerequisites: once at makefile parse time and once at target update time.

Consideration was given to adding metarules to the POSIX make. This would make %.o: %.c the same as .c.o:. This is quite useful and available from some vendors, but it would cause too many changes to this make to support. It would have introduced rule chaining and new substitution rules. However, the rules for target names have been set to reserve the '%' and '' characters. These are traditionally used to implement metarules and quoting of target names, respectively. Implementors are strongly encouraged to use these characters only for these purposes.

A request was made to extend the suffix delimiter character from a period to any character. The metarules feature in newer makes solves this problem in a more general way. This volume of IEEE Std 1003.1-2001 is staying with the more conservative historical definition.

The standard output format for the -p option is not described because it is primarily a debugging option and because the format is not generally useful to programs. In historical implementations the output is not suitable for use in generating makefiles. The -p format has been variable across historical implementations. Therefore, the definition of -p was only to provide a consistently named option for obtaining make script debugging information.

Some historical implementations have not cleared the suffix list with -r.

Implementations should be aware that some historical applications have intermixed target_name and macro= value operands on the command line, expecting that all of the macros are processed before any of the targets are dealt with. Conforming applications do not do this, but some backwards-compatibility support may be warranted.

Empty inference rules are specified with a semicolon command rather than omitting all commands, as described in an early proposal. The latter case has no traditional meaning and is reserved for implementation extensions, such as in GNU make.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , ar , c99 , get , lex , sccs , sh , yacc , the System Interfaces volume of IEEE Std 1003.1-2001, exec, system()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tabs(1p)

TABS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tabs - set terminal tabs

SYNOPSIS

tabs [ -n| -a| -a2| -c| -c2| -c3| -f| -p| -s| -u][+m[n]] [-T type]

tabs [-T type][ +[n]] n1[,n2,...]

DESCRIPTION

The tabs utility shall display a series of characters that first clears the hardware terminal tab settings and then initializes the tab stops at the specified positions and optionally adjusts the margin.

The phrase "tab-stop position N" shall be taken to mean that, from the start of a line of output, tabbing to position N shall cause the next character output to be in the ( N+1)th column position on that line. The maximum number of tab stops allowed is terminal-dependent.

It need not be possible to implement tabs on certain terminals. If the terminal type obtained from the TERM environment variable or -T option represents such a terminal, an appropriate diagnostic message shall be written to standard error and tabs shall exit with a status greater than zero.

OPTIONS

The tabs utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except for various extensions: the options -a2, -c2, and -c3 are multi-character.

The following options shall be supported:

-n
Specify repetitive tab stops separated by a uniform number of column positions, n, where n is a single-digit decimal number. The default usage of tabs with no arguments shall be equivalent to tabs-8. When -0 is used, the tab stops shall be cleared and no new ones set.
-a
1,10,16,36,72
Assembler, applicable to some mainframes.
-a2
1,10,16,40,72
Assembler, applicable to some mainframes.
-c
1,8,12,16,20,55
COBOL, normal format.
-c2
1,6,10,14,49
COBOL, compact format (columns 1 to 6 omitted).
-c3
1,6,10,14,18,22,26,30,34,38,42,46,50,54,58,62,67
COBOL compact format (columns 1 to 6 omitted), with more tabs than -c2.
-f
1,7,11,15,19,23
FORTRAN
-p
1,5,9,13,17,21,25,29,33,37,41,45,49,53,57,61
PL/1
-s
1,10,55
SNOBOL
-u
1,12,20,44
Assembler, applicable to some mainframes.
-T type
Indicate the type of terminal. If this option is not supplied and the TERM variable is unset or null, an unspecified default terminal type shall be used. The setting of type shall take precedence over the value in TERM .

OPERANDS

The following operand shall be supported:

n1[,n2,...]
A single command line argument that consists of tab-stop values separated using either commas or <blank>s. The application shall ensure that the tab-stop values are positive decimal integers in strictly ascending order. If any number (except the first one) is preceded by a plus sign, it is taken as an increment to be added to the previous value. For example, the tab lists 1,10,20,30 and 1,10,+10,+10 are considered to be identical.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of tabs:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TERM
Determine the terminal type. If this variable is unset or null, and if the -T option is not specified, an unspecified default terminal type shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If standard output is a terminal, the appropriate sequence to clear and set the tab stops may be written to standard output in an unspecified format. If standard output is not a terminal, undefined results occur.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

This utility makes use of the terminal's hardware tabs and the stty tabs option.

This utility is not recommended for application use.

Some integrated display units might not have escape sequences to set tab stops, but may be set by internal system calls. On these terminals, tabs works if standard output is directed to the terminal; if output is directed to another file, however, tabs fails.

EXAMPLES

None.

RATIONALE

Consideration was given to having the tput utility handle all of the functions described in tabs. However, the separate tabs utility was retained because it seems more intuitive to use a command named tabs than tput with a new option. The tput utility does not support setting or clearing tabs, and no known historical version of tabs supports the capability of setting arbitrary tab stops.

The System V tabs interface is very complex; the version in this volume of IEEE Std 1003.1-2001 has a reduced feature list, but many of the features omitted were restored as XSI extensions even though the supported languages and coding styles are primarily historical.

There was considerable sentiment for specifying only a means of resetting the tabs back to a known state-presumably the "standard" of tabs every eight positions. The following features were omitted:

*
Setting tab stops via the first line in a file, using -- file. Since even the SVID has no complete explanation of this feature, it is doubtful that it is in widespread use.

In an early proposal, a -t tablist option was added for consistency with expand; this was later removed when inconsistencies with the historical list of tabs were identified.

Consideration was given to adding a -p option that would output the current tab settings so that they could be saved and then later restored. This was not accepted because querying the tab stops of the terminal is not a capability in historical terminfo or termcap facilities and might not be supported on a wide range of terminals.

FUTURE DIRECTIONS

None.

SEE ALSO

expand , stty , tput , unexpand

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


logger(1p)

LOGGER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

logger - log messages

SYNOPSIS

logger string ...

DESCRIPTION

The logger utility saves a message, in an unspecified manner and format, containing the string operands provided by the user. The messages are expected to be evaluated later by personnel performing system administration tasks.

It is implementation-defined whether messages written in locales other than the POSIX locale are effective.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

string
One of the string arguments whose contents are concatenated together, in the order specified, separated by single <space>s.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of logger:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. (This means diagnostics from logger to the user or application, not diagnostic messages that the user is sending to the system administrator.)
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

Unspecified.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

This utility allows logging of information for later use by a system administrator or programmer in determining why non-interactive utilities have failed. The locations of the saved messages, their format, and retention period are all unspecified. There is no method for a conforming application to read messages, once written.

EXAMPLES

A batch application, running non-interactively, tries to read a configuration file and fails; it may attempt to notify the system administrator with:

logger myname: unable to read file foo. [timestamp]

RATIONALE

The standard developers believed strongly that some method of alerting administrators to errors was necessary. The obvious example is a batch utility, running non-interactively, that is unable to read its configuration files or that is unable to create or write its results file. However, the standard developers did not wish to define the format or delivery mechanisms as they have historically been (and will probably continue to be) very system-specific, as well as involving functionality clearly outside the scope of this volume of IEEE Std 1003.1-2001.

The text with LC_MESSAGES about diagnostic messages means diagnostics from logger to the user or application, not diagnostic messages that the user is sending to the system administrator.

Multiple string arguments are allowed, similar to echo, for ease-of-use.

Like the utilities mailx and lp, logger is admittedly difficult to test. This was not deemed sufficient justification to exclude these utilities from this volume of IEEE Std 1003.1-2001. It is also arguable that they are, in fact, testable, but that the tests themselves are not portable.

FUTURE DIRECTIONS

None.

SEE ALSO

lp , mailx , write()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tail(1p)

TAIL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tail - copy the last part of a file

SYNOPSIS

tail [-f][ -c number| -n number][file]

DESCRIPTION

The tail utility shall copy its input file to the standard output beginning at a designated place.

Copying shall begin at the point in the file indicated by the -c number or -n number options. The option-argument number shall be counted in units of lines or bytes, according to the options -n and -c. Both line and byte counts start from 1.

Tails relative to the end of the file may be saved in an internal buffer, and thus may be limited in length. Such a buffer, if any, shall be no smaller than {LINE_MAX}*10 bytes.

OPTIONS

The tail utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c number
The application shall ensure that the number option-argument is a decimal integer whose sign affects the location in the file, measured in bytes, to begin the copying:
Sign Copying Starts
+ Relative to the beginning of the file.
- Relative to the end of the file.
none Relative to the end of the file.

The origin for counting shall be 1; that is, -c +1 represents the first byte of the file, -c -1 the last.

-f
If the input file is a regular file or if the file operand specifies a FIFO, do not terminate after the last line of the input file has been copied, but read and copy further bytes from the input file when they become available. If no file operand is specified and standard input is a pipe, the -f option shall be ignored. If the input file is not a FIFO, pipe, or regular file, it is unspecified whether or not the -f option shall be ignored.
-n number
This option shall be equivalent to -c number, except the starting location in the file shall be measured in lines instead of bytes. The origin for counting shall be 1; that is, -n +1 represents the first line of the file, -n -1 the last.

If neither -c nor -n is specified, -n 10 shall be assumed.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If no file operands are specified, the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

If the -c option is specified, the input file can contain arbitrary data; otherwise, the input file shall be a text file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of tail:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The designated portion of the input file shall be written to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The -c option should be used with caution when the input is a text file containing multi-byte characters; it may produce output that does not start on a character boundary.

Although the input file to tail can be any type, the results might not be what would be expected on some character special device files or on file types not described by the System Interfaces volume of IEEE Std 1003.1-2001. Since this volume of IEEE Std 1003.1-2001 does not specify the block size used when doing input, tail need not read all of the data from devices that only perform block transfers.

EXAMPLES

The -f option can be used to monitor the growth of a file that is being written by some other process. For example, the command:

tail -f fred

prints the last ten lines of the file fred, followed by any lines that are appended to fred between the time tail is initiated and killed. As another example, the command:

tail -f -c 15 fred

prints the last 15 bytes of the file fred, followed by any bytes that are appended to fred between the time tail is initiated and killed.

RATIONALE

This version of tail was created to allow conformance to the Utility Syntax Guidelines. The historical -b option was omitted because of the general non-portability of block-sized units of text. The -c option historically meant "characters", but this volume of IEEE Std 1003.1-2001 indicates that it means "bytes". This was selected to allow reasonable implementations when multi-byte characters are possible; it was not named -b to avoid confusion with the historical -b.

The origin of counting both lines and bytes is 1, matching all widespread historical implementations.

The restriction on the internal buffer is a compromise between the historical System V implementation of 4096 bytes and the BSD 32768 bytes.

The -f option has been implemented as a loop that sleeps for 1 second and copies any bytes that are available. This is sufficient, but if more efficient methods of determining when new data are available are developed, implementations are encouraged to use them.

Historical documentation indicates that tail ignores the -f option if the input file is a pipe (pipe and FIFO on systems that support FIFOs). On BSD-based systems, this has been true; on System V-based systems, this was true when input was taken from standard input, but it did not ignore the -f flag if a FIFO was named as the file operand. Since the -f option is not useful on pipes and all historical implementations ignore -f if no file operand is specified and standard input is a pipe, this volume of IEEE Std 1003.1-2001 requires this behavior. However, since the -f option is useful on a FIFO, this volume of IEEE Std 1003.1-2001 also requires that if standard input is a FIFO or a FIFO is named, the -f option shall not be ignored. Although historical behavior does not ignore the -f option for other file types, this is unspecified so that implementations are allowed to ignore the -f option if it is known that the file cannot be extended.

This was changed to the current form based on comments noting that -c was almost never used without specifying a number and that there was no need to specify -l if -n number was given.

FUTURE DIRECTIONS

None.

SEE ALSO

head

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


talk(1p)

TALK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

talk - talk to another user

SYNOPSIS

talk address [terminal]

DESCRIPTION

The talk utility is a two-way, screen-oriented communication program.

When first invoked, talk shall send a message similar to:

Message from <unspecified string>
talk: connection requested by your_addresstalk: respond with: talk your_address

to the specified address. At this point, the recipient of the message can reply by typing:

talk your_address

Once communication is established, the two parties can type simultaneously, with their output displayed in separate regions of the screen. Characters shall be processed as follows:

*
Typing the alert character shall alert the recipient's terminal.

*
Typing <control>-L shall cause the sender's screen regions to be refreshed.

*
Typing the erase and kill characters shall affect the sender's terminal in the manner described by the termios interface in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

*
Typing the interrupt or end-of-file characters shall terminate the local talk utility. Once the talk session has been terminated on one side, the other side of the talk session shall be notified that the talk session has been terminated and shall be able to do nothing except exit.

*
Typing characters from LC_CTYPE classifications print or space shall cause those characters to be sent to the recipient's terminal.

*
When and only when the stty iexten local mode is enabled, the existence and processing of additional special control characters and multi-byte or single-byte functions shall be implementation-defined.

*
Typing other non-printable characters shall cause implementation-defined sequences of printable characters to be sent to the recipient's terminal.

Permission to be a recipient of a talk message can be denied or granted by use of the mesg utility. However, a user's privilege may further constrain the domain of accessibility of other users' terminals. The talk utility shall fail when the user lacks the appropriate privileges to perform the requested action.

Certain block-mode terminals do not have all the capabilities necessary to support the simultaneous exchange of messages required for talk. When this type of exchange cannot be supported on such terminals, the implementation may support an exchange with reduced levels of simultaneous interaction or it may report an error describing the terminal-related deficiency.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

address
The recipient of the talk session. One form of address is the <user name>, as returned by the who utility. Other address formats and how they are handled are unspecified.
terminal
If the recipient is logged in more than once, the terminal argument can be used to indicate the appropriate terminal name. If terminal is not specified, the talk message shall be displayed on one or more accessible terminals in use by the recipient. The format of terminal shall be the same as that returned by the who utility.

STDIN

Characters read from standard input shall be copied to the recipient's terminal in an unspecified manner. If standard input is not a terminal, talk shall write a diagnostic message and exit with a non-zero status.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of talk:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files). If the recipient's locale does not use an LC_CTYPE equivalent to the sender's, the results are undefined.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TERM
Determine the name of the invoker's terminal type. If this variable is unset or null, an unspecified default terminal type shall be used.

ASYNCHRONOUS EVENTS

When the talk utility receives a SIGINT signal, the utility shall terminate and exit with a zero status. It shall take the standard action for all other signals.

STDOUT

If standard output is a terminal, characters copied from the recipient's standard input may be written to standard output. Standard output also may be used for diagnostic messages. If standard output is not a terminal, talk shall exit with a non-zero status.

STDERR

None.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred or talk was invoked on a terminal incapable of supporting it.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Because the handling of non-printable, non- <space>s is tied to the stty description of iexten, implementation extensions within the terminal driver can be accessed. For example, some implementations provide line editing functions with certain control character sequences.

EXAMPLES

None.

RATIONALE

The write utility was included in this volume of IEEE Std 1003.1-2001 since it can be implemented on all terminal types. The talk utility, which cannot be implemented on certain terminals, was considered to be a "better" communications interface. Both of these programs are in widespread use on historical implementations. Therefore, both utilities have been specified.

All references to networking abilities (talking to a user on another system) were removed as being outside the scope of this volume of IEEE Std 1003.1-2001.

Historical BSD and System V versions of talk terminate both of the conversations when either user breaks out of the session. This can lead to adverse consequences if a user unwittingly continues to enter text that is interpreted by the shell when the other terminates the session. Therefore, the version of talk specified by this volume of IEEE Std 1003.1-2001 requires both users to terminate their end of the session explicitly.

Only messages sent to the terminal of the invoking user can be internationalized in any way:

*
The original "Message from <unspecified string> ..." message sent to the terminal of the recipient cannot be internationalized because the environment of the recipient is as yet inaccessible to the talk utility. The environment of the invoking party is irrelevant.

*
Subsequent communication between the two parties cannot be internationalized because the two parties may specify different languages in their environment (and non-portable characters cannot be mapped from one language to another).

*
Neither party can be required to communicate in a language other than C and/or the one specified by their environment because unavailable terminal hardware support (for example, fonts) may be required.

The text in the STDOUT section reflects the usage of the verb "display" in this section; some talk implementations actually use standard output to write to the terminal, but this volume of IEEE Std 1003.1-2001 does not require that to be the case.

The format of the terminal name is unspecified, but the descriptions of ps, talk, who, and write require that they all use or accept the same format.

The handling of non-printable characters is partially implementation-defined because the details of mapping them to printable sequences is not needed by the user. Historical implementations, for security reasons, disallow the transmission of non-printable characters that may send commands to the other terminal.

FUTURE DIRECTIONS

None.

SEE ALSO

mesg , stty , who , write , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iconv(1p)

ICONV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iconv - codeset conversion

SYNOPSIS

iconv [-cs] -f frommap -t tomap [file ...]

iconv -f fromcode [-cs] [-t tocode [file ...]

iconv -t tocode [-cs] [-f fromcode] [file ...]

iconv -l

DESCRIPTION

The iconv utility shall convert the encoding of characters in file from one codeset to another and write the results to standard output.

When the options indicate that charmap files are used to specify the codesets (see OPTIONS), the codeset conversion shall be accomplished by performing a logical join on the symbolic character names in the two charmaps. The implementation need not support the use of charmap files for codeset conversion unless the POSIX2_LOCALEDEF symbol is defined on the system.

OPTIONS

The iconv utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Omit any characters that are invalid in the codeset of the input file from the output. When -c is not used, the results of encountering invalid characters in the input stream (either those that are not characters in the codeset of the input file or that have no corresponding character in the codeset of the output file) shall be specified in the system documentation. The presence or absence of -c shall not affect the exit status of iconv.
-f fromcodeset

Identify the codeset of the input file. The implementation shall recognize the following two forms of the fromcodeset option-argument:

fromcode
The fromcode option-argument must not contain a slash character. It shall be interpreted as the name of one of the codeset descriptions provided by the implementation in an unspecified format. Valid values of fromcode are implementation-defined.
frommap
The frommap option-argument must contain a slash character. It shall be interpreted as the pathname of a charmap file as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.4, Character Set Description File. If the pathname does not represent a valid, readable charmap file, the results are undefined.

If this option is omitted, the codeset of the current locale shall be used.

-l
Write all supported fromcode and tocode values to standard output in an unspecified format.
-s
Suppress any messages written to standard error concerning invalid characters. When -s is not used, the results of encountering invalid characters in the input stream (either those that are not valid characters in the codeset of the input file or that have no corresponding character in the codeset of the output file) shall be specified in the system documentation. The presence or absence of -s shall not affect the exit status of iconv.
-t tocodeset
Identify the codeset to be used for the output file. The implementation shall recognize the following two forms of the tocodeset option-argument:
tocode
The semantics shall be equivalent to the -f fromcode option.
tomap
The semantics shall be equivalent to the tomap option.

If this option is omitted, the codeset of the current locale shall be used.

If either -f or -t represents a charmap file, but the other does not (or is omitted), or both -f and -t are omitted, the results are undefined.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If no file operands are specified, or if a file operand is '-' , the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' .

INPUT FILES

The input file shall be a text file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of iconv:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments). During translation of the file, this variable is superseded by the use of the fromcode option-argument.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

When the -l option is used, the standard output shall contain all supported fromcode and tocode values, written in an unspecified format.

When the -l option is not used, the standard output shall contain the sequence of characters read from the input files, translated to the specified codeset. Nothing else shall be written to the standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The user must ensure that both charmap files use the same symbolic names for characters the two codesets have in common.

EXAMPLES

The following example converts the contents of file mail.x400 from the ISO/IEC 6937:1994 standard codeset to the ISO/IEC 8859-1:1998 standard codeset, and stores the results in file mail.local:

iconv -f IS6937 -t IS8859 mail.x400 > mail.local

RATIONALE

The iconv utility can be used portably only when the user provides two charmap files as option-arguments. This is because a single charmap provided by the user cannot reliably be joined with the names in a system-provided character set description. The valid values for fromcode and tocode are implementation-defined and do not have to have any relation to the charmap mechanisms. As an aid to interactive users, the -l option was adopted from the Plan 9 operating system. It writes information concerning these implementation-defined values. The format is unspecified because there are many possible useful formats that could be chosen, such as a matrix of valid combinations of fromcode and tocode. The -l option is not intended for shell script usage; conforming applications will have to use charmaps.

FUTURE DIRECTIONS

None.

SEE ALSO

gencat

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tsort(1p)

TSORT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tsort - topological sort

SYNOPSIS

tsort [file]

DESCRIPTION

The tsort utility shall write to standard output a totally ordered list of items consistent with a partial ordering of items contained in the input.

The application shall ensure that the input consists of pairs of items (non-empty strings) separated by <blank>s. Pairs of different items indicate ordering. Pairs of identical items indicate presence, but not ordering.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

file
A pathname of a text file to order. If no file operand is given, the standard input shall be used.

STDIN

The standard input shall be a text file that is used if no file operand is given.

INPUT FILES

The input file named by the file operand is a text file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of tsort:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be a text file consisting of the order list produced from the partially ordered input.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The LC_COLLATE variable need not affect the actions of tsort. The output ordering is not lexicographic, but depends on the pairs of items given as input.

EXAMPLES

The command:

tsort <<EOF
a b c c d e
g g
f g e f
h h
EOF

produces the output:

a
b
c
d
e
f
g
h

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

None.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mailx(1p)

MAILX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mailx - process messages

SYNOPSIS

Send Mode

mailx [-s subject] address...

Receive Mode

mailx -e

mailx [-HiNn][-F][-u user]

mailx -f[-HiNn][-F][file]

DESCRIPTION

The mailx utility provides a message sending and receiving facility. It has two major modes, selected by the options used: Send Mode and Receive Mode.

On systems that do not support the User Portability Utilities option, an application using mailx shall have the ability to send messages in an unspecified manner (Send Mode). Unless the first character of one or more lines is tilde ( '~' ), all characters in the input message shall appear in the delivered message, but additional characters may be inserted in the message before it is retrieved.

On systems supporting the User Portability Utilities option, mail-receiving capabilities and other interactive features, Receive Mode, described below, also shall be enabled.

Send Mode

Send Mode can be used by applications or users to send messages from the text in standard input.

Receive Mode

Receive Mode is more oriented towards interactive users. Mail can be read and sent in this interactive mode.

When reading mail, mailx provides commands to facilitate saving, deleting, and responding to messages. When sending mail, mailx allows editing, reviewing, and other modification of the message as it is entered.

Incoming mail shall be stored in one or more unspecified locations for each user, collectively called the system mailbox for that user. When mailx is invoked in Receive Mode, the system mailbox shall be the default place to find new mail. As messages are read, they shall be marked to be moved to a secondary file for storage, unless specific action is taken. This secondary file is called the mbox and is normally located in the directory referred to by the HOME environment variable (see MBOX in the ENVIRONMENT VARIABLES section for a description of this file). Messages shall remain in this file until explicitly removed. When the -f option is used to read mail messages from secondary files, messages shall be retained in those files unless specifically removed. All three of these locations-system mailbox, mbox, and secondary file-are referred to in this section as simply "mailboxes", unless more specific identification is required.

OPTIONS

The mailx utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported. (Only the -s subject option shall be required on all systems. The other options are required only on systems supporting the User Portability Utilities option.)

-e
Test for the presence of mail in the system mailbox. The mailx utility shall write nothing and exit with a successful return code if there is mail to read.
-f
Read messages from the file named by the file operand instead of the system mailbox. (See also folder.) If no file operand is specified, read messages from mbox instead of the system mailbox.
-F
Record the message in a file named after the first recipient. The name is the login-name portion of the address found first on the To: line in the mail header. Overrides the record variable, if set (see Internal Variables in mailx .)
-H
Write a header summary only.
-i
Ignore interrupts. (See also ignore.)
-n
Do not initialize from the system default start-up file. See the EXTENDED DESCRIPTION section.
-N
Do not write an initial header summary.
-s subject
Set the Subject header field to subject. All characters in the subject string shall appear in the delivered message. The results are unspecified if subject is longer than {LINE_MAX} - 10 bytes or contains a <newline>.
-u user
Read the system mailbox of the login name user. This shall only be successful if the invoking user has the appropriate privileges to read the system mailbox of that user.

OPERANDS

The following operands shall be supported:

address
Addressee of message. When -n is specified and no user start-up files are accessed (see the EXTENDED DESCRIPTION section), the user or application shall ensure this is an address to pass to the mail delivery system. Any system or user start-up files may enable aliases (see alias under Commands in mailx ) that may modify the form of address before it is passed to the mail delivery system.
file
A pathname of a file to be read instead of the system mailbox when -f is specified. The meaning of the file option-argument shall be affected by the contents of the folder internal variable; see Internal Variables in mailx .

STDIN

When mailx is invoked in Send Mode (the first synopsis line), standard input shall be the message to be delivered to the specified addresses. When in Receive Mode, user commands shall be accepted from stdin. If the User Portability Utilities option is not supported, standard input lines beginning with a tilde ( '~' ) character produce unspecified results.

If the User Portability Utilities option is supported, then in both Send and Receive Modes, standard input lines beginning with the escape character (usually tilde ( '~' )) shall affect processing as described in Command Escapes in mailx .

INPUT FILES

When mailx is used as described by this volume of IEEE Std 1003.1-2001, the file option-argument (see the -f option) and the mbox shall be text files containing mail messages, formatted as described in the OUTPUT FILES section. The nature of the system mailbox is unspecified; it need not be a file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of mailx:

DEAD
Determine the pathname of the file in which to save partial messages in case of interrupts or delivery errors. The default shall be dead.letter in the directory named by the HOME variable. The behavior of mailx in saving partial messages is unspecified if the User Portability Utilities option is not supported and DEAD is not defined with the value /dev/null.
EDITOR
Determine the name of a utility to invoke when the edit (see Commands in mailx ) or ~e (see Command Escapes in mailx ) command is used. The default editor is unspecified. On XSI-conformant systems it is ed. The effects of this variable are unspecified if the User Portability Utilities option is not supported.
HOME
Determine the pathname of the user's home directory.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the handling of case-insensitive address and header-field comparisons.
LC_TIME
Determine the format and contents of the date and time strings written by mailx.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
LISTER
Determine a string representing the command for writing the contents of the folder directory to standard output when the folders command is given (see folders in Commands in mailx ). Any string acceptable as a command_string operand to the sh -c command shall be valid. If this variable is null or not set, the output command shall be ls. The effects of this variable are unspecified if the User Portability Utilities option is not supported.
MAILRC
Determine the pathname of the start-up file. The default shall be .mailrc in the directory referred to by the HOME environment variable. The behavior of mailx is unspecified if the User Portability Utilities option is not supported and MAILRC is not defined with the value /dev/null.
MBOX
Determine a pathname of the file to save messages from the system mailbox that have been read. The exit command shall override this function, as shall saving the message explicitly in another file. The default shall be mbox in the directory named by the HOME variable. The effects of this variable are unspecified if the User Portability Utilities option is not supported.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PAGER
Determine a string representing an output filtering or pagination command for writing the output to the terminal. Any string acceptable as a command_string operand to the sh -c command shall be valid. When standard output is a terminal device, the message output shall be piped through the command if the mailx internal variable crt is set to a value less the number of lines in the message; see Internal Variables in mailx . If the PAGER variable is null or not set, the paginator shall be either more or another paginator utility documented in the system documentation. The effects of this variable are unspecified if the User Portability Utilities option is not supported.
SHELL
Determine the name of a preferred command interpreter. The default shall be sh. The effects of this variable are unspecified if the User Portability Utilities option is not supported.
TERM
If the internal variable screen is not specified, determine the name of the terminal type to indicate in an unspecified manner the number of lines in a screenful of headers. If TERM is not set or is set to null, an unspecified default terminal type shall be used and the value of a screenful is unspecified. The effects of this variable are unspecified if the User Portability Utilities option is not supported.
TZ
This variable may determine the timezone used to calculate date and time strings written by mailx. If TZ is unset or null, an unspecified default timezone shall be used.
VISUAL
Determine a pathname of a utility to invoke when the visual command (see Commands in mailx ) or ~v command-escape (see Command Escapes in mailx ) is used. If this variable is null or not set, the full-screen editor shall be vi. The effects of this variable are unspecified if the User Portability Utilities option is not supported.

ASYNCHRONOUS EVENTS

When mailx is in Send Mode and standard input is not a terminal, it shall take the standard action for all signals.

In Receive Mode, or in Send Mode when standard input is a terminal, if a SIGINT signal is received:

1.
If in command mode, the current command, if there is one, shall be aborted, and a command-mode prompt shall be written.

2.
If in input mode:
a.
If ignore is set, mailx shall write "@\n" , discard the current input line, and continue processing, bypassing the message-abort mechanism described in item 2b.

b.
If the interrupt was received while sending mail, either when in Receive Mode or in Send Mode, a message shall be written, and another subsequent interrupt, with no other intervening characters typed, shall be required to abort the mail message. If in Receive Mode and another interrupt is received, a command-mode prompt shall be written. If in Send Mode and another interrupt is received, mailx shall terminate with a non-zero status.

In both cases listed in item b, if the message is not empty:

i.
If save is enabled and the file named by DEAD can be created, the message shall be written to the file named by DEAD . If the file exists, the message shall be written to replace the contents of the file.

ii.
If save is not enabled, or the file named by DEAD cannot be created, the message shall not be saved.

The mailx utility shall take the standard action for all other signals.

STDOUT

In command and input modes, all output, including prompts and messages, shall be written to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

Various mailx commands and command escapes can create or add to files, including the mbox, the dead-letter file, and secondary mailboxes. When mailx is used as described in this volume of IEEE Std 1003.1-2001, these files shall be text files, formatted as follows: line beginning with From<space>
[one or more header-lines; see Commands in mailx ]
empty line
[zero or more body lines
empty line]
[line beginning with From<space>...]

where each message begins with the From <space> line shown, preceded by the beginning of the file or an empty line. (The From <space> line is considered to be part of the message header, but not one of the header-lines referred to in Commands in mailx ; thus, it shall not be affected by the discard, ignore, or retain commands.) The formats of the remainder of the From <space> line and any additional header lines are unspecified, except that none shall be empty. The format of a message body line is also unspecified, except that no line following an empty line shall start with From <space>; mailx shall modify any such user-entered message body lines (following an empty line and beginning with From <space>) by adding one or more characters to precede the 'F' ; it may add these characters to From <space> lines that are not preceded by an empty line.

When a message from the system mailbox or entered by the user is not a text file, it is implementation-defined how such a message is stored in files written by mailx.

EXTENDED DESCRIPTION

The entire EXTENDED DESCRIPTION section shall apply only to implementations supporting the User Portability Utilities option.

The mailx utility cannot guarantee support for all character encodings in all circumstances. For example, inter-system mail may be restricted to 7-bit data by the underlying network, 8-bit data need not be portable to non-internationalized systems, and so on. Under these circumstances, it is recommended that only characters defined in the ISO/IEC 646:1991 standard International Reference Version (equivalent to ASCII) 7-bit range of characters be used.

When mailx is invoked using one of the Receive Mode synopsis forms, it shall write a page of header-summary lines (if -N was not specified and there are messages, see below), followed by a prompt indicating that mailx can accept regular commands (see Commands in mailx ); this is termed command mode. The page of header-summary lines shall contain the first new message if there are new messages, or the first unread message if there are unread messages, or the first message. When mailx is invoked using the Send Mode synopsis and standard input is a terminal, if no subject is specified on the command line and the asksub variable is set, a prompt for the subject shall be written. At this point, mailx shall be in input mode. This input mode shall also be entered when using one of the Receive Mode synopsis forms and a reply or new message is composed using the reply, Reply, followup, Followup, or mail commands and standard input is a terminal. When the message is typed and the end of the message is encountered, the message shall be passed to the mail delivery software. Commands can be entered by beginning a line with the escape character (by default, tilde ( '~' )) followed by a single command letter and optional arguments. See Commands in mailx for a summary of these commands. It is unspecified what effect these commands will have if standard input is not a terminal when a message is entered using either the Send Mode synopsis, or the Read Mode commands reply, Reply, followup, Followup, or mail.

Note:
For notational convenience, this section uses the default escape character, tilde, in all references and examples.

At any time, the behavior of mailx shall be governed by a set of environmental and internal variables. These are flags and valued parameters that can be set and cleared via the mailx set and unset commands.

Regular commands are of the form:

[command] [msglist] [argument ...]

If no command is specified in command mode, next shall be assumed. In input mode, commands shall be recognized by the escape character, and lines not treated as commands shall be taken as input for the message.

In command mode, each message shall be assigned a sequential number, starting with 1.

All messages have a state that shall affect how they are displayed in the header summary and how they are retained or deleted upon termination of mailx. There is at any time the notion of a current message, which shall be marked by a '>' at the beginning of a line in the header summary. When mailx is invoked using one of the Receive Mode synopsis forms, the current message shall be the first new message, if there is a new message, or the first unread message if there is an unread message, or the first message if there are any messages, or unspecified if there are no messages in the mailbox. Each command that takes an optional list of messages (msglist) or an optional single message (message) on which to operate shall leave the current message set to the highest-numbered message of the messages specified, unless the command deletes messages, in which case the current message shall be set to the first undeleted message (that is, a message not in the deleted state) after the highest-numbered message deleted by the command, if one exists, or the first undeleted message before the highest-numbered message deleted by the command, if one exists, or to an unspecified value if there are no remaining undeleted messages. All messages shall be in one of the following states:

new
The message is present in the system mailbox and has not been viewed by the user or moved to any other state. Messages in state new when mailx quits shall be retained in the system mailbox.
unread
The message has been present in the system mailbox for more than one invocation of mailx and has not been viewed by the user or moved to any other state. Messages in state unread when mailx quits shall be retained in the system mailbox.
read
The message has been processed by one of the following commands: ~f, ~m, ~F, ~M, copy, mbox, next, pipe, print, Print, top, type, Type, undelete. The delete, dp, and dt commands may also cause the next message to be marked as read, depending on the value of the autoprint variable. Messages that are in the system mailbox and in state read when mailx quits shall be saved in the mbox, unless the internal variable hold was set. Messages that are in the mbox or in a secondary mailbox and in state read when mailx quits shall be retained in their current location.
deleted
The message has been processed by one of the following commands: delete, dp, dt. Messages in state deleted when mailx quits shall be deleted. Deleted messages shall be ignored until mailx quits or changes mailboxes or they are specified to the undelete command; for example, the message specification / string shall only search the subject lines of messages that have not yet been deleted, unless the command operating on the list of messages is undelete. No deleted message or deleted message header shall be displayed by any mailx command other than undelete.
preserved
The message has been processed by a preserve command. When mailx quits, the message shall be retained in its current location.
saved
The message has been processed by one of the following commands: save or write. If the current mailbox is the system mailbox, and the internal variable keepsave is set, messages in the state saved shall be saved to the file designated by the MBOX variable (see the ENVIRONMENT VARIABLES section). If the current mailbox is the system mailbox, messages in the state saved shall be deleted from the current mailbox, when the quit or file command is used to exit the current mailbox.

The header-summary line for each message shall indicate the state of the message.

Many commands take an optional list of messages ( msglist) on which to operate, which defaults to the current message. A msglist is a list of message specifications separated by <blank>s, which can include:

n
Message number n.
+
The next undeleted message, or the next deleted message for the undelete command.
-
The next previous undeleted message, or the next previous deleted message for the undelete command.
.
The current message.
^
The first undeleted message, or the first deleted message for the undelete command.
$
The last message.
*
All messages.
n-m
An inclusive range of message numbers.
address
All messages from address; any address as shown in a header summary shall be matchable in this form.
/string
All messages with string in the subject line (case ignored).
:c
All messages of type c, where c shall be one of:
d
Deleted messages.
n
New messages.
o
Old messages (any not in state read or new).
r
Read messages.
u
Unread messages.

Other commands take an optional message ( message) on which to operate, which defaults to the current message. All of the forms allowed for msglist are also allowed for message, but if more than one message is specified, only the first shall be operated on.

Other arguments are usually arbitrary strings whose usage depends on the command involved.

Start-Up in mailx

At start-up time, mailx shall take the following steps in sequence:

1.
Establish all variables at their stated default values.

2.
Process command line options, overriding corresponding default values.

3.
Import any of the DEAD , EDITOR , MBOX , LISTER , PAGER , SHELL , or VISUAL variables that are present in the environment, overriding the corresponding default values.

4.
Read mailx commands from an unspecified system start-up file, unless the -n option is given, to initialize any internal mailx variables and aliases.

5.
Process the start-up file of mailx commands named in the user MAILRC variable.

Most regular mailx commands are valid inside start-up files, the most common use being to set up initial display options and alias lists. The following commands shall be invalid in the start-up file: !, edit, hold, mail, preserve, reply, Reply, shell, visual, Copy, followup, and Followup. Any errors in the start-up file shall either cause mailx to terminate with a diagnostic message and a non-zero status or to continue after writing a diagnostic message, ignoring the remainder of the lines in the start-up file.

A blank line in a start-up file shall be ignored.

Internal Variables in mailx

The following variables are internal mailx variables. Each internal variable can be set via the mailx set command at any time. The unset and set no name commands can be used to erase variables.

In the following list, variables shown as:

variable

represent Boolean values. Variables shown as:

variable=value

shall be assigned string or numeric values. For string values, the rules in Commands in mailx concerning filenames and quoting shall also apply.

The defaults specified here may be changed by the implementation-defined system start-up file unless the user specifies the -n option.

allnet
All network names whose login name components match shall be treated as identical. This shall cause the msglist message specifications to behave similarly. The default shall be noallnet. See also the alternates command and the metoo variable.
append
Append messages to the end of the mbox file upon termination instead of placing them at the beginning. The default shall be noappend. This variable shall not affect the save command when saving to mbox.
ask, asksub
Prompt for a subject line on outgoing mail if one is not specified on the command line with the -s option. The ask and asksub forms are synonyms; the system shall refer to asksub and noasksub in its messages, but shall accept ask and noask as user input to mean asksub and noasksub. It shall not be possible to set both ask and noasksub, or noask and asksub. The default shall be asksub, but no prompting shall be done if standard input is not a terminal.
askbcc
Prompt for the blind copy list. The default shall be noaskbcc.
askcc
Prompt for the copy list. The default shall be noaskcc.
autoprint
Enable automatic writing of messages after delete and undelete commands. The default shall be noautoprint.
bang
Enable the special-case treatment of exclamation marks ( '!' ) in escape command lines; see the escape command and Command Escapes in mailx . The default shall be nobang, disabling the expansion of '!' in the command argument to the ~! command and the ~<! command escape.
cmd=command

Set the default command to be invoked by the pipe command. The default shall be nocmd.

crt=number
Pipe messages having more than number lines through the command specified by the value of the PAGER variable. The default shall be nocrt. If it is set to null, the value used is implementation-defined.
debug
Enable verbose diagnostics for debugging. Messages are not delivered. The default shall be nodebug.
dot
When dot is set, a period on a line by itself during message input from a terminal shall also signify end-of-file (in addition to normal end-of-file). The default shall be nodot. If ignoreeof is set (see below), a setting of nodot shall be ignored and the period is the only method to terminate input mode.
escape=c
Set the command escape character to be the character 'c' . By default, the command escape character shall be tilde. If escape is unset, tilde shall be used; if it is set to null, command escaping shall be disabled.
flipr
Reverse the meanings of the R and r commands. The default shall be noflipr.
folder=directory

The default directory for saving mail files. User-specified filenames beginning with a plus sign ( '+' ) shall be expanded by preceding the filename with this directory name to obtain the real pathname. If directory does not start with a slash ( '/' ), the contents of HOME shall be prefixed to it. The default shall be nofolder. If folder is unset or set to null, user-specified filenames beginning with '+' shall refer to files in the current directory that begin with the literal '+' character. See also outfolder below. The folder value need not affect the processing of the files named in MBOX and DEAD .

header
Enable writing of the header summary when entering mailx in Receive Mode. The default shall be header.
hold
Preserve all messages that are read in the system mailbox instead of putting them in the mbox save file. The default shall be nohold.
ignore
Ignore interrupts while entering messages. The default shall be noignore.
ignoreeof
Ignore normal end-of-file during message input. Input can be terminated only by entering a period ( '.' ) on a line by itself or by the ~. command escape. The default shall be noignoreeof. See also dot above.
indentprefix=string

A string that shall be added as a prefix to each line that is inserted into the message by the ~m command escape. This variable shall default to one <tab>.

keep
When a system mailbox, secondary mailbox, or mbox is empty, truncate it to zero length instead of removing it. The default shall be nokeep.
keepsave
Keep the messages that have been saved from the system mailbox into other files in the file designated by the variable MBOX , instead of deleting them. The default shall be nokeepsave.
metoo
Suppress the deletion of the login name of the user from the recipient list when replying to a message or sending to a group. The default shall be nometoo.
onehop
When responding to a message that was originally sent to several recipients, the other recipient addresses are normally forced to be relative to the originating author's machine for the response. This flag disables alteration of the recipients' addresses, improving efficiency in a network where all machines can send directly to all other machines (that is, one hop away). The default shall be noonehop.
outfolder
Cause the files used to record outgoing messages to be located in the directory specified by the folder variable unless the pathname is absolute. The default shall be nooutfolder. See the record variable.
page
Insert a <form-feed> after each message sent through the pipe created by the pipe command. The default shall be nopage.
prompt=string

Set the command-mode prompt to string. If string is null or if noprompt is set, no prompting shall occur. The default shall be to prompt with the string "? " .

quiet
Refrain from writing the opening message and version when entering mailx. The default shall be noquiet.
record=file
Record all outgoing mail in the file with the pathname file. The default shall be norecord. See also outfolder above.
save
Enable saving of messages in the dead-letter file on interrupt or delivery error. See the variable DEAD for the location of the dead-letter file. The default shall be save.
screen=number

Set the number of lines in a screenful of headers for the headers and z commands. If screen is not specified, a value based on the terminal type identified by the TERM environment variable, the window size, the baud rate, or some combination of these shall be used.

sendwait
Wait for the background mailer to finish before returning. The default shall be nosendwait.
showto
When the sender of the message was the user who is invoking mailx, write the information from the To: line instead of the From: line in the header summary. The default shall be noshowto.
sign=string
Set the variable inserted into the text of a message when the ~a command escape is given. The default shall be nosign. The character sequences '\t' and '\n' shall be recognized in the variable as <tab>s and <newline>s, respectively. (See also ~i in Command Escapes in mailx .)
Sign=string
Set the variable inserted into the text of a message when the ~A command escape is given. The default shall be noSign. The character sequences '\t' and '\n' shall be recognized in the variable as <tab>s and <newline>s, respectively.
toplines=number

Set the number of lines of the message to write with the top command. The default shall be 5.

Commands in mailx

The following mailx commands shall be provided. In the following list, header refers to lines from the message header, as shown in the OUTPUT FILES section. Header-line refers to lines within the header that begin with one or more non-white-space characters, immediately followed by a colon and white space and continuing until the next line beginning with a non-white-space character or an empty line. Header-field refers to the portion of a header line prior to the first colon in that line.

For each of the commands listed below, the command can be entered as the abbreviation (those characters in the Synopsis command word preceding the '[' ), the full command (all characters shown for the command word, omitting the '[' and ']' ), or any truncation of the full command down to the abbreviation. For example, the exit command (shown as ex[it] in the Synopsis) can be entered as ex, exi, or exit.

The arguments to commands can be quoted, using the following methods:

*
An argument can be enclosed between paired double-quotes ( "" ) or single-quotes ( '' ); any white space, shell word expansion, or backslash characters within the quotes shall be treated literally as part of the argument. A double-quote shall be treated literally within single-quotes and vice versa. These special properties of the quote marks shall occur only when they are paired at the beginning and end of the argument.

*
A backslash outside of the enclosing quotes shall be discarded and the following character treated literally as part of the argument.

*
An unquoted backslash at the end of a command line shall be discarded and the next line shall continue the command.

Filenames, where expected, shall be subjected to the following transformations, in sequence:

*
If the filename begins with an unquoted plus sign, and the folder variable is defined (see the folder variable), the plus sign shall be replaced by the value of the folder variable followed by a slash. If the folder variable is unset or is set to null, the filename shall be unchanged.

*
Shell word expansions shall be applied to the filename (see Word Expansions ). If more than a single pathname results from this expansion and the command is expecting one file, the effects are unspecified.

Declare Aliases

Synopsis:

a[lias] [alias [address...]]g[roup] [alias [address...]]

Add the given addresses to the alias specified by alias. The names shall be substituted when alias is used as a recipient address specified by the user in an outgoing message (that is, other recipients addressed indirectly through the reply command shall not be substituted in this manner). Mail address alias substitution shall apply only when the alias string is used as a full address; for example, when hlj is an alias, hlj@posix.com does not trigger the alias substitution. If no arguments are given, write a listing of the current aliases to standard output. If only an alias argument is given, write a listing of the specified alias to standard output. These listings need not reflect the same order of addresses that were entered.

Declare Alternatives

Synopsis:

alt[ernates] name...

(See also the metoo command.) Declare a list of alternative names for the user's login. When responding to a message, these names shall be removed from the list of recipients for the response. The comparison of names shall be in a case-insensitive manner. With no arguments, alternates shall write the current list of alternative names.

Change Current Directory

Synopsis:

cd [directory]ch[dir] [directory]

Change directory. If directory is not specified, the contents of HOME shall be used.

Copy Messages

Synopsis:

c[opy] [file]c[opy] [msglist] fileC[opy] [msglist]

Copy messages to the file named by the pathname file without marking the messages as saved. Otherwise, it shall be equivalent to the save command.

In the capitalized form, save the specified messages in a file whose name is derived from the author of the message to be saved, without marking the messages as saved. Otherwise, it shall be equivalent to the Save command.

Delete Messages

Synopsis:

d[elete] [msglist]

Mark messages for deletion from the mailbox. The deletions shall not occur until mailx quits (see the quit command) or changes mailboxes (see the folder command). If autoprint is set and there are messages remaining after the delete command, the current message shall be written as described for the print command (see the print command); otherwise, the mailx prompt shall be written.

Discard Header Fields

Synopsis:

di[scard] [header-field...]ig[nore] [header-field...]

Suppress the specified header fields when writing messages. Specified header-fields shall be added to the list of suppressed header fields. Examples of header fields to ignore are status and cc. The fields shall be included when the message is saved. The Print and Type commands shall override this command. The comparison of header fields shall be in a case-insensitive manner. If no arguments are specified, write a list of the currently suppressed header fields to standard output; the listing need not reflect the same order of header fields that were entered.

If both retain and discard commands are given, discard commands shall be ignored.

Delete Messages and Display

Synopsis:

dp [msglist]dt [msglist]

Delete the specified messages as described for the delete command, except that the autoprint variable shall have no effect, and the current message shall be written only if it was set to a message after the last message deleted by the command. Otherwise, an informational message to the effect that there are no further messages in the mailbox shall be written, followed by the mailx prompt.

Echo a String

Synopsis:

ec[ho] string ...

Echo the given strings, equivalent to the shell echo utility.

Edit Messages

Synopsis:

e[dit] [msglist]

Edit the given messages. The messages shall be placed in a temporary file and the utility named by the EDITOR variable is invoked to edit each file in sequence. The default EDITOR is unspecified.

The edit command does not modify the contents of those messages in the mailbox.

Exit

Synopsis:

ex[it]x[it]

Exit from mailx without changing the mailbox. No messages shall be saved in the mbox (see also quit).

Change Folder

Synopsis:

fi[le] [file]fold[er] [file]

Quit (see the quit command) from the current file of messages and read in the file named by the pathname file. If no argument is given, the name and status of the current mailbox shall be written.

Several unquoted special characters shall be recognized when used as file names, with the following substitutions:

%
The system mailbox for the invoking user.
%user
The system mailbox for user.
#
The previous file.
&
The current mbox.
+file
The named file in the folder directory. (See the folder variable.)

The default file shall be the current mailbox.

Display List of Folders

Synopsis:

folders

Write the names of the files in the directory set by the folder variable. The command specified by the LISTER environment variable shall be used (see the ENVIRONMENT VARIABLES section).

Follow Up Specified Messages

Synopsis:

fo[llowup] [message]F[ollowup] [msglist]

In the lowercase form, respond to a message, recording the response in a file whose name is derived from the author of the message. See also the save and copy commands and outfolder.

In the capitalized form, respond to the first message in the msglist, sending the message to the author of each message in the msglist. The subject line shall be taken from the first message and the response shall be recorded in a file whose name is derived from the author of the first message. See also the Save and Copy commands and outfolder.

Both forms shall override the record variable, if set.

Display Header Summary for Specified Messages

Synopsis:

f[rom] [msglist]

Write the header summary for the specified messages.

Display Header Summary

Synopsis:

h[eaders] [message]

Write the page of headers that includes the message specified. If the message argument is not specified, the current message shall not change. However, if the message argument is specified, the current message shall become the message that appears at the top of the page of headers that includes the message specified. The screen variable sets the number of headers per page. See also the z command.

Help

Synopsis:

hel[p]?

Write a summary of commands.

Hold Messages

Synopsis:

ho[ld] [msglist]pre[serve] [msglist]

Mark the messages in msglist to be retained in the mailbox when mailx terminates. This shall override any commands that might previously have marked the messages to be deleted. During the current invocation of mailx, only the delete, dp, or dt commands shall remove the preserve marking of a message.

Execute Commands Conditionally

Synopsis:

i[f] s|r
mail-commands
el[se]
mail-commands
en[dif]

Execute commands conditionally, where if s executes the following mail-commands, up to an else or endif, if the program is in Send Mode, and if r shall cause the mail-commands to be executed only in Receive Mode.

List Available Commands

Synopsis:

l[ist]

Write a list of all commands available. No explanation shall be given.

Mail a Message

Synopsis:

m[ail] address...

Mail a message to the specified addresses or aliases.

Direct Messages to mbox

Synopsis:

mb[ox] [msglist]

Arrange for the given messages to end up in the mbox save file when mailx terminates normally. See MBOX . See also the exit and quit commands.

Process Next Specified Message

Synopsis:

n[ext] [message]

If the current message has not been written (for example, by the print command) since mailx started or since any other message was the current message, behave as if the print command was entered. Otherwise, if there is an undeleted message after the current message, make it the current message and behave as if the print command was entered. Otherwise, an informational message to the effect that there are no further messages in the mailbox shall be written, followed by the mailx prompt.

Pipe Message

Synopsis:

pi[pe] [[msglist] command]| [[msglist] command]

Pipe the messages through the given command by invoking the command interpreter specified by SHELL with two arguments: -c and command. (See also sh -c.) The application shall ensure that the command is given as a single argument. Quoting, described previously, can be used to accomplish this. If no arguments are given, the current message shall be piped through the command specified by the value of the cmd variable. If the page variable is set, a <form-feed> shall be inserted after each message.

Display Message with Headers

Synopsis:

P[rint] [msglist]T[ype] [msglist]

Write the specified messages, including all header lines, to standard output. Override suppression of lines by the discard, ignore, and retain commands. If crt is set, the messages longer than the number of lines specified by the crt variable shall be paged through the command specified by the PAGER environment variable.

Display Message

Synopsis:

p[rint] [msglist]t[ype] [msglist]

Write the specified messages to standard output. If crt is set, the messages longer than the number of lines specified by the crt variable shall be paged through the command specified by the PAGER environment variable.

Quit

Synopsis:

q[uit]
end-of-file

Terminate mailx, storing messages that were read in mbox (if the current mailbox is the system mailbox and unless hold is set), deleting messages that have been explicitly saved (unless keepsave is set), discarding messages that have been deleted, and saving all remaining messages in the mailbox.

Reply to a Message List

Synopsis:

R[eply] [msglist]R[espond] [msglist]

Mail a reply message to the sender of each message in the msglist. The subject line shall be formed by concatenating Re: <space> (unless it already begins with that string) and the subject from the first message. If record is set to a filename, the response shall be saved at the end of that file.

See also the flipr variable.

Reply to a Message

Synopsis:

r[eply] [message]r[espond] [message]

Mail a reply message to all recipients included in the header of the message. The subject line shall be formed by concatenating Re: <space> (unless it already begins with that string) and the subject from the message. If record is set to a filename, the response shall be saved at the end of that file.

See also the flipr variable.

Retain Header Fields

Synopsis:

ret[ain] [header-field...]

Retain the specified header fields when writing messages. This command shall override all discard and ignore commands. The comparison of header fields shall be in a case-insensitive manner. If no arguments are specified, write a list of the currently retained header fields to standard output; the listing need not reflect the same order of header fields that were entered.

Save Messages

Synopsis:

s[ave] [file]s[ave] [msglist] fileS[ave] [msglist]

Save the specified messages in the file named by the pathname file, or the mbox if the file argument is omitted. The file shall be created if it does not exist; otherwise, the messages shall be appended to the file. The message shall be put in the state saved, and shall behave as specified in the description of the saved state when the current mailbox is exited by the quit or file command.

In the capitalized form, save the specified messages in a file whose name is derived from the author of the first message. The name of the file shall be taken to be the author's name with all network addressing stripped off. See also the Copy, followup, and Followup commands and outfolder variable.

Set Variables

Synopsis:

se[t] [name[=[string]] ...] [name=number ...] [noname ...]

Define one or more variables called name. The variable can be given a null, string, or numeric value. Quoting and backslash escapes can occur anywhere in string, as described previously, as if the string portion of the argument were the entire argument. The forms name and name= shall be equivalent to name="" for variables that take string values. The set command without arguments shall write a list of all defined variables and their values. The no name form shall be equivalent to unset name.

Invoke a Shell

Synopsis:

sh[ell]

Invoke an interactive command interpreter (see also SHELL ).

Display Message Size

Synopsis:

si[ze] [msglist]

Write the size in bytes of each of the specified messages.

Read mailx Commands From a File

Synopsis:

so[urce] file

Read and execute commands from the file named by the pathname file and return to command mode.

Display Beginning of Messages

Synopsis:

to[p] [msglist]

Write the top few lines of each of the specified messages. If the toplines variable is set, it is taken as the number of lines to write. The default shall be 5.

Touch Messages

Synopsis:

tou[ch] [msglist]

Touch the specified messages. If any message in msglist is not specifically deleted nor saved in a file, it shall be placed in the mbox upon normal termination. See exit and quit.

Delete Aliases

Synopsis:

una[lias] [alias]...

Delete the specified alias names. If a specified alias does not exist, the results are unspecified.

Undelete Messages

Synopsis:

u[ndelete] [msglist]

Change the state of the specified messages from deleted to read. If autoprint is set, the last message of those restored shall be written. If msglist is not specified, the message shall be selected as follows:

*
If there are any deleted messages that follow the current message, the first of these shall be chosen.

*
Otherwise, the last deleted message that also precedes the current message shall be chosen.

Unset Variables

Synopsis:

uns[et] name...

Cause the specified variables to be erased.

Edit Message with Full-Screen Editor

Synopsis:

v[isual] [msglist]

Edit the given messages with a screen editor. Each message shall be placed in a temporary file, and the utility named by the VISUAL variable shall be invoked to edit each file in sequence. The default editor shall be vi.

The visual command does not modify the contents of those messages in the mailbox.

Write Messages to a File

Synopsis:

w[rite] [msglist] file

Write the given messages to the file specified by the pathname file, minus the message header. Otherwise, it shall be equivalent to the save command.

Scroll Header Display

Synopsis:

z[+|-]

Scroll the header display forward (if '+' is specified or if no option is specified) or backward (if '-' is specified) one screenful. The number of headers written shall be set by the screen variable.

Invoke Shell Command

Synopsis:

!command

Invoke the command interpreter specified by SHELL with two arguments: -c and command. (See also sh -c.) If the bang variable is set, each unescaped occurrence of '!' in command shall be replaced with the command executed by the previous ! command or ~! command escape.

Null Command

Synopsis:

# comment

This null command (comment) shall be ignored by mailx.

Display Current Message Number

Synopsis:

=

Write the current message number.

Command Escapes in mailx

The following commands can be entered only from input mode, by beginning a line with the escape character (by default, tilde ( '~' )). See the escape variable description for changing this special character. The format for the commands shall be:

<escape-character><command-char><separator>[<arguments>]

where the <separator> can be zero or more <blank>s.

In the following descriptions, the application shall ensure that the argument command (but not mailx-command) is a shell command string. Any string acceptable to the command interpreter specified by the SHELL variable when it is invoked as SHELL -c command_string shall be valid. The command can be presented as multiple arguments (that is, quoting is not required).

Command escapes that are listed with msglist or mailx-command arguments are invalid in Send Mode and produce unspecified results.

~! command
Invoke the command interpreter specified by SHELL with two arguments: -c and command; and then return to input mode. If the bang variable is set, each unescaped occurrence of '!' in command shall be replaced with the command executed by the previous ! command or ~! command escape.
~.
Simulate end-of-file (terminate message input).
~: mailx-command, ~_ mailx-command

Perform the command-level request.

~?
Write a summary of command escapes.
~A
This shall be equivalent to ~i Sign.
~a
This shall be equivalent to ~i sign.
~b name...
Add the names to the blind carbon copy ( Bcc) list.
~c name...
Add the names to the carbon copy ( Cc) list.
~d
Read in the dead-letter file. See DEAD for a description of this file.
~e
Invoke the editor, as specified by the EDITOR environment variable, on the partial message.
~f [msglist]
Forward the specified messages. The specified messages shall be inserted into the current message without alteration. This command escape also shall insert message headers into the message with field selection affected by the discard, ignore, and retain commands.
~F [msglist]
This shall be the equivalent of the ~f command escape, except that all headers shall be included in the message, regardless of previous discard, ignore, and retain commands.
~h
If standard input is a terminal, prompt for a Subject line and the To, Cc, and Bcc lists. Other implementation-defined headers may also be presented for editing. If the field is written with an initial value, it can be edited as if it had just been typed.
~i string
Insert the value of the named variable, followed by a <newline>, into the text of the message. If the string is unset or null, the message shall not be changed.
~m [msglist]
Insert the specified messages into the message, prefixing non-empty lines with the string in the indentprefix variable. This command escape also shall insert message headers into the message, with field selection affected by the discard, ignore, and retain commands.
~M [msglist]
This shall be the equivalent of the ~m command escape, except that all headers shall be included in the message, regardless of previous discard, ignore, and retain commands.
~p
Write the message being entered. If the message is longer than crt lines (see Internal Variables in mailx ), the output shall be paginated as described for the PAGER variable.
~q
Quit (see the quit command) from input mode by simulating an interrupt. If the body of the message is not empty, the partial message shall be saved in the dead-letter file. See DEAD for a description of this file.
~r file, ~<
file, ~r !command, ~< !command

Read in the file specified by the pathname file. If the argument begins with an exclamation mark ( '!' ), the rest of the string shall be taken as an arbitrary system command; the command interpreter specified by SHELL shall be invoked with two arguments: -c and command. The standard output of command shall be inserted into the message.

~s string
Set the subject line to string.
~t name...
Add the given names to the To list.
~v
Invoke the full-screen editor, as specified by the VISUAL environment variable, on the partial message.
~w file
Write the partial message, without the header, onto the file named by the pathname file. The file shall be created or the message shall be appended to it if the file exists.
~x
Exit as with ~q, except the message shall not be saved in the dead-letter file.
~| command
Pipe the body of the message through the given command by invoking the command interpreter specified by SHELL with two arguments: -c and command. If the command returns a successful exit status, the standard output of the command shall replace the message. Otherwise, the message shall remain unchanged. If the command fails, an error message giving the exit status shall be written.

EXIT STATUS

When the -e option is specified, the following exit values are returned:

0
Mail was found.
>0
Mail was not found or an error occurred.

Otherwise, the following exit values are returned:

0
Successful completion; note that this status implies that all messages were sent, but it gives no assurances that any of them were actually delivered.
>0
An error occurred.

CONSEQUENCES OF ERRORS

When in input mode (Receive Mode) or Send Mode:

*
If an error is encountered processing a command escape (see Command Escapes in mailx ), a diagnostic message shall be written to standard error, and the message being composed may be modified, but this condition shall not prevent the message from being sent.

*
Other errors shall prevent the sending of the message.

When in command mode:

*
Default.

The following sections are informative.

APPLICATION USAGE

Delivery of messages to remote systems requires the existence of communication paths to such systems. These need not exist.

Input lines are limited to {LINE_MAX} bytes, but mailers between systems may impose more severe line-length restrictions. This volume of IEEE Std 1003.1-2001 does not place any restrictions on the length of messages handled by mailx, and for delivery of local messages the only limitations should be the normal problems of available disk space for the target mail file. When sending messages to external machines, applications are advised to limit messages to less than 100000 bytes because some mail gateways impose message-length restrictions.

The format of the system mailbox is intentionally unspecified. Not all systems implement system mailboxes as flat files, particularly with the advent of multimedia mail messages. Some system mailboxes may be multiple files, others records in a database. The internal format of the messages themselves is specified with the historical format from Version 7, but only after the messages have been saved in some file other than the system mailbox. This was done so that many historical applications expecting text-file mailboxes are not broken.

Some new formats for messages can be expected in the future, probably including binary data, bit maps, and various multimedia objects. As described here, mailx is not prohibited from handling such messages, but it must store them as text files in secondary mailboxes (unless some extension, such as a variable or command line option, is used to change the stored format). Its method of doing so is implementation-defined and might include translating the data into text file-compatible or readable form or omitting certain portions of the message from the stored output.

The discard and ignore commands are not inverses of the retain command. The retain command discards all header-fields except those explicitly retained. The discard command keeps all header-fields except those explicitly discarded. If headers exist on the retained header list, discard and ignore commands are ignored.

EXAMPLES

None.

RATIONALE

The standard developers felt strongly that a method for applications to send messages to specific users was necessary. The obvious example is a batch utility, running non-interactively, that wishes to communicate errors or results to a user. However, the actual format, delivery mechanism, and method of reading the message are clearly beyond the scope of this volume of IEEE Std 1003.1-2001.

The intent of this command is to provide a simple, portable interface for sending messages non-interactively. It merely defines a "front-end" to the historical mail system. It is suggested that implementations explicitly denote the sender and recipient in the body of the delivered message. Further specification of formats for either the message envelope or the message itself were deliberately not made, as the industry is in the midst of changing from the current standards to a more internationalized standard and it is probably incorrect, at this time, to require either one.

Implementations are encouraged to conform to the various delivery mechanisms described in the CCITT X.400 standards or to the equivalent Internet standards, described in Internet Request for Comment (RFC) documents RFC 819, RFC 822, RFC 920, RFC 921, and RFC 1123.

Many historical systems modified each body line that started with From by prefixing the 'F' with '>' . It is unnecessary, but allowed, to do that when the string does not follow a blank line because it cannot be confused with the next header.

The edit and visual commands merely edit the specified messages in a temporary file. They do not modify the contents of those messages in the mailbox; such a capability could be added as an extension, such as by using different command names.

The restriction on a subject line being {LINE_MAX}-10 bytes is based on the historical format that consumes 10 bytes for Subject: and the trailing <newline>. Many historical mailers that a message may encounter on other systems are not able to handle lines that long, however.

Like the utilities logger and lp, mailx admittedly is difficult to test. This was not deemed sufficient justification to exclude this utility from this volume of IEEE Std 1003.1-2001. It is also arguable that it is, in fact, testable, but that the tests themselves are not portable.

When mailx is being used by an application that wishes to receive the results as if none of the User Portability Utilities option features were supported, the DEAD environment variable must be set to /dev/null. Otherwise, it may be subject to the file creations described in mailx ASYNCHRONOUS EVENTS. Similarly, if the MAILRC environment variable is not set to /dev/null, historical versions of mailx and Mail read initialization commands from a file before processing begins. Since the initialization that a user specifies could alter the contents of messages an application is trying to send, such applications must set MAILRC to /dev/null.

The description of LC_TIME uses "may affect" because many historical implementations do not or cannot manipulate the date and time strings in the incoming mail headers. Some headers found in incoming mail do not have enough information to determine the timezone in which the mail originated, and, therefore, mailx cannot convert the date and time strings into the internal form that then is parsed by routines like strftime() that can take LC_TIME settings into account. Changing all these times to a user-specified format is allowed, but not required.

The paginator selected when PAGER is null or unset is partially unspecified to allow the System V historical practice of using pg as the default. Bypassing the pagination function, such as by declaring that cat is the paginator, would not meet with the intended meaning of this description. However, any "portable user" would have to set PAGER explicitly to get his or her preferred paginator on all systems. The paginator choice was made partially unspecified, unlike the VISUAL editor choice (mandated to be vi) because most historical pagers follow a common theme of user input, whereas editors differ dramatically.

Options to specify addresses as cc (carbon copy) or bcc (blind carbon copy) were considered to be format details and were omitted.

A zero exit status implies that all messages were sent, but it gives no assurances that any of them were actually delivered. The reliability of the delivery mechanism is unspecified and is an appropriate marketing distinction between systems.

In order to conform to the Utility Syntax Guidelines, a solution was required to the optional file option-argument to -f. By making file an operand, the guidelines are satisfied and users remain portable. However, it does force implementations to support usage such as:

mailx -fin mymail.box

The no name method of unsetting variables is not present in all historical systems, but it is in System V and provides a logical set of commands corresponding to the format of the display of options from the mailx set command without arguments.

The ask and asksub variables are the names selected by BSD and System V, respectively, for the same feature. They are synonyms in this volume of IEEE Std 1003.1-2001.

The mailx echo command was not documented in the BSD version and has been omitted here because it is not obviously useful for interactive users.

The default prompt on the System V mailx is a question mark, on BSD Mail an ampersand. Since this volume of IEEE Std 1003.1-2001 chose the mailx name, it kept the System V default, assuming that BSD users would not have difficulty with this minor incompatibility (that they can override).

The meanings of r and R are reversed between System V mailx and SunOS Mail. Once again, since this volume of IEEE Std 1003.1-2001 chose the mailx name, it kept the System V default, but allows the SunOS user to achieve the desired results using flipr, an internal variable in System V mailx, although it has not been documented in the SVID.

The indentprefix variable, the retain and unalias commands, and the ~F and ~M command escapes were adopted from 4.3 BSD Mail.

The version command was not included because no sufficiently general specification of the version information could be devised that would still be useful to a portable user. This command name should be used by suppliers who wish to provide version information about the mailx command.

The "implementation-specific (unspecified) system start-up file" historically has been named /etc/mailx.rc, but this specific name and location are not required.

The intent of the wording for the next command is that if any command has already displayed the current message it should display a following message, but, otherwise, it should display the current message. Consider the command sequence:

next 3
delete 3
next

where the autoprint option was not set. The normative text specifies that the second next command should display a message following the third message, because even though the current message has not been displayed since it was set by the delete command, it has been displayed since the current message was anything other than message number 3. This does not always match historical practice in some implementations, where the command file address followed by next (or the default command) would skip the message for which the user had searched.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , ed , ls , more , vi

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mesg(1p)

MESG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mesg - permit or deny messages

SYNOPSIS

mesg [y|n]

DESCRIPTION

The mesg utility shall control whether other users are allowed to send messages via write, talk, or other utilities to a terminal device. The terminal device affected shall be determined by searching for the first terminal in the sequence of devices associated with standard input, standard output, and standard error, respectively. With no arguments, mesg shall report the current state without changing it. Processes with appropriate privileges may be able to send messages to the terminal independent of the current state.

OPTIONS

None.

OPERANDS

The following operands shall be supported in the POSIX locale:

y
Grant permission to other users to send messages to the terminal device.
n
Deny permission to other users to send messages to the terminal device.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of mesg:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written (by mesg) to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If no operand is specified, mesg shall display the current terminal state in an unspecified format.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Receiving messages is allowed.
1
Receiving messages is not allowed.
>1
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The mechanism by which the message status of the terminal is changed is unspecified. Therefore, unspecified actions may cause the status of the terminal to change after mesg has successfully completed. These actions may include, but are not limited to: another invocation of the mesg utility, login procedures; invocation of the stty utility, invocation of the chmod utility or chmod() function, and so on.

EXAMPLES

None.

RATIONALE

The terminal changed by mesg is that associated with the standard input, output, or error, rather than the controlling terminal for the session. This is because users logged in more than once should be able to change any of their login terminals without having to stop the job running in those sessions. This is not a security problem involving the terminals of other users because appropriate privileges would be required to affect the terminal of another user.

The method of checking each of the first three file descriptors in sequence until a terminal is found was adopted from System V.

The file /dev/tty is not specified for the terminal device because it was thought to be too restrictive. Typical environment changes for the n operand are that write permissions are removed for others and group from the appropriate device. It was decided to leave the actual description of what is done as unspecified because of potential differences between implementations.

The format for standard output is unspecified because of differences between historical implementations. This output is generally not useful to shell scripts (they can use the exit status), so exact parsing of the output is unnecessary.

FUTURE DIRECTIONS

None.

SEE ALSO

talk , write()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


patch(1p)

PATCH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

patch - apply changes to files

SYNOPSIS

patch [-blNR][ -c| -e| -n][-d dir][-D define][-i patchfile]
[-o outfile][-p num][-r rejectfile][file]

DESCRIPTION

The patch utility shall read a source (patch) file containing any of the three forms of difference (diff) listings produced by the diff utility (normal, context, or in the style of ed) and apply those differences to a file. By default, patch shall read from the standard input.

The patch utility shall attempt to determine the type of the diff listing, unless overruled by a -c, -e, or -n option.

If the patch file contains more than one patch, patch shall attempt to apply each of them as if they came from separate patch files. (In this case, the application shall ensure that the name of the patch file is determinable for each diff listing.)

OPTIONS

The patch utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-b
Save a copy of the original contents of each modified file, before the differences are applied, in a file of the same name with the suffix .orig appended to it. If the file already exists, it shall be overwritten; if multiple patches are applied to the same file, the .orig file shall be written only for the first patch. When the -o outfile option is also specified, file .orig shall not be created but, if outfile already exists, outfile .orig shall be created.
-c
Interpret the patch file as a context difference (the output of the utility diff when the -c or -C options are specified).
-d dir
Change the current directory to dir before processing as described in the EXTENDED DESCRIPTION section.
-D define
Mark changes with one of the following C preprocessor constructs:

#ifdef define
...
#endif

#ifndef define
...
#endif

optionally combined with the C preprocessor construct #else. If the patched file is processed with the C preprocessor, where the macro define is defined, the output shall contain the changes from the patch file; otherwise, the output shall not contain the patches specified in the patch file.

-e
Interpret the patch file as an ed script, rather than a diff script.
-i patchfile
Read the patch information from the file named by the pathname patchfile, rather than the standard input.
-l
(The letter ell.) Cause any sequence of <blank>s in the difference script to match any sequence of <blank>s in the input file. Other characters shall be matched exactly.
-n
Interpret the script as a normal difference.
-N
Ignore patches where the differences have already been applied to the file; by default, already-applied patches shall be rejected.
-o outfile
Instead of modifying the files (specified by the file operand or the difference listings) directly, write a copy of the file referenced by each patch, with the appropriate differences applied, to outfile. Multiple patches for a single file shall be applied to the intermediate versions of the file created by any previous patches, and shall result in multiple, concatenated versions of the file being written to outfile.
-p num
For all pathnames in the patch file that indicate the names of files to be patched, delete num pathname components from the beginning of each pathname. If the pathname in the patch file is absolute, any leading slashes shall be considered the first component (that is, -p 1 shall remove the leading slashes). Specifying -p 0 shall cause the full pathname to be used. If -p is not specified, only the basename (the final pathname component) shall be used.
-R
Reverse the sense of the patch script; that is, assume that the difference script was created from the new version to the old version. The -R option cannot be used with ed scripts. The patch utility shall attempt to reverse each portion of the script before applying it. Rejected differences shall be saved in swapped format. If this option is not specified, and until a portion of the patch file is successfully applied, patch attempts to apply each portion in its reversed sense as well as in its normal sense. If the attempt is successful, the user shall be prompted to determine whether the -R option should be set.
-r rejectfile
Override the default reject filename. In the default case, the reject file shall have the same name as the output file, with the suffix .rej appended to it; see Patch Application .

OPERANDS

The following operand shall be supported:

file
A pathname of a file to patch.

STDIN

See the INPUT FILES section.

INPUT FILES

Input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of patch:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
LC_TIME
Determine the locale for recognizing the format of file timestamps written by the diff utility in a context-difference input file.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used for diagnostic and informational messages.

OUTPUT FILES

The output of the patch utility, the save files ( .orig suffixes), and the reject files ( .rej suffixes) shall be text files.

EXTENDED DESCRIPTION

A patch file may contain patching instructions for more than one file; filenames shall be determined as specified in Filename Determination . When the -b option is specified, for each patched file, the original shall be saved in a file of the same name with the suffix .orig appended to it.

For each patched file, a reject file may also be created as noted in Patch Application . In the absence of a -r option, the name of this file shall be formed by appending the suffix .rej to the original filename.

Patch File Format

The patch file shall contain zero or more lines of header information followed by one or more patches. Each patch shall contain zero or more lines of filename identification in the format produced by diff -c, and one or more sets of diff output, which are customarily called hunks.

The patch utility shall recognize the following expression in the header information:

Index: pathname

The file to be patched is named pathname.

If all lines (including headers) within a patch begin with the same leading sequence of <blank>s, the patch utility shall remove this sequence before proceeding. Within each patch, if the type of difference is context, the patch utility shall recognize the following expressions:

*** filename timestamp

The patches arose from filename.

--- filename timestamp

The patches should be applied to filename.

Each hunk within a patch shall be the diff output to change a line range within the original file. The line numbers for successive hunks within a patch shall occur in ascending order.

Filename Determination

If no file operand is specified, patch shall perform the following steps to determine the filename to use:

1.
If the type of diff is context, the patch utility shall delete pathname components (as specified by the -p option) from the filename on the line beginning with "***" , then test for the existence of this file relative to the current directory (or the directory specified with the -d option). If the file exists, the patch utility shall use this filename.

2.
If the type of diff is context, the patch utility shall delete the pathname components (as specified by the -p option) from the filename on the line beginning with "---" , then test for the existence of this file relative to the current directory (or the directory specified with the -d option). If the file exists, the patch utility shall use this filename.

3.
If the header information contains a line beginning with the string Index:, the patch utility shall delete pathname components (as specified by the -p option) from this line, then test for the existence of this file relative to the current directory (or the directory specified with the -d option). If the file exists, the patch utility shall use this filename.

4.
If an SCCS directory exists in the current directory, patch shall attempt to perform a get -e SCCS/s. filename command to retrieve an editable version of the file. If the file exists, the patch utility shall use this filename.

5.
The patch utility shall write a prompt to standard output and request a filename interactively from the controlling terminal (for example, /dev/tty).

Patch Application

If the -c, -e, or -n option is present, the patch utility shall interpret information within each hunk as a context difference, an ed difference, or a normal difference, respectively. In the absence of any of these options, the patch utility shall determine the type of difference based on the format of information within the hunk.

For each hunk, the patch utility shall begin to search for the place to apply the patch at the line number at the beginning of the hunk, plus or minus any offset used in applying the previous hunk. If lines matching the hunk context are not found, patch shall scan both forwards and backwards at least 1000 bytes for a set of lines that match the hunk context.

If no such place is found and it is a context difference, then another scan shall take place, ignoring the first and last line of context. If that fails, the first two and last two lines of context shall be ignored and another scan shall be made. Implementations may search more extensively for installation locations.

If no location can be found, the patch utility shall append the hunk to the reject file. The rejected hunk shall be written in context-difference format regardless of the format of the patch file. If the input was a normal or ed-style difference, the reject file may contain differences with zero lines of context. The line numbers on the hunks in the reject file may be different from the line numbers in the patch file since they shall reflect the approximate locations for the failed hunks in the new file rather than the old one.

If the type of patch is an ed diff, the implementation may accomplish the patching by invoking the ed utility.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
1
One or more lines were written to a reject file.
>1
An error occurred.

CONSEQUENCES OF ERRORS

Patches that cannot be correctly placed in the file shall be written to a reject file.

The following sections are informative.

APPLICATION USAGE

The -R option does not work with ed scripts because there is too little information to reconstruct the reverse operation.

The -p option makes it possible to customize a patch file to local user directory structures without manually editing the patch file. For example, if the filename in the patch file was:

/curds/whey/src/blurfl/blurfl.c

Setting -p 0 gives the entire pathname unmodified; -p 1 gives:

curds/whey/src/blurfl/blurfl.c

without the leading slash, -p 4 gives:

blurfl/blurfl.c

and not specifying -p at all gives:

blurfl.c .

EXAMPLES

None.

RATIONALE

Some of the functionality in historical patch implementations was not specified. The following documents those features present in historical implementations that have not been specified.

A deleted piece of functionality was the '+' pseudo-option allowing an additional set of options and a patch file operand to be given. This was seen as being insufficiently useful to standardize.

In historical implementations, if the string "Prereq:" appeared in the header, the patch utility would search for the corresponding version information (the string specified in the header, delimited by <blank>s or the beginning or end of a line or the file) anywhere in the original file. This was deleted as too simplistic and insufficiently trustworthy a mechanism to standardize. For example, if:

Prereq: 1.2

were in the header, the presence of a delimited 1.2 anywhere in the file would satisfy the prerequisite.

The following options were dropped from historical implementations of patch as insufficiently useful to standardize:

-b
The -b option historically provided a method for changing the name extension of the backup file from the default .orig. This option has been modified and retained in this volume of IEEE Std 1003.1-2001.
-F
The -F option specified the number of lines of a context diff to ignore when searching for a place to install a patch.
-f
The -f option historically caused patch not to request additional information from the user.
-r
The -r option historically provided a method of overriding the extension of the reject file from the default .rej.
-s
The -s option historically caused patch to work silently unless an error occurred.
-x
The -x option historically set internal debugging flags.

In some file system implementations, the saving of a .orig file may produce unwanted results. In the case of 12, 13, or 14-character filenames (on file systems supporting 14-character maximum filenames), the .orig file overwrites the new file. The reject file may also exceed this filename limit. It was suggested, due to some historical practice, that a tilde ( '~' ) suffix be used instead of .orig and some other character instead of the .rej suffix. This was rejected because it is not obvious to the user which file is which. The suffixes .orig and .rej are clearer and more understandable.

The -b option has the opposite sense in some historical implementations-do not save the .orig file. The default case here is not to save the files, making patch behave more consistently with the other standard utilities.

The -w option in early proposals was changed to -l to match historical practice.

The -N option was included because without it, a non-interactive application cannot reject previously applied patches. For example, if a user is piping the output of diff into the patch utility, and the user only wants to patch a file to a newer version non-interactively, the -N option is required.

Changes to the -l option description were proposed to allow matching across <newline>s in addition to just <blank>s. Since this is not historical practice, and since some ambiguities could result, it is suggested that future developments in this area utilize another option letter, such as -L.

FUTURE DIRECTIONS

None.

SEE ALSO

ed , diff

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


chgrp(1p)

CHGRP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

chgrp - change the file group ownership

SYNOPSIS

chgrp [-hR] group file ...

chgrp -R [-H | -L | -P ] group file ...

DESCRIPTION

The chgrp utility shall set the group ID of the file named by each file operand to the group ID specified by the group operand.

For each file operand, or, if the -R option is used, each file encountered while walking the directory trees specified by the file operands, the chgrp utility shall perform actions equivalent to the chown() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:

*
The file operand shall be used as the path argument.

*
The user ID of the file shall be used as the owner argument.

*
The specified group ID shall be used as the group argument.

Unless chgrp is invoked by a process with appropriate privileges, the set-user-ID and set-group-ID bits of a regular file shall be cleared upon successful completion; the set-user-ID and set-group-ID bits of other file types may be cleared.

OPTIONS

The chgrp utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-h
If the system supports group IDs for symbolic links, for each file operand that names a file of type symbolic link, chgrp shall attempt to set the group ID of the symbolic link instead of the file referenced by the symbolic link. If the system does not support group IDs for symbolic links, for each file operand that names a file of type symbolic link, chgrp shall do nothing more with the current file and shall go on to any remaining files.
-H
If the -R option is specified and a symbolic link referencing a file of type directory is specified on the command line, chgrp shall change the group of the directory referenced by the symbolic link and all files in the file hierarchy below it.
-L
If the -R option is specified and a symbolic link referencing a file of type directory is specified on the command line or encountered during the traversal of a file hierarchy, chgrp shall change the group of the directory referenced by the symbolic link and all files in the file hierarchy below it.
-P
If the -R option is specified and a symbolic link is specified on the command line or encountered during the traversal of a file hierarchy, chgrp shall change the group ID of the symbolic link if the system supports this operation. The chgrp utility shall not follow the symbolic link to any other part of the file hierarchy.
-R
Recursively change file group IDs. For each file operand that names a directory, chgrp shall change the group of the directory and all files in the file hierarchy below it. Unless a -H, -L, or -P option is specified, it is unspecified which of these options will be used as the default.

Specifying more than one of the mutually-exclusive options -H, -L, and -P shall not be considered an error. The last option specified shall determine the behavior of the utility.

OPERANDS

The following operands shall be supported:

group
A group name from the group database or a numeric group ID. Either specifies a group ID to be given to each file named by one of the file operands. If a numeric group operand exists in the group database as a group name, the group ID number associated with that group name is used as the group ID.
file
A pathname of a file whose group ID is to be modified.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of chgrp:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The utility executed successfully and all requested changes were made.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Only the owner of a file or the user with appropriate privileges may change the owner or group of a file.

Some implementations restrict the use of chgrp to a user with appropriate privileges when the group specified is not the effective group ID or one of the supplementary group IDs of the calling process.

EXAMPLES

None.

RATIONALE

The System V and BSD versions use different exit status codes. Some implementations used the exit status as a count of the number of errors that occurred; this practice is unworkable since it can overflow the range of valid exit status values. The standard developers chose to mask these by specifying only 0 and >0 as exit values.

The functionality of chgrp is described substantially through references to chown(). In this way, there is no duplication of effort required for describing the interactions of permissions, multiple groups, and so on.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , chown() , the System Interfaces volume of IEEE Std 1003.1-2001, chown()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sort(1p)

SORT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sort - sort, merge, or sequence check text files

SYNOPSIS

sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]

sort -c [-bdfinru][-t char][-k keydef][file]

DESCRIPTION

The sort utility shall perform one of the following functions:

1.
Sort lines of all the named files together and write the result to the specified output.

2.
Merge lines of all the named (presorted) files together and write the result to the specified output.

3.
Check that a single input file is correctly presorted.

Comparisons shall be based on one or more sort keys extracted from each line of input (or, if no sort keys are specified, the entire line up to, but not including, the terminating <newline>), and shall be performed using the collating sequence of the current locale.

OPTIONS

The sort utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, and the -k keydef option should follow the -b, -d, -f, -i, -n, and -r options.

The following options shall be supported:

-c
Check that the single input file is ordered as specified by the arguments and the collating sequence of the current locale. No output shall be produced; only the exit code shall be affected.
-m
Merge only; the input file shall be assumed to be already sorted.
-o output
Specify the name of an output file to be used instead of the standard output. This file can be the same as one of the input files.
-u
Unique: suppress all but one in each set of lines having equal keys. If used with the -c option, check that there are no lines with duplicate keys, in addition to checking that the input file is sorted.

The following options shall override the default ordering rules. When ordering options appear independent of any key field specifications, the requested field ordering rules shall be applied globally to all sort keys. When attached to a specific key (see -k), the specified ordering options shall override all global ordering options for that key.

-d
Specify that only <blank>s and alphanumeric characters, according to the current setting of LC_CTYPE , shall be significant in comparisons. The behavior is undefined for a sort key to which -i or -n also applies.
-f
Consider all lowercase characters that have uppercase equivalents, according to the current setting of LC_CTYPE , to be the uppercase equivalent for the purposes of comparison.
-i
Ignore all characters that are non-printable, according to the current setting of LC_CTYPE .
-n
Restrict the sort key to an initial numeric string, consisting of optional <blank>s, optional minus sign, and zero or more digits with an optional radix character and thousands separators (as defined in the current locale), which shall be sorted by arithmetic value. An empty digit string shall be treated as zero. Leading zeros and signs on zeros shall not affect ordering.
-r
Reverse the sense of comparisons.

The treatment of field separators can be altered using the options:

-b
Ignore leading <blank>s when determining the starting and ending positions of a restricted sort key. If the -b option is specified before the first -k option, it shall be applied to all -k options. Otherwise, the -b option can be attached independently to each -k field_start or field_end option-argument (see below).
-t char
Use char as the field separator character; char shall not be considered to be part of a field (although it can be included in a sort key). Each occurrence of char shall be significant (for example, <char><char> delimits an empty field). If -t is not specified, <blank>s shall be used as default field separators; each maximal non-empty sequence of <blank>s that follows a non- <blank> shall be a field separator.

Sort keys can be specified using the options:

-k keydef
The keydef argument is a restricted sort key field definition. The format of this definition is:

field_start[type][,field_end[type]]

where field_start and field_end define a key field restricted to a portion of the line (see the EXTENDED DESCRIPTION section), and type is a modifier from the list of characters 'b' , 'd' , 'f' , 'i' , 'n' , 'r' . The 'b' modifier shall behave like the -b option, but shall apply only to the field_start or field_end to which it is attached. The other modifiers shall behave like the corresponding options, but shall apply only to the key field to which they are attached; they shall have this effect if specified with field_start, field_end, or both. If any modifier is attached to a field_start or to a field_end, no option shall apply to either. Implementations shall support at least nine occurrences of the -k option, which shall be significant in command line order. If no -k option is specified, a default sort key of the entire line shall be used.

When there are multiple key fields, later keys shall be compared only after all earlier keys compare equal. Except when the -u option is specified, lines that otherwise compare equal shall be ordered as if none of the options -d, -f, -i, -n, or -k were present (but with -r still in effect, if it was specified) and with all bytes in the lines significant to the comparison. The order in which lines that still compare equal are written is unspecified.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be sorted, merged, or checked. If no file operands are specified, or if a file operand is '-' , the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' . See the INPUT FILES section.

INPUT FILES

The input files shall be text files, except that the sort utility shall add a <newline> to the end of a file ending with an incomplete last line.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of sort:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for ordering rules.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classification for the -b, -d, -f, -i, and -n options.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_NUMERIC

Determine the locale for the definition of the radix character and thousands separator for the -n option.

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Unless the -o or -c options are in effect, the standard output shall contain the sorted input.

STDERR

The standard error shall be used for diagnostic messages. A warning message about correcting an incomplete last line of an input file may be generated, but need not affect the final exit status.

OUTPUT FILES

If the -o option is in effect, the sorted input shall be written to the file output.

EXTENDED DESCRIPTION

The notation:

-k field_start[type][,field_end[type]]

shall define a key field that begins at field_start and ends at field_end inclusive, unless field_start falls beyond the end of the line or after field_end, in which case the key field is empty. A missing field_end shall mean the last character of the line.

A field comprises a maximal sequence of non-separating characters and, in the absence of option -t, any preceding field separator.

The field_start portion of the keydef option-argument shall have the form:

field_number[.first_character]

Fields and characters within fields shall be numbered starting with 1. The field_number and first_character pieces, interpreted as positive decimal integers, shall specify the first character to be used as part of a sort key. If .first_character is omitted, it shall refer to the first character of the field.

The field_end portion of the keydef option-argument shall have the form:

field_number[.last_character]

The field_number shall be as described above for field_start. The last_character piece, interpreted as a non-negative decimal integer, shall specify the last character to be used as part of the sort key. If last_character evaluates to zero or .last_character is omitted, it shall refer to the last character of the field specified by field_number.

If the -b option or b type modifier is in effect, characters within a field shall be counted from the first non- <blank> in the field. (This shall apply separately to first_character and last_character.)

EXIT STATUS

The following exit values shall be returned:

0
All input files were output successfully, or -c was specified and the input file was correctly sorted.
1
Under the -c option, the file was not ordered as specified, or if the -c and -u options were both specified, two input lines were found with equal keys.
>1
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The default value for -t, <blank>, has different properties from, for example, -t "<space>". If a line contains:

<space><space>foo

the following treatment would occur with default separation as opposed to specifically selecting a <space>:
Field | Default | -t "<space>"
1 | <space><space>foo | empty
2 | empty | empty
3 | empty | foo

The leading field separator itself is included in a field when -t is not used. For example, this command returns an exit status of zero, meaning the input was already sorted:

sort -c -k 2 <<eof
y<tab>b
x<space>a
eof

(assuming that a <tab> precedes the <space> in the current collating sequence). The field separator is not included in a field when it is explicitly set via -t. This is historical practice and allows usage such as:

sort -t "|" -k 2n <<eof
Atlanta|425022|Georgia
Birmingham|284413|Alabama
Columbia|100385|South Carolina
eof

where the second field can be correctly sorted numerically without regard to the non-numeric field separator.

The wording in the OPTIONS section clarifies that the -b, -d, -f, -i, -n, and -r options have to come before the first sort key specified if they are intended to apply to all specified keys. The way it is described in this volume of IEEE Std 1003.1-2001 matches historical practice, not historical documentation. The results are unspecified if these options are specified after a -k option.

The -f option might not work as expected in locales where there is not a one-to-one mapping between an uppercase and a lowercase letter.

EXAMPLES

1.
The following command sorts the contents of infile with the second field as the sort key:

sort -k 2,2 infile

2.
The following command sorts, in reverse order, the contents of infile1 and infile2, placing the output in outfile and using the second character of the second field as the sort key (assuming that the first character of the second field is the field separator):

sort -r -o outfile -k 2.2,2.2 infile1 infile2

3.
The following command sorts the contents of infile1 and infile2 using the second non- <blank> of the second field as the sort key:

sort -k 2.2b,2.2b infile1 infile2

4.
The following command prints the System V password file (user database) sorted by the numeric user ID (the third colon-separated field):

sort -t : -k 3,3n /etc/passwd

5.
The following command prints the lines of the already sorted file infile, suppressing all but one occurrence of lines having the same third field:

sort -um -k 3.1,3.0 infile

RATIONALE

Examples in some historical documentation state that options -um with one input file keep the first in each set of lines with equal keys. This behavior was deemed to be an implementation artifact and was not standardized.

The -z option was omitted; it is not standard practice on most systems and is inconsistent with using sort to sort several files individually and then merge them together. The text concerning -z in historical documentation appeared to require implementations to determine the proper buffer length during the sort phase of operation, but not during the merge.

The -y option was omitted because of non-portability. The -M option, present in System V, was omitted because of non-portability in international usage.

An undocumented -T option exists in some implementations. It is used to specify a directory for intermediate files. Implementations are encouraged to support the use of the TMPDIR environment variable instead of adding an option to support this functionality.

The -k option was added to satisfy two objections. First, the zero-based counting used by sort is not consistent with other utility conventions. Second, it did not meet syntax guideline requirements.

Historical documentation indicates that "setting -n implies -b". The description of -n already states that optional leading <blank>s are tolerated in doing the comparison. If -b is enabled, rather than implied, by -n, this has unusual side effects. When a character offset is used in a column of numbers (for example, to sort modulo 100), that offset is measured relative to the most significant digit, not to the column. Based upon a recommendation from the author of the original sort utility, the -b implication has been omitted from this volume of IEEE Std 1003.1-2001, and an application wishing to achieve the previously mentioned side effects has to code the -b flag explicitly.

FUTURE DIRECTIONS

None.

SEE ALSO

comm , join , uniq , the System Interfaces volume of IEEE Std 1003.1-2001, toupper()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


paste(1p)

PASTE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

paste - merge corresponding or subsequent lines of files

SYNOPSIS

paste [-s][-d list] file...

DESCRIPTION

The paste utility shall concatenate the corresponding lines of the given input files, and write the resulting lines to standard output.

The default operation of paste shall concatenate the corresponding lines of the input files. The <newline> of every line except the line from the last input file shall be replaced with a <tab>.

If an end-of-file condition is detected on one or more input files, but not all input files, paste shall behave as though empty lines were read from the files on which end-of-file was detected, unless the -s option is specified.

OPTIONS

The paste utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-d list
Unless a backslash character appears in list, each character in list is an element specifying a delimiter character. If a backslash character appears in list, the backslash character and one or more characters following it are an element specifying a delimiter character as described below. These elements specify one or more delimiters to use, instead of the default <tab>, to replace the <newline> of the input lines. The elements in list shall be used circularly; that is, when the list is exhausted the first element from the list is reused. When the -s option is specified:
*
The last <newline> in a file shall not be modified.

*
The delimiter shall be reset to the first element of list after each file operand is processed.

When the -s option is not specified:

*
The <newline>s in the file specified by the last file operand shall not be modified.

*
The delimiter shall be reset to the first element of list each time a line is processed from each file.

If a backslash character appears in list, it and the character following it shall be used to represent the following delimiter characters:

\n
<newline>.
\t
<tab>.
\\
Backslash character.
\0
Empty string (not a null character). If '\0' is immediately followed by the character 'x' , the character 'X' , or any character defined by the LC_CTYPE digit keyword (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale), the results are unspecified.

If any other characters follow the backslash, the results are unspecified.

-s
Concatenate all of the lines of each separate input file in command line order. The <newline> of every line except the last line in each input file shall be replaced with the <tab>, unless otherwise specified by the -d option.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If '-' is specified for one or more of the files, the standard input shall be used; the standard input shall be read one line at a time, circularly, for each instance of '-' . Implementations shall support pasting of at least 12 file operands.

STDIN

The standard input shall be used only if one or more file operands is '-' . See the INPUT FILES section.

INPUT FILES

The input files shall be text files, except that line lengths shall be unlimited.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of paste:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Concatenated lines of input files shall be separated by the <tab> (or other characters under the control of the -d option) and terminated by a <newline>.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If one or more input files cannot be opened when the -s option is not specified, a diagnostic message shall be written to standard error, but no output is written to standard output. If the -s option is specified, the paste utility shall provide the default behavior described in Utility Description Defaults .

The following sections are informative.

APPLICATION USAGE

When the escape sequences of the list option-argument are used in a shell script, they must be quoted; otherwise, the shell treats the '\' as a special character.

Conforming applications should only use the specific backslash escaped delimiters presented in this volume of IEEE Std 1003.1-2001. Historical implementations treat '\x' , where 'x' is not in this list, as 'x' , but future implementations are free to expand this list to recognize other common escapes similar to those accepted by printf and other standard utilities.

Most of the standard utilities work on text files. The cut utility can be used to turn files with arbitrary line lengths into a set of text files containing the same data. The paste utility can be used to create (or recreate) files with arbitrary line lengths. For example, if file contains long lines:

cut -b 1-500 -n file > file1
cut -b 501- -n file > file2

creates file1 (a text file) with lines no longer than 500 bytes (plus the <newline>) and file2 that contains the remainder of the data from file. Note that file2 is not a text file if there are lines in file that are longer than 500 + {LINE_MAX} bytes. The original file can be recreated from file1 and file2 using the command:

paste -d "\0" file1 file2 > file

The commands:

paste -d "\0" ...
paste -d "" ...

are not necessarily equivalent; the latter is not specified by this volume of IEEE Std 1003.1-2001 and may result in an error. The construct '\0' is used to mean "no separator" because historical versions of paste did not follow the syntax guidelines, and the command:

paste -d"" ...

could not be handled properly by getopt().

EXAMPLES

1.
Write out a directory in four columns:

ls | paste - - - -

2.
Combine pairs of lines from a file into single lines:

paste -s -d "\t\n" file

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Utility Description Defaults , cut , grep , pr

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


c99(1p)

C99

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

c99 - compile standard C programs

SYNOPSIS

c99 [-c][-D name[=value]]...[-E][-g][-I directory] ... [-L directory]
... [-o outfile][-O optlevel][-s][-U name]... operand ...

DESCRIPTION

The c99 utility is an interface to the standard C compilation system; it shall accept source code conforming to the ISO C standard. The system conceptually consists of a compiler and link editor. The files referenced by operands shall be compiled and linked to produce an executable file. (It is unspecified whether the linking occurs entirely within the operation of c99; some implementations may produce objects that are not fully resolved until the file is executed.)

If the -c option is specified, for all pathname operands of the form file .c, the files:

$(basename pathname .c).o

shall be created as the result of successful compilation. If the -c option is not specified, it is unspecified whether such .o files are created or deleted for the file .c operands.

If there are no options that prevent link editing (such as -c or -E), and all operands compile and link without error, the resulting executable file shall be written according to the -o outfile option (if present) or to the file a.out.

The executable file shall be created as specified in File Read, Write, and Creation , except that the file permission bits shall be set to:

S_IRWXO | S_IRWXG | S_IRWXU

and the bits specified by the umask of the process shall be cleared.

OPTIONS

The c99 utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that:

*
The -l library operands have the format of options, but their position within a list of operands affects the order in which libraries are searched.

*
The order of specifying the -I and -L options is significant.

*
Conforming applications shall specify each option separately; that is, grouping option letters (for example, -cO) need not be recognized by all implementations.

The following options shall be supported:

-c
Suppress the link-edit phase of the compilation, and do not remove any object files that are produced.
-g
Produce symbolic information in the object or executable files; the nature of this information is unspecified, and may be modified by implementation-defined interactions with other options.
-s
Produce object or executable files, or both, from which symbolic and other information not required for proper execution using the exec family defined in the System Interfaces volume of IEEE Std 1003.1-2001 has been removed (stripped). If both -g and -s options are present, the action taken is unspecified.
-o outfile
Use the pathname outfile, instead of the default a.out, for the executable file produced. If the -o option is present with -c or -E, the result is unspecified.
-D name[=value]

Define name as if by a C-language #define directive. If no = value is given, a value of 1 shall be used. The -D option has lower precedence than the -U option. That is, if name is used in both a -U and a -D option, name shall be undefined regardless of the order of the options. Additional implementation-defined names may be provided by the compiler. Implementations shall support at least 2048 bytes of -D definitions and 256 names.

-E
Copy C-language source files to standard output, expanding all preprocessor directives; no compilation shall be performed. If any operand is not a text file, the effects are unspecified.
-I directory
Change the algorithm for searching for headers whose names are not absolute pathnames to look in the directory named by the directory pathname before looking in the usual places. Thus, headers whose names are enclosed in double-quotes ( "" ) shall be searched for first in the directory of the file with the #include line, then in directories named in -I options, and last in the usual places. For headers whose names are enclosed in angle brackets ( "<>" ), the header shall be searched for only in directories named in -I options and then in the usual places. Directories named in -I options shall be searched in the order specified. Implementations shall support at least ten instances of this option in a single c99 command invocation.
-L directory
Change the algorithm of searching for the libraries named in the -l objects to look in the directory named by the directory pathname before looking in the usual places. Directories named in -L options shall be searched in the order specified. Implementations shall support at least ten instances of this option in a single c99 command invocation. If a directory specified by a -L option contains files named libc.a, libm.a, libl.a, or liby.a, the results are unspecified.
-O optlevel
Specify the level of code optimization. If the optlevel option-argument is the digit '0' , all special code optimizations shall be disabled. If it is the digit '1' , the nature of the optimization is unspecified. If the -O option is omitted, the nature of the system's default optimization is unspecified. It is unspecified whether code generated in the presence of the -O 0 option is the same as that generated when -O is omitted. Other optlevel values may be supported.
-U name
Remove any initial definition of name.

Multiple instances of the -D, -I, -U, and -L options can be specified.

OPERANDS

An operand is either in the form of a pathname or the form -l library. The application shall ensure that at least one operand of the pathname form is specified. The following operands shall be supported:

file.c
A C-language source file to be compiled and optionally linked. The application shall ensure that the operand is of this form if the -c option is used.
file.a
A library of object files typically produced by the ar utility, and passed directly to the link editor. Implementations may recognize implementation-defined suffixes other than .a as denoting object file libraries.
file.o
An object file produced by c99 -c and passed directly to the link editor. Implementations may recognize implementation-defined suffixes other than .o as denoting object files.

The processing of other files is implementation-defined.

-l library
(The letter ell.) Search the library named:

liblibrary.a

A library shall be searched when its name is encountered, so the placement of a -l operand is significant. Several standard libraries can be specified in this manner, as described in the EXTENDED DESCRIPTION section. Implementations may recognize implementation-defined suffixes other than .a as denoting libraries.

STDIN

Not used.

INPUT FILES

The input file shall be one of the following: a text file containing a C-language source program, an object file in the format produced by c99 -c, or a library of object files, in the format produced by archiving zero or more object files, using ar. Implementations may supply additional utilities that produce files in these formats. Additional input file formats are implementation-defined.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of c99:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TMPDIR
Provide a pathname that should override the default directory for temporary files, if any. On XSI-conforming systems, provide a pathname that shall override the default directory for temporary files, if any.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If more than one file operand ending in .c (or possibly other unspecified suffixes) is given, for each such file:

"%s:\n", <file>

may be written. These messages, if written, shall precede the processing of each input file; they shall not be written to the standard output if they are written to the standard error, as described in the STDERR section.

If the -E option is specified, the standard output shall be a text file that represents the results of the preprocessing stage of the language; it may contain extra information appropriate for subsequent compilation passes.

STDERR

The standard error shall be used only for diagnostic messages. If more than one file operand ending in .c (or possibly other unspecified suffixes) is given, for each such file:

"%s:\n", <file>

may be written to allow identification of the diagnostic and warning messages with the appropriate input file. These messages, if written, shall precede the processing of each input file; they shall not be written to the standard error if they are written to the standard output, as described in the STDOUT section.

This utility may produce warning messages about certain conditions that do not warrant returning an error (non-zero) exit value.

OUTPUT FILES

Object files or executable files or both are produced in unspecified formats.

EXTENDED DESCRIPTION

Standard Libraries

The c99 utility shall recognize the following -l operands for standard libraries:

-l c
This operand shall make visible all functions referenced in the System Interfaces volume of IEEE Std 1003.1-2001, with the possible exception of those functions listed as residing in <aio.h>, <arpa/inet.h>, <complex.h>, <fenv.h>, <math.h>, <mqueue.h>, <netdb.h>, <netinet/in.h>, <pthread.h>, <sched.h>, <semaphore.h>, <spawn.h>, <sys/socket.h>, pthread_kill(), and pthread_sigmask() in <signal.h>, <trace.h>, functions marked as extensions other than as part of the MF or MPR extensions in <sys/mman.h>, functions marked as ADV in <fcntl.h>, and functions marked as CS, CPT, and TMR in <time.h>. This operand shall not be required to be present to cause a search of this library.
-l l
This operand shall make visible all functions required by the C-language output of lex that are not made available through the -l c operand.
-l pthread
This operand shall make visible all functions referenced in <pthread.h> and pthread_kill() and pthread_sigmask() referenced in <signal.h>. An implementation may search this library in the absence of this operand.
-l m
This operand shall make visible all functions referenced in <math.h>, <complex.h>, and <fenv.h>. An implementation may search this library in the absence of this operand.
-l rt
This operand shall make visible all functions referenced in <aio.h>, <mqueue.h>, <sched.h>, <semaphore.h>, and <spawn.h>, functions marked as extensions other than as part of the MF or MPR extensions in <sys/mman.h>, functions marked as ADV in <fcntl.h>, and functions marked as CS, CPT, and TMR in <time.h>. An implementation may search this library in the absence of this operand.
-l trace
This operand shall make visible all functions referenced in <trace.h>. An implementation may search this library in the absence of this operand.
-l xnet
This operand makes visible all functions referenced in <arpa/inet.h>, <netdb.h>, <netinet/in.h>, and <sys/socket.h>. An implementation may search this library in the absence of this operand.
-l y
This operand shall make visible all functions required by the C-language output of yacc that are not made available through the -l c operand.

In the absence of options that inhibit invocation of the link editor, such as -c or -E, the c99 utility shall cause the equivalent of a -l c operand to be passed to the link editor as the last -l operand, causing it to be searched after all other object files and libraries are loaded.

It is unspecified whether the libraries libc.a, libm.a, librt.a, libpthread.a, libl.a, liby.a, or libxnet.a exist as regular files. The implementation may accept as -l operands names of objects that do not exist as regular files.

External Symbols

The C compiler and link editor shall support the significance of external symbols up to a length of at least 31 bytes; the action taken upon encountering symbols exceeding the implementation-defined maximum symbol length is unspecified.

The compiler and link editor shall support a minimum of 511 external symbols per source or object file, and a minimum of 4095 external symbols in total. A diagnostic message shall be written to the standard output if the implementation-defined limit is exceeded; other actions are unspecified.

Programming Environments

All implementations shall support one of the following programming environments as a default. Implementations may support more than one of the following programming environments. Applications can use sysconf() or getconf to determine which programming environments are supported.

Table: Programming Environments: Type Sizes
Programming Environment | Bits in | Bits in | Bits in | Bits in
getconf Name | int | long | pointer | off_t
_POSIX_V6_ILP32_OFF32 | 32 | 32 | 32 | 32
_POSIX_V6_ILP32_OFFBIG | 32 | 32 | 32 | >=64
_POSIX_V6_LP64_OFF64 | 32 | 64 | 64 | 64
_POSIX_V6_LPBIG_OFFBIG | >=32 | >=64 | >=64 | >=64

All implementations shall support one or more environments where the widths of the following types are no greater than the width of type long: blksize_t, cc_t, mode_t, nfds_t, pid_t, ptrdiff_t, size_t, speed_t, ssize_t, suseconds_t, tcflag_t, useconds_t, wchar_t, wint_t

The executable files created when these environments are selected shall be in a proper format for execution by the exec family of functions. Each environment may be one of the ones in Programming Environments: Type Sizes , or it may be another environment. The names for the environments that meet this requirement shall be output by a getconf command using the _POSIX_V6_WIDTH_RESTRICTED_ENVS argument. If more than one environment meets the requirement, the names of all such environments shall be output on separate lines. Any of these names can then be used in a subsequent getconf command to obtain the flags specific to that environment with the following suffixes added as appropriate:

_CFLAGS
To get the C compiler flags.
_LDFLAGS
To get the linker/loader flags.
_LIBS
To get the libraries.

This requirement may be removed in a future version of IEEE Std 1003.1.

When this utility processes a file containing a function called main(), it shall be defined with a return type equivalent to int. Using return from the initial call to main() shall be equivalent (other than with respect to language scope issues) to calling exit() with the returned value. Reaching the end of the initial call to main() shall be equivalent to calling exit(0). The implementation shall not declare a prototype for this function.

Implementations provide configuration strings for C compiler flags, linker/loader flags, and libraries for each supported environment. When an application needs to use a specific programming environment rather than the implementation default programming environment while compiling, the application shall first verify that the implementation supports the desired environment. If the desired programming environment is supported, the application shall then invoke c99 with the appropriate C compiler flags as the first options for the compile, the appropriate linker/loader flags after any other options but before any operands, and the appropriate libraries at the end of the operands.

Conforming applications shall not attempt to link together object files compiled for different programming models. Applications shall also be aware that binary data placed in shared memory or in files might not be recognized by applications built for other programming models.

Table: Programming Environments: c99 and cc Arguments
Programming Environment |  | c99 and cc Arguments
getconf Name | Use | getconf Name
_POSIX_V6_ILP32_OFF32 | C Compiler Flags | POSIX_V6_ILP32_OFF32_CFLAGS
 | Linker/Loader Flags | POSIX_V6_ILP32_OFF32_LDFLAGS
 | Libraries | POSIX_V6_ILP32_OFF32_LIBS
_POSIX_V6_ILP32_OFFBIG | C Compiler Flags | POSIX_V6_ILP32_OFFBIG_CFLAGS
 | Linker/Loader Flags | POSIX_V6_ILP32_OFFBIG_LDFLAGS
 | Libraries | POSIX_V6_ILP32_OFFBIG_LIBS
_POSIX_V6_LP64_OFF64 | C Compiler Flags | POSIX_V6_LP64_OFF64_CFLAGS
 | Linker/Loader Flags | POSIX_V6_LP64_OFF64_LDFLAGS
 | Libraries | POSIX_V6_LP64_OFF64_LIBS
_POSIX_V6_LPBIG_OFFBIG | C Compiler Flags | POSIX_V6_LPBIG_OFFBIG_CFLAGS
 | Linker/Loader Flags | POSIX_V6_LPBIG_OFFBIG_LDFLAGS
 | Libraries | POSIX_V6_LPBIG_OFFBIG_LIBS

EXIT STATUS

The following exit values shall be returned:

0
Successful compilation or link edit.
>0
An error occurred.

CONSEQUENCES OF ERRORS

When c99 encounters a compilation error that causes an object file not to be created, it shall write a diagnostic to standard error and continue to compile other source code operands, but it shall not perform the link phase and return a non-zero exit status. If the link edit is unsuccessful, a diagnostic message shall be written to standard error and c99 exits with a non-zero status. A conforming application shall rely on the exit status of c99, rather than on the existence or mode of the executable file.

The following sections are informative.

APPLICATION USAGE

Since the c99 utility usually creates files in the current directory during the compilation process, it is typically necessary to run the c99 utility in a directory in which a file can be created.

On systems providing POSIX Conformance (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 2, Conformance), c99 is required only with the C-Language Development option; XSI-conformant systems always provide c99.

Some historical implementations have created .o files when -c is not specified and more than one source file is given. Since this area is left unspecified, the application cannot rely on .o files being created, but it also must be prepared for any related .o files that already exist being deleted at the completion of the link edit.

Some historical implementations have permitted -L options to be interspersed with -l operands on the command line. For an application to compile consistently on systems that do not behave like this, it is necessary for a conforming application to supply all -L options before any of the -l options.

There is the possible implication that if a user supplies versions of the standard functions (before they would be encountered by an implicit -l c or explicit -l m), that those versions would be used in place of the standard versions. There are various reasons this might not be true (functions defined as macros, manipulations for clean name space, and so on), so the existence of files named in the same manner as the standard libraries within the -L directories is explicitly stated to produce unspecified behavior.

All of the functions specified in the System Interfaces volume of IEEE Std 1003.1-2001 may be made visible by implementations when the Standard C Library is searched. Conforming applications must explicitly request searching the other standard libraries when functions made visible by those libraries are used.

EXAMPLES

1.
The following usage example compiles foo.c and creates the executable file foo:

c99 -o foo foo.c

The following usage example compiles foo.c and creates the object file foo.o:

c99 -c foo.c

The following usage example compiles foo.c and creates the executable file a.out:

c99 foo.c

The following usage example compiles foo.c, links it with bar.o, and creates the executable file a.out. It may also create and leave foo.o:

c99 foo.c bar.o

2.
The following example shows how an application using threads interfaces can test for support of and use a programming environment supporting 32-bit int, long, and pointer types and an off_t type using at least 64 bits:

if [ $(getconf _POSIX_V6_ILP32_OFFBIG) != "-1" ]
then
    c99 $(getconf POSIX_V6_ILP32_OFFBIG_CFLAGS) -D_XOPEN_SOURCE=600 \
        $(getconf POSIX_V6_ILP32_OFFBIG_LDFLAGS) foo.c -o foo \
        $(getconf POSIX_V6_ILP32_OFFBIG_LIBS) -l pthread
else
    echo ILP32_OFFBIG programming environment not supported
    exit 1
fi

3.
The following examples clarify the use and interactions of -L options and -l operands.

Consider the case in which module a.c calls function f() in library libQ.a, and module b.c calls function g() in library libp.a. Assume that both libraries reside in /a/b/c. The command line to compile and link in the desired way is:

c99 -L /a/b/c main.o a.c -l Q b.c -l p

In this case the -l Q operand need only precede the first -l p operand, since both libQ.a and libp.a reside in the same directory.

Multiple -L operands can be used when library name collisions occur. Building on the previous example, suppose that the user wants to use a new libp.a, in /a/a/a, but still wants f() from /a/b/c/libQ.a:

c99 -L /a/a/a -L /a/b/c main.o a.c -l Q b.c -l p

In this example, the linker searches the -L options in the order specified, and finds /a/a/a/libp.a before /a/b/c/libp.a when resolving references for b.c. The order of the -l operands is still important, however.

4.
The following example shows how an application can use a programming environment where the widths of the following types: blksize_t, cc_t, mode_t, nfds_t, pid_t, ptrdiff_t, size_t, speed_t, ssize_t, suseconds_t, tcflag_t, useconds_t, wchar_t, wint_t

are no greater than the width of type long:

# First choose one of the listed environments ...

# ... if there are no additional constraints, the first one will do:
CENV=$(getconf _POSIX_V6_WIDTH_RESTRICTED_ENVS | head -n l)

# ... or, if an environment that supports large files is preferred,
# look for names that contain "OFF64" or "OFFBIG". (This chooses
# the last one in the list if none match.)
for CENV in $(getconf _POSIX_V6_WIDTH_RESTRICTED_ENVS)
do
    case $CENV in
    *OFF64*|*OFFBIG*) break ;;
    esac
done

# The chosen environment name can now be used like this:

c99 $(getconf ${CENV}_CFLAGS) -D _POSIX_C_SOURCE=200112L \
$(getconf ${CENV}_LDFLAGS) foo.c -o foo \
$(getconf ${CENV}_LIBS)

RATIONALE

The c99 utility is based on the c89 utility originally introduced in the ISO POSIX-2:1993 standard.

Some of the changes from c89 include the modification to the contents of the Standard Libraries section to account for new headers and options; for example, <spawn.h> added to the -l rt operand, and the -l trace operand added for the Tracing functions.

FUTURE DIRECTIONS

None.

SEE ALSO

File Read, Write, and Creation , ar , getconf , make , nm , strip , umask() , the System Interfaces volume of IEEE Std 1003.1-2001, exec, sysconf(), the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mkfifo(1p)

MKFIFO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mkfifo - make FIFO special files

SYNOPSIS

mkfifo [-m mode] file...

DESCRIPTION

The mkfifo utility shall create the FIFO special files specified by the operands, in the order specified.

For each file operand, the mkfifo utility shall perform actions equivalent to the mkfifo() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:

1.
The file operand is used as the path argument.

2.
The value of the bitwise-inclusive OR of S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH is used as the mode argument. (If the -m option is specified, the value of the mkfifo() mode argument is unspecified, but the FIFO shall at no time have permissions less restrictive than the -m mode option-argument.)

OPTIONS

The mkfifo utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-m mode
Set the file permission bits of the newly-created FIFO to the specified mode value. The mode option-argument shall be the same as the mode operand defined for the chmod utility. In the symbolic_mode strings, the op characters '+' and '-' shall be interpreted relative to an assumed initial mode of a= rw.

OPERANDS

The following operand shall be supported:

file
A pathname of the FIFO special file to be created.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of mkfifo:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All the specified FIFO special files were created successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

This utility was added to permit shell applications to create FIFO special files.

The -m option was added to control the file mode, for consistency with the similar functionality provided by the mkdir utility.

Early proposals included a -p option similar to the mkdir -p option that created intermediate directories leading up to the FIFO specified by the final component. This was removed because it is not commonly needed and is not common practice with similar utilities.

The functionality of mkfifo is described substantially through a reference to the mkfifo() function in the System Interfaces volume of IEEE Std 1003.1-2001. For example, by default, the mode of the FIFO file is affected by the file mode creation mask in accordance with the specified behavior of the mkfifo() function. In this way, there is less duplication of effort required for describing details of the file creation.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , umask() , the System Interfaces volume of IEEE Std 1003.1-2001, mkfifo()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


test(1p)

TEST

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

test - evaluate expression

SYNOPSIS

test [expression]

[ [expression] ]

DESCRIPTION

The test utility shall evaluate the expression and indicate the result of the evaluation by its exit status. An exit status of zero indicates that the expression evaluated as true and an exit status of 1 indicates that the expression evaluated as false.

In the second form of the utility, which uses "[]" rather than test, the application shall ensure that the square brackets are separate arguments.

OPTIONS

The test utility shall not recognize the "--" argument in the manner specified by guideline 10 in the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

No options shall be supported.

OPERANDS

The application shall ensure that all operators and elements of primaries are presented as separate arguments to the test utility.

The following primaries can be used to construct expression:

-b file
True if file exists and is a block special file.
-c file
True if file exists and is a character special file.
-d file
True if file exists and is a directory.
-e file
True if file exists.
-f file
True if file exists and is a regular file.
-g file
True if file exists and its set-group-ID flag is set.
-h file
True if file exists and is a symbolic link.
-L file
True if file exists and is a symbolic link.
-n string
True if the length of string is non-zero.
-p file
True if file is a FIFO.
-r file
True if file exists and is readable. True shall indicate that permission to read from file will be granted, as defined in File Read, Write, and Creation .
-S file
True if file exists and is a socket.
-s file
True if file exists and has a size greater than zero.
-t file_descriptor

True if the file whose file descriptor number is file_descriptor is open and is associated with a terminal.

-u file
True if file exists and its set-user-ID flag is set.
-w file
True if file exists and is writable. True shall indicate that permission to write from file will be granted, as defined in File Read, Write, and Creation .
-x file
True if file exists and is executable. True shall indicate that permission to execute file will be granted, as defined in File Read, Write, and Creation . If file is a directory, true shall indicate that permission to search file will be granted.
-z string
True if the length of string string is zero.
string
True if the string string is not the null string.
s1 = s2
True if the strings s1 and s2 are identical.
s1 != s2
True if the strings s1 and s2 are not identical.
n1 -eq n2
True if the integers n1 and n2 are algebraically equal.
n1 -ne n2
True if the integers n1 and n2 are not algebraically equal.
n1 -gt n2
True if the integer n1 is algebraically greater than the integer n2.
n1 -ge n2
True if the integer n1 is algebraically greater than or equal to the integer n2.
n1 -lt n2
True if the integer n1 is algebraically less than the integer n2.
n1 -le n2
True if the integer n1 is algebraically less than or equal to the integer n2.
expression1 -a expression2

True if both expression1 and expression2 are true. The -a binary primary is left associative. It has a higher precedence than -o.

expression1 -o expression2

True if either expression1 or expression2 is true. The -o binary primary is left associative.

With the exception of the -h file and -L file primaries, if a file argument is a symbolic link, test shall evaluate the expression by resolving the symbolic link and using the file referenced by the link.

These primaries can be combined with the following operators:

! expression
True if expression is false.
( expression )
True if expression is true. The parentheses can be used to alter the normal precedence and associativity.

The primaries with two elements of the form:

-primary_operator primary_operand

are known as unary primaries. The primaries with three elements in either of the two forms:

primary_operand -primary_operator primary_operand

primary_operand primary_operator primary_operand

are known as binary primaries. Additional implementation-defined operators and primary_operators may be provided by implementations. They shall be of the form - operator where the first character of operator is not a digit.

The algorithm for determining the precedence of the operators and the return value that shall be generated is based on the number of arguments presented to test. (However, when using the "[...]" form, the right-bracket final argument shall not be counted in this algorithm.)

In the following list, $1, $2, $3, and $4 represent the arguments presented to test:

0 arguments:
Exit false (1).
1 argument:
Exit true (0) if $1 is not null; otherwise, exit false.
2 arguments:
*
If $1 is '!' , exit true if $2 is null, false if $2 is not null.

*
If $1 is a unary primary, exit true if the unary test is true, false if the unary test is false.

*
Otherwise, produce unspecified results.

3 arguments:
*
If $2 is a binary primary, perform the binary test of $1 and $3.

*
If $1 is '!' , negate the two-argument test of $2 and $3.

*
If $1 is '(' and $3 is ')' , perform the unary test of $2.

*
Otherwise, produce unspecified results.

4 arguments:
*
If $1 is '!' , negate the three-argument test of $2, $3, and $4.

*
If $1 is '(' and $4 is ')' , perform the two-argument test of $2 and $3.

*
Otherwise, the results are unspecified.

>4 arguments:
The results are unspecified.

On XSI-conformant systems, combinations of primaries and operators shall be evaluated using the precedence and associativity rules described previously. In addition, the string comparison binary primaries '=' and "!=" shall have a higher precedence than any unary primary.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of test:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
expression evaluated to true.
1
expression evaluated to false or expression was missing.
>1
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Scripts should be careful when dealing with user-supplied input that could be confused with primaries and operators. Unless the application writer knows all the cases that produce input to the script, invocations like:

test "$1" -a "$2"

should be written as:

test "$1" && test "$2"

to avoid problems if a user supplied values such as $1 set to '!' and $2 set to the null string. That is, in cases where maximal portability is of concern, replace:

test expr1 -a expr2

with:

test expr1 && test expr2

and replace:

test expr1 -o expr2

with:

test expr1 || test expr2

but note that, in test, -a has higher precedence than -o while "&&" and "||" have equal precedence in the shell.

Parentheses or braces can be used in the shell command language to effect grouping.

Parentheses must be escaped when using sh; for example:

test \( expr1 -a expr2 \) -o expr3

This command is not always portable outside XSI-conformant systems. The following form can be used instead:

( test expr1 && test expr2 ) || test expr3

The two commands:

test "$1"
test ! "$1"

could not be used reliably on some historical systems. Unexpected results would occur if such a string expression were used and $1 expanded to '!' , '(' , or a known unary primary. Better constructs are:

test -n "$1"
test -z "$1"
respectively.

Historical systems have also been unreliable given the common construct:

test "$response" = "expected string"

One of the following is a more reliable form:

test "X$response" = "Xexpected string"
test "expected string" = "$response"

Note that the second form assumes that expected string could not be confused with any unary primary. If expected string starts with '-' , '(' , '!' , or even '=' , the first form should be used instead. Using the preceding rules without the XSI marked extensions, any of the three comparison forms is reliable, given any input. (However, note that the strings are quoted in all cases.)

Because the string comparison binary primaries, '=' and "!=" , have a higher precedence than any unary primary in the greater than 4 argument case, unexpected results can occur if arguments are not properly prepared. For example, in:

test -d $1 -o -d $2

If $1 evaluates to a possible directory name of '=' , the first three arguments are considered a string comparison, which shall cause a syntax error when the second -d is encountered. One of the following forms prevents this; the second is preferred:

test \( -d "$1" \) -o \( -d "$2" \)
test -d "$1" || test -d "$2"

Also in the greater than 4 argument case:

test "$1" = "bat" -a "$2" = "ball"

syntax errors occur if $1 evaluates to '(' or '!' . One of the following forms prevents this; the third is preferred:

test "X$1" = "Xbat" -a "X$2" = "Xball"
test "$1" = "bat" && test "$2" = "ball"
test "X$1" = "Xbat" && test "X$2" = "Xball"

EXAMPLES

1.
Exit if there are not two or three arguments (two variations):

if [ $# -ne 2 -a $# -ne 3 ]; then exit 1; fi
if [ $# -lt 2 -o $# -gt 3 ]; then exit 1; fi

2.
Perform a mkdir if a directory does not exist:

test ! -d tempdir && mkdir tempdir

3.
Wait for a file to become non-readable:

while test -r thefile
do
    sleep 30
done
echo '"thefile" is no longer readable'

4.
Perform a command if the argument is one of three strings (two variations):

if [ "$1" = "pear" ] || [ "$1" = "grape" ] || [ "$1" = "apple" ]
then
    command
fi

case "$1" in
    pear|grape|apple) command ;;
esac

RATIONALE

The KornShell-derived conditional command (double bracket [[]]) was removed from the shell command language description in an early proposal. Objections were raised that the real problem is misuse of the test command ( [), and putting it into the shell is the wrong way to fix the problem. Instead, proper documentation and a new shell reserved word ( !) are sufficient.

Tests that require multiple test operations can be done at the shell level using individual invocations of the test command and shell logicals, rather than using the error-prone -o flag of test.

XSI-conformant systems support more than four arguments.

XSI-conformant systems support the combining of primaries with the following constructs:

expression1 -a expression2

True if both expression1 and expression2 are true.

expression1 -o expression2

True if at least one of expression1 and expression2 are true.

( expression )

True if expression is true.

In evaluating these more complex combined expressions, the following precedence rules are used:

*
The unary primaries have higher precedence than the algebraic binary primaries.

*
The unary primaries have lower precedence than the string binary primaries.

*
The unary and binary primaries have higher precedence than the unary string primary.

*
The ! operator has higher precedence than the -a operator, and the -a operator has higher precedence than the -o operator.

*
The -a and -o operators are left associative.

*
The parentheses can be used to alter the normal precedence and associativity.

The BSD and System V versions of -f are not the same. The BSD definition was:

-f file
True if file exists and is not a directory.

The SVID version (true if the file exists and is a regular file) was chosen for this volume of IEEE Std 1003.1-2001 because its use is consistent with the -b, -c, -d, and -p operands ( file exists and is a specific file type).

The -e primary, possessing similar functionality to that provided by the C shell, was added because it provides the only way for a shell script to find out if a file exists without trying to open the file. Since implementations are allowed to add additional file types, a portable script cannot use:

test -b foo -o -c foo -o -d foo -o -f foo -o -p foo

to find out if foo is an existing file. On historical BSD systems, the existence of a file could be determined by:

test -f foo -o -d foo

but there was no easy way to determine that an existing file was a regular file. An early proposal used the KornShell -a primary (with the same meaning), but this was changed to -e because there were concerns about the high probability of humans confusing the -a primary with the -a binary operator.

The following options were not included in this volume of IEEE Std 1003.1-2001, although they are provided by some implementations. These operands should not be used by new implementations for other purposes:

-k file
True if file exists and its sticky bit is set.
-C file
True if file is a contiguous file.
-V file
True if file is a version file.

The following option was not included because it was undocumented in most implementations, has been removed from some implementations (including System V), and the functionality is provided by the shell (see Parameter Expansion .

-l string
The length of the string string.

The -b, -c, -g, -p, -u, and -x operands are derived from the SVID; historical BSD does not provide them. The -k operand is derived from System V; historical BSD does not provide it.

On historical BSD systems, test -w directory always returned false because test tried to open the directory for writing, which always fails.

Some additional primaries newly invented or from the KornShell appeared in an early proposal as part of the conditional command ( [[]]): s1 > s2, s1 < s2, str = pattern, str != pattern, f1 -nt f2, f1 -ot f2, and f1 -ef f2. They were not carried forward into the test utility when the conditional command was removed from the shell because they have not been included in the test utility built into historical implementations of the sh utility.

The -t file_descriptor primary is shown with a mandatory argument because the grammar is ambiguous if it can be omitted. Historical implementations have allowed it to be omitted, providing a default of 1.

FUTURE DIRECTIONS

None.

SEE ALSO

File Read, Write, and Creation , find

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


file(1p)

FILE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

file - determine file type

SYNOPSIS

file [-dh][-M file][-m file] file ...

file -i [-h] file ...

DESCRIPTION

The file utility shall perform a series of tests in sequence on each specified file in an attempt to classify it:

1.
If file does not exist, cannot be read, or its file status could not be determined, the output shall indicate that the file was processed, but that its type could not be determined.

2.
If the file is not a regular file, its file type shall be identified. The file types directory, FIFO, socket, block special, and character special shall be identified as such. Other implementation-defined file types may also be identified. If file is a symbolic link, by default the link shall be resolved and file shall test the type of file referenced by the symbolic link. (See the -h and -i options below.)

3.
If the length of file is zero, it shall be identified as an empty file.

4.
The file utility shall examine an initial segment of file and shall make a guess at identifying its contents based on position-sensitive tests. (The answer is not guaranteed to be correct; see the -d, -M, and -m options below.)

5.
The file utility shall examine file and make a guess at identifying its contents based on context-sensitive default system tests. (The answer is not guaranteed to be correct.)

6.
The file shall be identified as a data file.

If file does not exist, cannot be read, or its file status could not be determined, the output shall indicate that the file was processed, but that its type could not be determined.

If file is a symbolic link, by default the link shall be resolved and file shall test the type of file referenced by the symbolic link.

OPTIONS

The file utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the order of the -m, -d, and -M options shall be significant.

The following options shall be supported by the implementation:

-d
Apply any position-sensitive default system tests and context-sensitive default system tests to the file. This is the default if no -M or -m option is specified.
-h
When a symbolic link is encountered, identify the file as a symbolic link. If -h is not specified and file is a symbolic link that refers to a nonexistent file, file shall identify the file as a symbolic link, as if -h had been specified.
-i
If a file is a regular file, do not attempt to classify the type of the file further, but identify the file as specified in the STDOUT section.
-M file
Specify the name of a file containing position-sensitive tests that shall be applied to a file in order to classify it (see the EXTENDED DESCRIPTION). No position-sensitive default system tests nor context-sensitive default system tests shall be applied unless the -d option is also specified.
-m file
Specify the name of a file containing position-sensitive tests that shall be applied to a file in order to classify it (see the EXTENDED DESCRIPTION).

If the -m option is specified without specifying the -d option or the -M option, position-sensitive default system tests shall be applied after the position-sensitive tests specified by the -m option. If the -M option is specified with the -d option, the -m option, or both, or the -m option is specified with the -d option, the concatenation of the position-sensitive tests specified by these options shall be applied in the order specified by the appearance of these options. If a -M or -m file option-argument is -, the results are unspecified.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be tested.

STDIN

Not used.

INPUT FILES

The file can be any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of file:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

In the POSIX locale, the following format shall be used to identify each operand, file specified:

"%s: %s\n", <file>, <type>

The values for <type> are unspecified, except that in the POSIX locale, if file is identified as one of the types listed in the following table, <type> shall contain (but is not limited to) the corresponding string, unless the file is identified by a position-sensitive test specified by a -M or -m option. Each space shown in the strings shall be exactly one <space>.

Table: File Utility Output Strings
If file is: | <type> shall contain the string: | Notes
Nonexistent | cannot open |
Block special | block special | 1
Character special | character special | 1
Directory | directory | 1
FIFO | fifo | 1
Socket | socket | 1
Symbolic link | symbolic link to | 1
Regular file | regular file | 1,2
Empty regular file | empty | 3
Regular file that cannot be read | cannot open | 3
Executable binary | executable | 4,6
ar archive library (see ar) | archive | 4,6
Extended cpio format (see pax) | cpio archive | 4,6
Extended tar format (see ustar in pax) | tar archive | 4,6
Shell script | commands text | 5,6
C-language source | c program text | 5,6
FORTRAN source | fortran program text | 5,6
Regular file whose type cannot be determined | data |
Notes:
1.
This is a file type test.

2.
This test is applied only if the -i option is specified.

3.
This test is applied only if the -i option is not specified.

4.
This is a position-sensitive default system test.

5.
This is a context-sensitive default system test.

6.
Position-sensitive default system tests and context-sensitive default system tests are not applied if the -M option is specified unless the -d option is also specified.

In the POSIX locale, if file is identified as a symbolic link (see the -h option), the following alternative output format shall be used:

"%s: %s %s\n", <file>, <type>, <contents of link>"

If the file named by the file operand does not exist, cannot be read, or the type of the file named by the file operand cannot be determined, this shall not be considered an error that affects the exit status.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

A file specified as an option-argument to the -m or -M options shall contain one position-sensitive test per line, which shall be applied to the file. If the test succeeds, the message field of the line shall be printed and no further tests shall be applied, with the exception that tests on immediately following lines beginning with a single '>' character shall be applied.

Each line shall be composed of the following four <blank>-separated fields:

offset
An unsigned number (optionally preceded by a single '>' character) specifying the offset, in bytes, of the value in the file that is to be compared against the value field of the line. If the file is shorter than the specified offset, the test shall fail.

If the offset begins with the character '>' , the test contained in the line shall not be applied to the file unless the test on the last line for which the offset did not begin with a '>' was successful. By default, the offset shall be interpreted as an unsigned decimal number. With a leading 0x or 0X, the offset shall be interpreted as a hexadecimal number; otherwise, with a leading 0, the offset shall be interpreted as an octal number.

type
The type of the value in the file to be tested. The type shall consist of the type specification characters c , d , f , s , and u , specifying character, signed decimal, floating point, string, and unsigned decimal, respectively.

The type string shall be interpreted as the bytes from the file starting at the specified offset and including the same number of bytes specified by the value field. If insufficient bytes remain in the file past the offset to match the value field, the test shall fail.

The type specification characters d , f , and u can be followed by an optional unsigned decimal integer that specifies the number of bytes represented by the type. The type specification character f can be followed by an optional F , D , or L , indicating that the value is of type float, double, or long double, respectively. The type specification characters d and u can be followed by an optional C , S , I , or L , indicating that the value is of type char, short, int, or long, respectively.

The default number of bytes represented by the type specifiers d , f , and u shall correspond to their respective C-language types as follows. If the system claims conformance to the C-Language Development Utilities option, those specifiers shall correspond to the default sizes used in the c99 utility. Otherwise, the default sizes shall be implementation-defined.

For the type specifier characters d and u , the default number of bytes shall correspond to the size of a basic integer type of the implementation. For these specifier characters, the implementation shall support values of the optional number of bytes to be converted corresponding to the number of bytes in the C-language types char, short, int, or long. These numbers can also be specified by an application as the characters C , S , I , and L , respectively. The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system.

For the type specifier f , the default number of bytes shall correspond to the number of bytes in the basic double precision floating-point data type of the underlying implementation. The implementation shall support values of the optional number of bytes to be converted corresponding to the number of bytes in the C-language types float, double, and long double. These numbers can also be specified by an application as the characters F , D , and L , respectively.

All type specifiers, except for s , can be followed by a mask specifier of the form &number. The mask value shall be AND'ed with the value of the input file before the comparison with the value field of the line is made. By default, the mask shall be interpreted as an unsigned decimal number. With a leading 0x or 0X, the mask shall be interpreted as an unsigned hexadecimal number; otherwise, with a leading 0, the mask shall be interpreted as an unsigned octal number.

The strings byte, short, long, and string shall also be supported as type fields, being interpreted as dC , dS , dL , and s , respectively.

value
The value to be compared with the value from the file.

If the specifier from the type field is s or string, then interpret the value as a string. Otherwise, interpret it as a number. If the value is a string, then the test shall succeed only when a string value exactly matches the bytes from the file.

If the value is a string, it can contain the following sequences:

\character
The backslash-escape sequences as specified in the Base Definitions volume of IEEE Std 1003.1-2001, Table 5-1, Escape Sequences and Associated Actions ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ). The results of using any other character, other than an octal digit, following the backslash are unspecified.
\octal
Octal sequences that can be used to represent characters with specific coded values. An octal sequence shall consist of a backslash followed by the longest sequence of one, two, or three octal-digit characters (01234567). If the size of a byte on the system is greater than 9 bits, the valid escape sequence used to represent a byte is implementation-defined.

By default, any value that is not a string shall be interpreted as a signed decimal number. Any such value, with a leading 0x or 0X, shall be interpreted as an unsigned hexadecimal number; otherwise, with a leading zero, the value shall be interpreted as an unsigned octal number.

If the value is not a string, it can be preceded by a character indicating the comparison to be performed. Permissible characters and the comparisons they specify are as follows:

=
The test shall succeed if the value from the file equals the value field.
<
The test shall succeed if the value from the file is less than the value field.
>
The test shall succeed if the value from the file is greater than the value field.
&
The test shall succeed if all of the set bits in the value field are set in the value from the file.
^
The test shall succeed if at least one of the set bits in the value field is not set in the value from the file.
x
The test shall succeed if the file is large enough to contain a value of the type specified starting at the offset specified.

message
The message to be printed if the test succeeds. The message shall be interpreted using the notation for the printf formatting specification; see printf() . If the value field was a string, then the value from the file shall be the argument for the printf formatting specification; otherwise, the value from the file shall be the argument.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The file utility can only be required to guess at many of the file types because only exhaustive testing can determine some types with certainty. For example, binary data on some implementations might match the initial segment of an executable or a tar archive.

Note that the table indicates that the output contains the stated string. Systems may add text before or after the string. For executables, as an example, the machine architecture and various facts about how the file was link-edited may be included. Note also that on systems that recognize shell script files starting with "#!" as executable files, these may be identified as executable binary files rather than as shell scripts.

EXAMPLES

Determine whether an argument is a binary executable file:

file "$1" | grep -Fq executable &&
    printf "%s is executable.\n" "$1"

RATIONALE

The -f option was omitted because the same effect can (and should) be obtained using the xargs utility.

Historical versions of the file utility attempt to identify the following types of files: symbolic link, directory, character special, block special, socket, tar archive, cpio archive, SCCS archive, archive library, empty, compress output, pack output, binary data, C source, FORTRAN source, assembler source, nroff/ troff/ eqn/ tbl source troff output, shell script, C shell script, English text, ASCII text, various executables, APL workspace, compiled terminfo entries, and CURSES screen images. Only those types that are reasonably well specified in POSIX or are directly related to POSIX utilities are listed in the table.

Historical systems have used a "magic file" named /etc/magic to help identify file types. Because it is generally useful for users and scripts to be able to identify special file types, the -m flag and a portable format for user-created magic files has been specified. No requirement is made that an implementation of file use this method of identifying files, only that users be permitted to add their own classifying tests.

In addition, three options have been added to historical practice. The -d flag has been added to permit users to cause their tests to follow any default system tests. The -i flag has been added to permit users to test portably for regular files in shell scripts. The -M flag has been added to permit users to ignore any default system tests.

The IEEE Std 1003.1-2001 description of default system tests and the interaction between the -d, -M, and -m options did not clearly indicate that there were two types of "default system tests". The "position-sensitive tests'' determine file types by looking for certain string or binary values at specific offsets in the file being examined. These position-sensitive tests were implemented in historical systems using the magic file described above. Some of these tests are now built into the file utility itself on some implementations so the output can provide more detail than can be provided by magic files. For example, a magic file can easily identify a core file on most implementations, but cannot name the program file that dropped the core. A magic file could produce output such as:

/home/dwc/core: ELF 32-bit MSB core file SPARC Version 1

but by building the test into the file utility, you could get output such as:

/home/dwc/core: ELF 32-bit MSB core file SPARC Version 1, from 'testprog'

These extended built-in tests are still to be treated as position-sensitive default system tests even if they are not listed in /etc/magic or any other magic file.

The context-sensitive default system tests were always built into the file utility. These tests looked for language constructs in text files trying to identify shell scripts, C, FORTRAN, and other computer language source files, and even plain text files. With the addition of the -m and -M options the distinction between position-sensitive and context-sensitive default system tests became important because the order of testing is important. The context-sensitive system default tests should never be applied before any position-sensitive tests even if the -d option is specified before a -m option or -M option due to the high probability that the context-sensitive system default tests will incorrectly identify arbitrary text files as text files before position-sensitive tests specified by the -m or -M option would be applied to give a more accurate identification.

Leaving the meaning of -M - and -m - unspecified allows an existing prototype of these options to continue to work in a backwards-compatible manner. (In that implementation, -M - was roughly equivalent to -d in IEEE Std 1003.1-2001.)

The historical -c option was omitted as not particularly useful to users or portable shell scripts. In addition, a reasonable implementation of the file utility would report any errors found each time the magic file is read.

The historical format of the magic file was the same as that specified by the Rationale in the ISO POSIX-2:1993 standard for the offset, value, and message fields; however, it used less precise type fields than the format specified by the current normative text. The new type field values are a superset of the historical ones.

The following is an example magic file:

0  short     070707              cpio archive
0  short     0143561             Byte-swapped cpio archive
0  string    070707              ASCII cpio archive
0  long      0177555             Very old archive
0  short     0177545             Old archive
0  short     017437              Old packed data
0  string    \037\036            Packed data
0  string    \377\037            Compacted data
0  string    \037\235            Compressed data
>2 byte&0x80 >0                  Block compressed
>2 byte&0x1f x                   %d bits
0  string    \032\001            Compiled Terminfo Entry
0  short     0433                Curses screen image
0  short     0434                Curses screen image
0  string    <ar>                System V Release 1 archive
0  string    !<arch>\n__.SYMDEF  Archive random library
0  string    !<arch>             Archive
0  string    ARF_BEGARF          PHIGS clear text archive
0  long      0x137A2950          Scalable OpenFont binary
0  long      0x137A2951          Encrypted scalable OpenFont binary

The use of a basic integer data type is intended to allow the implementation to choose a word size commonly used by applications on that architecture.

FUTURE DIRECTIONS

None.

SEE ALSO

ar , ls , pax

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


find(1p)

FIND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

find - find files

SYNOPSIS

find [-H | -L] path ... [operand_expression ...]

DESCRIPTION

The find utility shall recursively descend the directory hierarchy from each file specified by path, evaluating a Boolean expression composed of the primaries described in the OPERANDS section for each file encountered.

The find utility shall be able to descend to arbitrary depths in a file hierarchy and shall not fail due to path length limitations (unless a path operand specified by the application exceeds {PATH_MAX} requirements).

The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate.

OPTIONS

The find utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-H
Cause the file information and file type evaluated for each symbolic link encountered on the command line to be those of the file referenced by the link, and not the link itself. If the referenced file does not exist, the file information and type shall be for the link itself. File information for all symbolic links not on the command line shall be that of the link itself.
-L
Cause the file information and file type evaluated for each symbolic link to be those of the file referenced by the link, and not the link itself.

Specifying more than one of the mutually-exclusive options -H and -L shall not be considered an error. The last option specified shall determine the behavior of the utility.

OPERANDS

The following operands shall be supported:

The path operand is a pathname of a starting point in the directory hierarchy.

The first argument that starts with a '-' , or is a '!' or a '(' , and all subsequent arguments shall be interpreted as an expression made up of the following primaries and operators. In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus ( '-' ) sign, as follows:

+n
More than n.
n
Exactly n.
-n
Less than n.

The following primaries shall be supported:

-name pattern

The primary shall evaluate as true if the basename of the filename being examined matches pattern using the pattern matching notation described in Pattern Matching Notation .

-nouser
The primary shall evaluate as true if the file belongs to a user ID for which the getpwuid() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 (or equivalent) returns NULL.
-nogroup
The primary shall evaluate as true if the file belongs to a group ID for which the getgrgid() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 (or equivalent) returns NULL.
-xdev
The primary shall always evaluate as true; it shall cause find not to continue descending past directories that have a different device ID ( st_dev, see the stat() function defined in the System Interfaces volume of IEEE Std 1003.1-2001). If any -xdev primary is specified, it shall apply to the entire expression even if the -xdev primary would not normally be evaluated.
-prune
The primary shall always evaluate as true; it shall cause find not to descend the current pathname if it is a directory. If the -depth primary is specified, the -prune primary shall have no effect.
-perm [-]mode

The mode argument is used to represent file mode bits. It shall be identical in format to the symbolic_mode operand described in chmod() , and shall be interpreted as follows. To start, a template shall be assumed with all file mode bits cleared. An op symbol of '+' shall set the appropriate mode bits in the template; '-' shall clear the appropriate bits; '=' shall set the appropriate mode bits, without regard to the contents of process' file mode creation mask. The op symbol of '-' cannot be the first character of mode; this avoids ambiguity with the optional leading hyphen. Since the initial mode is all bits off, there are not any symbolic modes that need to use '-' as the first character.

If the hyphen is omitted, the primary shall evaluate as true when the file permission bits exactly match the value of the resulting template.

Otherwise, if mode is prefixed by a hyphen, the primary shall evaluate as true if at least all the bits in the resulting template are set in the file permission bits.

-perm [-]onum

If the hyphen is omitted, the primary shall evaluate as true when the file permission bits exactly match the value of the octal number onum and only the bits corresponding to the octal mask 07777 shall be compared. (See the description of the octal mode in chmod() .) Otherwise, if onum is prefixed by a hyphen, the primary shall evaluate as true if at least all of the bits specified in onum that are also set in the octal mask 07777 are set.

-type c
The primary shall evaluate as true if the type of the file is c, where c is 'b' , 'c' , 'd' , 'l' , 'p' , 'f' , or 's' for block special file, character special file, directory, symbolic link, FIFO, regular file, or socket, respectively.
-links n
The primary shall evaluate as true if the file has n links.
-user uname
The primary shall evaluate as true if the file belongs to the user uname. If uname is a decimal integer and the getpwnam() (or equivalent) function does not return a valid user name, uname shall be interpreted as a user ID.
-group gname

The primary shall evaluate as true if the file belongs to the group gname. If gname is a decimal integer and the getgrnam() (or equivalent) function does not return a valid group name, gname shall be interpreted as a group ID.

-size n[c]
The primary shall evaluate as true if the file size in bytes, divided by 512 and rounded up to the next integer, is n. If n is followed by the character 'c' , the size shall be in bytes.
-atime n
The primary shall evaluate as true if the file access time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.
-ctime n
The primary shall evaluate as true if the time of last change of file status information subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.
-mtime n
The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.
-exec utility_name [argument ...] ;
-exec utility_name [argument ...]
{} +

The end of the primary expression shall be punctuated by a semicolon or by a plus sign. Only a plus sign that follows an argument containing the two characters "{}" shall punctuate the end of the primary expression. Other uses of the plus sign shall not be treated as special.

If the primary expression is punctuated by a semicolon, the utility utility_name shall be invoked once for each pathname and the primary shall evaluate as true if the utility returns a zero value as exit status. A utility_name or argument containing only the two characters "{}" shall be replaced by the current pathname.

If the primary expression is punctuated by a plus sign, the primary shall always evaluate as true, and the pathnames for which the primary is evaluated shall be aggregated into sets. The utility utility_name shall be invoked once for each set of aggregated pathnames. Each invocation shall begin after the last pathname in the set is aggregated, and shall be completed before the find utility exits and before the first pathname in the next set (if any) is aggregated for this primary, but it is otherwise unspecified whether the invocation occurs before, during, or after the evaluations of other primaries. If any invocation returns a non-zero value as exit status, the find utility shall return a non-zero exit status. An argument containing only the two characters "{}" shall be replaced by the set of aggregated pathnames, with each pathname passed as a separate argument to the invoked utility in the same order that it was aggregated. The size of any set of two or more pathnames shall be limited such that execution of the utility does not cause the system's {ARG_MAX} limit to be exceeded. If more than one argument containing only the two characters "{}" is present, the behavior is unspecified.

If a utility_name or argument string contains the two characters "{}" , but not just the two characters "{}" , it is implementation-defined whether find replaces those two characters or uses the string without change. The current directory for the invocation of utility_name shall be the same as the current directory when the find utility was started. If the utility_name names any of the special built-in utilities (see Special Built-In Utilities ), the results are undefined.

-ok utility_name [argument ...] ;

The -ok primary shall be equivalent to -exec, except that the use of a plus sign to punctuate the end of the primary expression need not be supported, and find shall request affirmation of the invocation of utility_name using the current file as an argument by writing to standard error as described in the STDERR section. If the response on standard input is affirmative, the utility shall be invoked. Otherwise, the command shall not be invoked and the value of the -ok operand shall be false.

-print
The primary shall always evaluate as true; it shall cause the current pathname to be written to standard output.
-newer file
The primary shall evaluate as true if the modification time of the current file is more recent than the modification time of the file named by the pathname file.
-depth
The primary shall always evaluate as true; it shall cause descent of the directory hierarchy to be done so that all entries in a directory are acted on before the directory itself. If a -depth primary is not specified, all entries in a directory shall be acted on after the directory itself. If any -depth primary is specified, it shall apply to the entire expression even if the -depth primary would not normally be evaluated.

The primaries can be combined using the following operators (in order of decreasing precedence):

( expression )
True if expression is true.
! expression
Negation of a primary; the unary NOT operator.
expression [-a] expression

Conjunction of primaries; the AND operator is implied by the juxtaposition of two primaries or made explicit by the optional -a operator. The second expression shall not be evaluated if the first expression is false.

expression -o expression

Alternation of primaries; the OR operator. The second expression shall not be evaluated if the first expression is true.

If no expression is present, -print shall be used as the expression. Otherwise, if the given expression does not contain any of the primaries -exec, -ok, or -print, the given expression shall be effectively replaced by:

( given_expression ) -print

The -user, -group, and -newer primaries each shall evaluate their respective arguments only once.

STDIN

If the -ok primary is used, the response shall be read from the standard input. An entire line shall be read as the response. Otherwise, the standard input shall not be used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of find:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements used in the pattern matching notation for the -n option and in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.

LC_CTYPE
This variable determines the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments), the behavior of character classes within the pattern matching notation used for the -n option, and the behavior of character classes within regular expressions used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.
LC_MESSAGES
Determine the locale for the processing of affirmative responses that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the location of the utility_name for the -exec and -ok primaries, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The -print primary shall cause the current pathnames to be written to standard output. The format shall be:

"%s\n", <path>

STDERR

The -ok primary shall write a prompt to standard error containing at least the utility_name to be invoked and the current pathname. In the POSIX locale, the last non- <blank> in the prompt shall be '?' . The exact format used is unspecified.

Otherwise, the standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All path operands were traversed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

When used in operands, pattern matching notation, semicolons, opening parentheses, and closing parentheses are special to the shell and must be quoted (see Quoting ).

The bit that is traditionally used for sticky (historically 01000) is specified in the -perm primary using the octal number argument form. Since this bit is not defined by this volume of IEEE Std 1003.1-2001, applications must not assume that it actually refers to the traditional sticky bit.

EXAMPLES

1.
The following commands are equivalent:

find .
find . -print

They both write out the entire directory hierarchy from the current directory.

2.
The following command:

find / \( -name tmp -o -name '*.xx' \) -atime +7 -exec rm {} \;

removes all files named tmp or ending in .xx that have not been accessed for seven or more 24-hour periods.

3.
The following command:

find . -perm -o+w,+s

prints ( -print is assumed) the names of all files in or below the current directory, with all of the file permission bits S_ISUID, S_ISGID, and S_IWOTH set.

4.
The following command:

find . -name SCCS -prune -o -print

recursively prints pathnames of all files in the current directory and below, but skips directories named SCCS and files in them.

5.
The following command:

find . -print -name SCCS -prune

behaves as in the previous example, but prints the names of the SCCS directories.

6.
The following command is roughly equivalent to the -nt extension to test:

if [ -n "$(find file1 -prune -newer file2)" ]; then
    printf %s\\n "file1 is newer than file2"
fi

7.
The descriptions of -atime, -ctime, and -mtime use the terminology n "86400 second periods (days)". For example, a file accessed at 23:59 is selected by:

find . -atime -1 -print

at 00:01 the next day (less than 24 hours later, not more than one day ago); the midnight boundary between days has no effect on the 24-hour calculation.

RATIONALE

The -a operator was retained as an optional operator for compatibility with historical shell scripts, even though it is redundant with expression concatenation.

The descriptions of the '-' modifier on the mode and onum arguments to the -perm primary agree with historical practice on BSD and System V implementations. System V and BSD documentation both describe it in terms of checking additional bits; in fact, it uses the same bits, but checks for having at least all of the matching bits set instead of having exactly the matching bits set.

The exact format of the interactive prompts is unspecified. Only the general nature of the contents of prompts are specified because:

*
Implementations may desire more descriptive prompts than those used on historical implementations.

*
Since the historical prompt strings do not terminate with <newline>s, there is no portable way for another program to interact with the prompts of this utility via pipes.

Therefore, an application using this prompting option relies on the system to provide the most suitable dialog directly with the user, based on the general guidelines specified.

The -name file operand was changed to use the shell pattern matching notation so that find is consistent with other utilities using pattern matching.

The -size operand refers to the size of a file, rather than the number of blocks it may occupy in the file system. The intent is that the st_size field defined in the System Interfaces volume of IEEE Std 1003.1-2001 should be used, not the st_blocks found in historical implementations. There are at least two reasons for this:

1.
In both System V and BSD, find only uses st_size in size calculations for the operands specified by this volume of IEEE Std 1003.1-2001. (BSD uses st_blocks only when processing the -ls primary.)

2.
Users usually think of file size in terms of bytes, which is also the unit used by the ls utility for the output from the -l option. (In both System V and BSD, ls uses st_size for the -l option size field and uses st_blocks for the ls -s calculations. This volume of IEEE Std 1003.1-2001 does not specify ls -s.)

The descriptions of -atime, -ctime, and -mtime were changed from the SVID description of n "days'' to "24-hour periods". The description is also different in terms of the exact timeframe for the n case (versus the +n or -n), but it matches all known historical implementations. It refers to one 86400 second period in the past, not any time from the beginning of that period to the current time. For example, -atime 3 is true if the file was accessed any time in the period from 72 hours to 48 hours ago.

Historical implementations do not modify "{}" when it appears as a substring of an -exec or -ok utility_name or argument string. There have been numerous user requests for this extension, so this volume of IEEE Std 1003.1-2001 allows the desired behavior. At least one recent implementation does support this feature, but encountered several problems in managing memory allocation and dealing with multiple occurrences of "{}" in a string while it was being developed, so it is not yet required behavior.

Assuming the presence of -print was added to correct a historical pitfall that plagues novice users, it is entirely upwards-compatible from the historical System V find utility. In its simplest form ( find directory), it could be confused with the historical BSD fast find. The BSD developers agreed that adding -print as a default expression was the correct decision and have added the fast find functionality within a new utility called locate.

Historically, the -L option was implemented using the primary -follow. The -H and -L options were added for two reasons. First, they offer a finer granularity of control and consistency with other programs that walk file hierarchies. Second, the -follow primary always evaluated to true. As they were historically really global variables that took effect before the traversal began, some valid expressions had unexpected results. An example is the expression -print -o -follow. Because -print always evaluates to true, the standard order of evaluation implies that -follow would never be evaluated. This was never the case. Historical practice for the -follow primary, however, is not consistent. Some implementations always follow symbolic links on the command line whether -follow is specified or not. Others follow symbolic links on the command line only if -follow is specified. Both behaviors are provided by the -H and -L options, but scripts using the current -follow primary would be broken if the -follow option is specified to work either way.

Since the -L option resolves all symbolic links and the -type l primary is true for symbolic links that still exist after symbolic links have been resolved, the command:

find -L . -type l

prints a list of symbolic links reachable from the current directory that do not resolve to accessible files.

A feature of SVR4's find utility was the -exec primary's + terminator. This allowed filenames containing special characters (especially <newline>s) to be grouped together without the problems that occur if such filenames are piped to xargs. Other implementations have added other ways to get around this problem, notably a -print0 primary that wrote filenames with a null byte terminator. This was considered here, but not adopted. Using a null terminator meant that any utility that was going to process find's -print0 output had to add a new option to parse the null terminators it would now be reading.

The "-exec ... {} +" syntax adopted was a result of IEEE PASC Interpretation 1003.2 #210. It should be noted that this is an incompatible change to the ISO/IEC 9899:1999 standard. For example, the following command prints all files with a '-' after their name if they are regular files, and a '+' otherwise:

find / -type f -exec echo {} - ';' -o -exec echo {} + ';'

The change invalidates usage like this. Even though the previous standard stated that this usage would work, in practice many did not support it and the standard developers felt it better to now state that this was not allowable.

FUTURE DIRECTIONS

None.

SEE ALSO

Quoting , Pattern Matching Notation , Special Built-In Utilities , chmod() , pax , sh , test , the System Interfaces volume of IEEE Std 1003.1-2001, getgrgid(), getpwuid(), stat()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


eval(1p)

EVAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

eval - construct command by concatenating arguments

SYNOPSIS

eval [argument ...]

DESCRIPTION

The eval utility shall construct a command by concatenating arguments together, separating each with a <space>. The constructed command shall be read and executed by the shell.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If there are no arguments, or only null arguments, eval shall return a zero exit status; otherwise, it shall return the exit status of the command defined by the string of concatenated arguments separated by <space>s.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

foo=10 x=foo
y='$'$x
echo $y
$fooeval y='$'$x
echo $y
10

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strings(1p)

STRINGS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strings - find printable strings in files

SYNOPSIS

strings [-a][-t format][-n number][file...]

DESCRIPTION

The strings utility shall look for printable strings in regular files and shall write those strings to standard output. A printable string is any sequence of four (by default) or more printable characters terminated by a <newline> or NUL character. Additional implementation-defined strings may be written; see localedef.

OPTIONS

The strings utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Scan files in their entirety. If -a is not specified, it is implementation-defined what portion of each file is scanned for strings.
-n number
Specify the minimum string length, where the number argument is a positive decimal integer. The default shall be 4.
-t format
Write each string preceded by its byte offset from the start of the file. The format shall be dependent on the single character used as the format option-argument:
d
The offset shall be written in decimal.
o
The offset shall be written in octal.
x
The offset shall be written in hexadecimal.

OPERANDS

The following operand shall be supported:

file
A pathname of a regular file to be used as input. If no file operand is specified, the strings utility shall read from the standard input.

STDIN

See the INPUT FILES section.

INPUT FILES

The input files named by the utility arguments or the standard input shall be regular files of any format.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of strings:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and to identify printable strings.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Strings found shall be written to the standard output, one per line.

When the -t option is not specified, the format of the output shall be:

"%s", <string>

With the -t o option, the format of the output shall be:

"%o %s", <byte offset>, <string>

With the -t x option, the format of the output shall be:

"%x %s", <byte offset>, <string>

With the -t d option, the format of the output shall be:

"%d %s", <byte offset>, <string>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

By default the data area (as opposed to the text, "bss", or header areas) of a binary executable file is scanned. Implementations document which areas are scanned.

Some historical implementations do not require NUL or <newline> terminators for strings to permit those languages that do not use NUL as a string terminator to have their strings written.

EXAMPLES

None.

RATIONALE

Apart from rationalizing the option syntax and slight difficulties with object and executable binary files, strings is specified to match historical practice closely. The -a and -n options were introduced to replace the non-conforming - and - number options.

The -o option historically means different things on different implementations. Some use it to mean " offset in decimal", while others use it as " offset in octal". Instead of trying to decide which way would be least objectionable, the -t option was added. It was originally named -O to mean "offset", but was changed to -t to be consistent with od.

The ISO C standard function isprint() is restricted to a domain of unsigned char. This volume of IEEE Std 1003.1-2001 requires implementations to write strings as defined by the current locale.

FUTURE DIRECTIONS

None.

SEE ALSO

localedef , nm

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


basename(1p)

BASENAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

basename - return non-directory portion of a pathname

SYNOPSIS

basename string [suffix]

DESCRIPTION

The string operand shall be treated as a pathname, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.266, Pathname. The string string shall be converted to the filename corresponding to the last pathname component in string and then the suffix string suffix, if present, shall be removed. This shall be done by performing actions equivalent to the following steps in order:

1.
If string is a null string, it is unspecified whether the resulting string is '.' or a null string. In either case, skip steps 2 through 6.

2.
If string is "//" , it is implementation-defined whether steps 3 to 6 are skipped or processed.

3.
If string consists entirely of slash characters, string shall be set to a single slash character. In this case, skip steps 4 to 6.

4.
If there are any trailing slash characters in string, they shall be removed.

5.
If there are any slash characters remaining in string, the prefix of string up to and including the last slash character in string shall be removed.

6.
If the suffix operand is present, is not identical to the characters remaining in string, and is identical to a suffix of the characters remaining in string, the suffix suffix shall be removed from string. Otherwise, string is not modified by this step. It shall not be considered an error if suffix is not found in string.

The resulting string shall be written to standard output.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

string
A string.
suffix
A string.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of basename:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The basename utility shall write a line to the standard output in the following format:

"%s\n", <resulting string>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The definition of pathname specifies implementation-defined behavior for pathnames starting with two slash characters. Therefore, applications shall not arbitrarily add slashes to the beginning of a pathname unless they can ensure that there are more or less than two or are prepared to deal with the implementation-defined consequences.

EXAMPLES

If the string string is a valid pathname:

$(basename "string")

produces a filename that could be used to open the file named by string in the directory returned by:

$(dirname "string")

If the string string is not a valid pathname, the same algorithm is used, but the result need not be a valid filename. The basename utility is not expected to make any judgements about the validity of string as a pathname; it just follows the specified algorithm to produce a result string.

The following shell script compiles /usr/src/cmd/cat.c and moves the output to a file named cat in the current directory when invoked with the argument /usr/src/cmd/cat or with the argument /usr/src/cmd/cat.c:

c99 $(dirname "$1")/$(basename "$1" .c).c
mv a.out $(basename "$1" .c)

RATIONALE

The behaviors of basename and dirname have been coordinated so that when string is a valid pathname:

$(basename "string")

would be a valid filename for the file in the directory:

$(dirname "string")

This would not work for the early proposal versions of these utilities due to the way it specified handling of trailing slashes.

Since the definition of pathname specifies implementation-defined behavior for pathnames starting with two slash characters, this volume of IEEE Std 1003.1-2001 specifies similar implementation-defined behavior for the basename and dirname utilities.

FUTURE DIRECTIONS

None.

SEE ALSO

Parameters and Variables , dirname()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


asa(1p)

ASA

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

asa - interpret carriage-control characters

SYNOPSIS

asa [ file ... ]

DESCRIPTION

The asa utility shall write its input files to standard output, mapping carriage-control characters from the text files to line-printer control sequences in an implementation-defined manner.

The first character of every line shall be removed from the input, and the following actions are performed.

If the character removed is:

<space>
The rest of the line is output without change.
0
A <newline> is output, then the rest of the input line.
1
One or more implementation-defined characters that causes an advance to the next page shall be output, followed by the rest of the input line.
+
The <newline> of the previous line shall be replaced with one or more implementation-defined characters that causes printing to return to column position 1, followed by the rest of the input line. If the '+' is the first character in the input, it shall be equivalent to <space>.

The action of the asa utility is unspecified upon encountering any character other than those listed above as the first character in a line.

OPTIONS

None.

OPERANDS

file
A pathname of a text file used for input. If no file operands are specified, the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified; see the INPUT FILES section.

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of asa:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be the text from the input file modified as described in the DESCRIPTION section.

STDERR

None.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were output successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

1.
The following command:

asa file

permits the viewing of file (created by a program using FORTRAN-style carriage-control characters) on a terminal.

2.
The following command:

a.out | asa | lp

formats the FORTRAN output of a.out and directs it to the printer.

RATIONALE

The asa utility is needed to map "standard" FORTRAN 77 output into a form acceptable to contemporary printers. Usually, asa is used to pipe data to the lp utility; see lp.

This utility is generally used only by FORTRAN programs. The standard developers decided to retain asa to avoid breaking the historical large base of FORTRAN applications that put carriage-control characters in their output files. There is no requirement that a system have a FORTRAN compiler in order to run applications that need asa.

Historical implementations have used an ASCII <form-feed> in response to a 1 and an ASCII <carriage-return> in response to a '+' . It is suggested that implementations treat characters other than 0, 1, and '+' as <space> in the absence of any compelling reason to do otherwise. However, the action is listed here as "unspecified", permitting an implementation to provide extensions to access fast multiple-line slewing and channel seeking in a non-portable manner.

FUTURE DIRECTIONS

None.

SEE ALSO

fort77 , lp

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


time(1p)

TIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

time - time a simple command

SYNOPSIS

time [-p] utility [argument...]

DESCRIPTION

The time utility shall invoke the utility named by the utility operand with arguments supplied as the argument operands and write a message to standard error that lists timing statistics for the utility. The message shall include the following information:

*
The elapsed (real) time between invocation of utility and its termination.

*
The User CPU time, equivalent to the sum of the tms_utime and tms_cutime fields returned by the times() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 for the process in which utility is executed.

*
The System CPU time, equivalent to the sum of the tms_stime and tms_cstime fields returned by the times() function for the process in which utility is executed.

The precision of the timing shall be no less than the granularity defined for the size of the clock tick unit on the system, but the results shall be reported in terms of standard time units (for example, 0.02 seconds, 00:00:00.02, 1m33.75s, 365.21 seconds), not numbers of clock ticks.

When time is used as part of a pipeline, the times reported are unspecified, except when it is the sole command within a grouping command (see Grouping Commands ) in that pipeline. For example, the commands on the left are unspecified; those on the right report on utilities a and c, respectively:

time a | b | c    { time a } | b | c
a | b | time c    a | b | (time c)

OPTIONS

The time utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-p
Write the timing output to standard error in the format shown in the STDERR section.

OPERANDS

The following operands shall be supported:

utility
The name of a utility that is to be invoked. If the utility operand names any of the special built-in utilities in Special Built-In Utilities , the results are undefined.
argument
Any string to be supplied as an argument when invoking the utility named by the utility operand.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of time:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic and informative messages written to standard error.
LC_NUMERIC

Determine the locale for numeric formatting.

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the search path that shall be used to locate the utility to be invoked; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used to write the timing statistics. If -p is specified, the following format shall be used in the POSIX locale:

"real %f\nuser %f\nsys %f\n", <real seconds>, <user seconds>,
    <system seconds>

where each floating-point number shall be expressed in seconds. The precision used may be less than the default six digits of %f , but shall be sufficiently precise to accommodate the size of the clock tick on the system (for example, if there were 60 clock ticks per second, at least two digits shall follow the radix character). The number of digits following the radix character shall be no less than one, even if this always results in a trailing zero. The implementation may append white space and additional information following the format shown here.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If the utility utility is invoked, the exit status of time shall be the exit status of utility; otherwise, the time utility shall exit with one of the following values:

1-125
An error occurred in the time utility.
126
The utility specified by utility was found but could not be invoked.
127
The utility specified by utility could not be found.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The command, env, nice, nohup, time, and xargs utilities have been specified to use exit code 127 if an error occurs so that applications can distinguish "failure to find a utility" from "invoked utility exited with an error indication". The value 127 was chosen because it is not commonly used for other meanings; most utilities use small values for "normal error conditions" and the values above 128 can be confused with termination due to receipt of a signal. The value 126 was chosen in a similar manner to indicate that the utility could be found, but not invoked. Some scripts produce meaningful error messages differentiating the 126 and 127 cases. The distinction between exit codes 126 and 127 is based on KornShell practice that uses 127 when all attempts to exec the utility fail with [ENOENT], and uses 126 when any attempt to exec the utility fails for any other reason.

EXAMPLES

It is frequently desirable to apply time to pipelines or lists of commands. This can be done by placing pipelines and command lists in a single file; this file can then be invoked as a utility, and the time applies to everything in the file.

Alternatively, the following command can be used to apply time to a complex command:

time sh -c 'complex-command-line'

RATIONALE

When the time utility was originally proposed to be included in the ISO POSIX-2:1993 standard, questions were raised about its suitability for inclusion on the grounds that it was not useful for conforming applications, specifically:

*
The underlying CPU definitions from the System Interfaces volume of IEEE Std 1003.1-2001 are vague, so the numeric output could not be compared accurately between systems or even between invocations.

*
The creation of portable benchmark programs was outside the scope this volume of IEEE Std 1003.1-2001.

However, time does fit in the scope of user portability. Human judgement can be applied to the analysis of the output, and it could be very useful in hands-on debugging of applications or in providing subjective measures of system performance. Hence it has been included in this volume of IEEE Std 1003.1-2001.

The default output format has been left unspecified because historical implementations differ greatly in their style of depicting this numeric output. The -p option was invented to provide scripts with a common means of obtaining this information.

In the KornShell, time is a shell reserved word that can be used to time an entire pipeline, rather than just a simple command. The POSIX definition has been worded to allow this implementation. Consideration was given to invalidating this approach because of the historical model from the C shell and System V shell. However, since the System V time utility historically has not produced accurate results in pipeline timing (because the constituent processes are not all owned by the same parent process, as allowed by POSIX), it did not seem worthwhile to break historical KornShell usage.

The term utility is used, rather than command, to highlight the fact that shell compound commands, pipelines, special built-ins, and so on, cannot be used directly. However, utility includes user application programs and shell scripts, not just the standard utilities.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , sh , the System Interfaces volume of IEEE Std 1003.1-2001, times()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


awk(1p)

AWK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

awk - pattern scanning and processing language

SYNOPSIS

awk [-F ERE][-v assignment] ... program [argument ...]

awk [-F ERE] -f progfile ... [-v assignment] ...[argument ...]

DESCRIPTION

The awk utility shall execute programs written in the awk programming language, which is specialized for textual data manipulation. An awk program is a sequence of patterns and corresponding actions. When input is read that matches a pattern, the action associated with that pattern is carried out.

Input shall be interpreted as a sequence of records. By default, a record is a line, less its terminating <newline>, but this can be changed by using the RS built-in variable. Each record of input shall be matched in turn against each pattern in the program. For each pattern matched, the associated action shall be executed.

The awk utility shall interpret each input record as a sequence of fields where, by default, a field is a string of non- <blank>s. This default white-space field delimiter can be changed by using the FS built-in variable or -F ERE. The awk utility shall denote the first field in a record $1, the second $2, and so on. The symbol $0 shall refer to the entire record; setting any other field causes the re-evaluation of $0. Assigning to $0 shall reset the values of all other fields and the NF built-in variable.

OPTIONS

The awk utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-F ERE
Define the input field separator to be the extended regular expression ERE, before any input is read; see Regular Expressions .
-f progfile
Specify the pathname of the file progfile containing an awk program. If multiple instances of this option are specified, the concatenation of the files specified as progfile in the order specified shall be the awk program. The awk program can alternatively be specified in the command line as a single argument.
-v assignment
The application shall ensure that the assignment argument is in the same form as an assignment operand. The specified variable assignment shall occur prior to executing the awk program, including the actions associated with BEGIN patterns (if any). Multiple occurrences of this option can be specified.

OPERANDS

The following operands shall be supported:

program
If no -f option is specified, the first operand to awk shall be the text of the awk program. The application shall supply the program operand as a single argument to awk. If the text does not end in a <newline>, awk shall interpret the text as if it did.
argument
Either of the following two types of argument can be intermixed:
file
A pathname of a file that contains the input to be read, which is matched against the set of patterns in the program. If no file operands are specified, or if a file operand is '-' , the standard input shall be used.
assignment
An operand that begins with an underscore or alphabetic character from the portable character set (see the table in the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set), followed by a sequence of underscores, digits, and alphabetics from the portable character set, followed by the '=' character, shall specify a variable assignment rather than a pathname. The characters before the '=' represent the name of an awk variable; if that name is an awk reserved word (see Grammar ) the behavior is undefined. The characters following the equal sign shall be interpreted as if they appeared in the awk program preceded and followed by a double-quote ( ' )' character, as a STRING token (see Grammar ), except that if the last character is an unescaped backslash, it shall be interpreted as a literal backslash rather than as the first character of the sequence "\"" . The variable shall be assigned the value of that STRING token and, if appropriate, shall be considered a numeric string (see Expressions in awk ), the variable shall also be assigned its numeric value. Each such variable assignment shall occur just prior to the processing of the following file, if any. Thus, an assignment before the first file argument shall be executed after the BEGIN actions (if any), while an assignment after the last file argument shall occur before the END actions (if any). If there are no file arguments, assignments shall be executed before processing the standard input.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' ; see the INPUT FILES section. If the awk program contains no actions and no patterns, but is otherwise a valid awk program, standard input and any file operands shall not be read and awk shall exit with a return status of zero.

INPUT FILES

Input files to the awk program from any of the following sources shall be text files:

*
Any file operands or their equivalents, achieved by modifying the awk variables ARGV and ARGC

*
Standard input in the absence of any file operands

*
Arguments to the getline function

Whether the variable RS is set to a value other than a <newline> or not, for these files, implementations shall support records terminated with the specified separator up to {LINE_MAX} bytes and may support longer records.

If -f progfile is specified, the application shall ensure that the files named by each of the progfile option-arguments are text files and their concatenation, in the same order as they appear in the arguments, is an awk program.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of awk:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE
Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions and in comparisons of string values.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the behavior of character classes within regular expressions, the identification of characters as letters, and the mapping of uppercase and lowercase characters for the toupper and tolower functions.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_NUMERIC
Determine the radix character used when interpreting numeric input, performing conversions between numeric and string values, and formatting numeric output. Regardless of locale, the period character (the decimal-point character of the POSIX locale) is the decimal-point character recognized in processing awk programs (including assignments in command line arguments).
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the search path when looking for commands executed by system(expr), or input and output pipes; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

In addition, all environment variables shall be visible via the awk variable ENVIRON.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The nature of the output files depends on the awk program.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The nature of the output files depends on the awk program.

EXTENDED DESCRIPTION

Overall Program Structure

An awk program is composed of pairs of the form:

pattern { action }

Either the pattern or the action (including the enclosing brace characters) can be omitted.

A missing pattern shall match any record of input, and a missing action shall be equivalent to:

{ print }

Execution of the awk program shall start by first executing the actions associated with all BEGIN patterns in the order they occur in the program. Then each file operand (or standard input if no files were specified) shall be processed in turn by reading data from the file until a record separator is seen ( <newline> by default). Before the first reference to a field in the record is evaluated, the record shall be split into fields, according to the rules in Regular Expressions , using the value of FS that was current at the time the record was read. Each pattern in the program then shall be evaluated in the order of occurrence, and the action associated with each pattern that matches the current record executed. The action for a matching pattern shall be executed before evaluating subsequent patterns. Finally, the actions associated with all END patterns shall be executed in the order they occur in the program.

Expressions in awk

Expressions describe computations used in patterns and actions. In the following table, valid expression operations are given in groups from highest precedence first to lowest precedence last, with equal-precedence operators grouped between horizontal lines. In expression evaluation, where the grammar is formally ambiguous, higher precedence operators shall be evaluated before lower precedence operators. In this table expr, expr1, expr2, and expr3 represent any expression, while lvalue represents any entity that can be assigned to (that is, on the left side of an assignment operator). The precise syntax of expressions is given in Grammar .

Table: Expressions in Decreasing Precedence in awk
Syntax | Name | Type of Result | Associativity
( expr ) | Grouping | Type of expr | N/A
$expr | Field reference | String | N/A
++ lvalue | Pre-increment | Numeric | N/A
-- lvalue | Pre-decrement | Numeric | N/A
lvalue ++ | Post-increment | Numeric | N/A
lvalue -- | Post-decrement | Numeric | N/A
expr ^ expr | Exponentiation | Numeric | Right
! expr | Logical not | Numeric | N/A
+ expr | Unary plus | Numeric | N/A
- expr | Unary minus | Numeric | N/A
expr * expr | Multiplication | Numeric | Left
expr / expr | Division | Numeric | Left
expr % expr | Modulus | Numeric | Left
expr + expr | Addition | Numeric | Left
expr - expr | Subtraction | Numeric | Left
expr expr | String concatenation | String | Left
expr < expr | Less than | Numeric | None
expr <= expr | Less than or equal to | Numeric | None
expr != expr | Not equal to | Numeric | None
expr == expr | Equal to | Numeric | None
expr > expr | Greater than | Numeric | None
expr >= expr | Greater than or equal to | Numeric | None
expr ~ expr | ERE match | Numeric | None
expr !~ expr | ERE non-match | Numeric | None
expr in array | Array membership | Numeric | Left
( index ) in array | Multi-dimension array | Numeric | Left
 | membership |  |
expr && expr | Logical AND | Numeric | Left
expr || expr | Logical OR | Numeric | Left
expr1 ? expr2 : expr3 | Conditional expression | Type of selected | Right
 |  | expr2 or expr3 |
lvalue ^= expr | Exponentiation assignment | Numeric | Right
lvalue %= expr | Modulus assignment | Numeric | Right
lvalue *= expr | Multiplication assignment | Numeric | Right
lvalue /= expr | Division assignment | Numeric | Right
lvalue += expr | Addition assignment | Numeric | Right
lvalue -= expr | Subtraction assignment | Numeric | Right
lvalue = expr | Assignment | Type of expr | Right

Each expression shall have either a string value, a numeric value, or both. Except as stated for specific contexts, the value of an expression shall be implicitly converted to the type needed for the context in which it is used. A string value shall be converted to a numeric value by the equivalent of the following calls to functions defined by the ISO C standard:

setlocale(LC_NUMERIC, "");
numeric_value = atof(string_value);

A numeric value that is exactly equal to the value of an integer (see Concepts Derived from the ISO C Standard ) shall be converted to a string by the equivalent of a call to the sprintf function (see String Functions ) with the string "%d" as the fmt argument and the numeric value being converted as the first and only expr argument. Any other numeric value shall be converted to a string by the equivalent of a call to the sprintf function with the value of the variable CONVFMT as the fmt argument and the numeric value being converted as the first and only expr argument. The result of the conversion is unspecified if the value of CONVFMT is not a floating-point format specification. This volume of IEEE Std 1003.1-2001 specifies no explicit conversions between numbers and strings. An application can force an expression to be treated as a number by adding zero to it, or can force it to be treated as a string by concatenating the null string ( "" ) to it.

A string value shall be considered a numeric string if it comes from one of the following:

1.
Field variables

2.
Input from the getline() function

3.
FILENAME

4.
ARGV array elements

5.
ENVIRON array elements

6.
Array elements created by the split() function

7.
A command line variable assignment

8.
Variable assignment from another numeric string variable

and after all the following conversions have been applied, the resulting string would lexically be recognized as a NUMBER token as described by the lexical conventions in Grammar :

*
All leading and trailing <blank>s are discarded.

*
If the first non- <blank> is '+' or '-' , it is discarded.

*
Changing each occurrence of the decimal point character from the current locale to a period.

If a '-' character is ignored in the preceding description, the numeric value of the numeric string shall be the negation of the numeric value of the recognized NUMBER token. Otherwise, the numeric value of the numeric string shall be the numeric value of the recognized NUMBER token. Whether or not a string is a numeric string shall be relevant only in contexts where that term is used in this section.

When an expression is used in a Boolean context, if it has a numeric value, a value of zero shall be treated as false and any other value shall be treated as true. Otherwise, a string value of the null string shall be treated as false and any other value shall be treated as true. A Boolean context shall be one of the following:

*
The first subexpression of a conditional expression

*
An expression operated on by logical NOT, logical AND, or logical OR

*
The second expression of a for statement

*
The expression of an if statement

*
The expression of the while clause in either a while or do... while statement

*
An expression used as a pattern (as in Overall Program Structure)

All arithmetic shall follow the semantics of floating-point arithmetic as specified by the ISO C standard (see Concepts Derived from the ISO C Standard ).

The value of the expression:

expr1 ^ expr2

shall be equivalent to the value returned by the ISO C standard function call:

pow(expr1, expr2)

The expression:

lvalue ^= expr

shall be equivalent to the ISO C standard expression:

lvalue = pow(lvalue, expr)

except that lvalue shall be evaluated only once. The value of the expression:

expr1 % expr2

shall be equivalent to the value returned by the ISO C standard function call:

fmod(expr1, expr2)

The expression:

lvalue %= expr

shall be equivalent to the ISO C standard expression:

lvalue = fmod(lvalue, expr)

except that lvalue shall be evaluated only once.

Variables and fields shall be set by the assignment statement:

lvalue = expression

and the type of expression shall determine the resulting variable type. The assignment includes the arithmetic assignments ( "+=" , "-=" , "*=" , "/=" , "%=" , "^=" , "++" , "--" ) all of which shall produce a numeric result. The left-hand side of an assignment and the target of increment and decrement operators can be one of a variable, an array with index, or a field selector.

The awk language supplies arrays that are used for storing numbers or strings. Arrays need not be declared. They shall initially be empty, and their sizes shall change dynamically. The subscripts, or element identifiers, are strings, providing a type of associative array capability. An array name followed by a subscript within square brackets can be used as an lvalue and thus as an expression, as described in the grammar; see Grammar . Unsubscripted array names can be used in only the following contexts:

*
A parameter in a function definition or function call

*
The NAME token following any use of the keyword in as specified in the grammar (see Grammar ); if the name used in this context is not an array name, the behavior is undefined

A valid array index shall consist of one or more comma-separated expressions, similar to the way in which multi-dimensional arrays are indexed in some programming languages. Because awk arrays are really one-dimensional, such a comma-separated list shall be converted to a single string by concatenating the string values of the separate expressions, each separated from the other by the value of the SUBSEP variable. Thus, the following two index operations shall be equivalent:

var[expr1, expr2, ... exprn]

var[expr1 SUBSEP expr2 SUBSEP ... SUBSEP exprn]

The application shall ensure that a multi-dimensioned index used with the in operator is parenthesized. The in operator, which tests for the existence of a particular array element, shall not cause that element to exist. Any other reference to a nonexistent array element shall automatically create it.

Comparisons (with the '<' , "<=" , "!=" , "==" , '>' , and ">=" operators) shall be made numerically if both operands are numeric, if one is numeric and the other has a string value that is a numeric string, or if one is numeric and the other has the uninitialized value. Otherwise, operands shall be converted to strings as required and a string comparison shall be made using the locale-specific collation sequence. The value of the comparison expression shall be 1 if the relation is true, or 0 if the relation is false.

Variables and Special Variables

Variables can be used in an awk program by referencing them. With the exception of function parameters (see User-Defined Functions ), they are not explicitly declared. Function parameter names shall be local to the function; all other variable names shall be global. The same name shall not be used as both a function parameter name and as the name of a function or a special awk variable. The same name shall not be used both as a variable name with global scope and as the name of a function. The same name shall not be used within the same scope both as a scalar variable and as an array. Uninitialized variables, including scalar variables, array elements, and field variables, shall have an uninitialized value. An uninitialized value shall have both a numeric value of zero and a string value of the empty string. Evaluation of variables with an uninitialized value, to either string or numeric, shall be determined by the context in which they are used.

Field variables shall be designated by a '$' followed by a number or numerical expression. The effect of the field number expression evaluating to anything other than a non-negative integer is unspecified; uninitialized variables or string values need not be converted to numeric values in this context. New field variables can be created by assigning a value to them. References to nonexistent fields (that is, fields after $NF), shall evaluate to the uninitialized value. Such references shall not create new fields. However, assigning to a nonexistent field (for example, $(NF+2)=5) shall increase the value of NF; create any intervening fields with the uninitialized value; and cause the value of $0 to be recomputed, with the fields being separated by the value of OFS. Each field variable shall have a string value or an uninitialized value when created. Field variables shall have the uninitialized value when created from $0 using FS and the variable does not contain any characters. If appropriate, the field variable shall be considered a numeric string (see Expressions in awk ).

Implementations shall support the following other special variables that are set by awk:

ARGC
The number of elements in the ARGV array.
ARGV
An array of command line arguments, excluding options and the program argument, numbered from zero to ARGC-1.

The arguments in ARGV can be modified or added to; ARGC can be altered. As each input file ends, awk shall treat the next non-null element of ARGV, up to the current value of ARGC-1, inclusive, as the name of the next input file. Thus, setting an element of ARGV to null means that it shall not be treated as an input file. The name '-' indicates the standard input. If an argument matches the format of an assignment operand, this argument shall be treated as an assignment rather than a file argument.

CONVFMT
The printf format for converting numbers to strings (except for output statements, where OFMT is used); "%.6g" by default.
ENVIRON
An array representing the value of the environment, as described in the exec functions defined in the System Interfaces volume of IEEE Std 1003.1-2001. The indices of the array shall be strings consisting of the names of the environment variables, and the value of each array element shall be a string consisting of the value of that variable. If appropriate, the environment variable shall be considered a numeric string (see Expressions in awk ); the array element shall also have its numeric value.

In all cases where the behavior of awk is affected by environment variables (including the environment of any commands that awk executes via the system function or via pipeline redirections with the print statement, the printf statement, or the getline function), the environment used shall be the environment at the time awk began executing; it is implementation-defined whether any modification of ENVIRON affects this environment.

FILENAME
A pathname of the current input file. Inside a BEGIN action the value is undefined. Inside an END action the value shall be the name of the last input file processed.
FNR
The ordinal number of the current record in the current file. Inside a BEGIN action the value shall be zero. Inside an END action the value shall be the number of the last record processed in the last file processed.
FS
Input field separator regular expression; a <space> by default.
NF
The number of fields in the current record. Inside a BEGIN action, the use of NF is undefined unless a getline function without a var argument is executed previously. Inside an END action, NF shall retain the value it had for the last record read, unless a subsequent, redirected, getline function without a var argument is performed prior to entering the END action.
NR
The ordinal number of the current record from the start of input. Inside a BEGIN action the value shall be zero. Inside an END action the value shall be the number of the last record processed.
OFMT
The printf format for converting numbers to strings in output statements (see Output Statements ); "%.6g" by default. The result of the conversion is unspecified if the value of OFMT is not a floating-point format specification.
OFS
The print statement output field separation; <space> by default.
ORS
The print statement output record separator; a <newline> by default.
RLENGTH
The length of the string matched by the match function.
RS
The first character of the string value of RS shall be the input record separator; a <newline> by default. If RS contains more than one character, the results are unspecified. If RS is null, then records are separated by sequences consisting of a <newline> plus one or more blank lines, leading or trailing blank lines shall not result in empty records at the beginning or end of the input, and a <newline> shall always be a field separator, no matter what the value of FS is.
RSTART
The starting position of the string matched by the match function, numbering from 1. This shall always be equivalent to the return value of the match function.
SUBSEP
The subscript separator string for multi-dimensional arrays; the default value is implementation-defined.

Regular Expressions

The awk utility shall make use of the extended regular expression notation (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.4, Extended Regular Expressions) except that it shall allow the use of C-language conventions for escaping special characters within the EREs, as specified in the table in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ) and the following table; these escape sequences shall be recognized both inside and outside bracket expressions. Note that records need not be separated by <newline>s and string constants can contain <newline>s, so even the "\n" sequence is valid in awk EREs. Using a slash character within an ERE requires the escaping shown in the following table.

Table: Escape Sequences in awk
Escape |  |
Sequence | Description | Meaning
\" | Backslash quotation-mark | Quotation-mark character
\/ | Backslash slash | Slash character
\ddd | A backslash character followed by the longest sequence of one, two, or three octal-digit characters (01234567). If all of the digits are 0 (that is, representation of the NUL character), the behavior is undefined. | The character whose encoding is represented by the one, two, or three-digit octal integer. Multi-byte characters require multiple, concatenated escape sequences of this type, including the leading '\' for each byte.
\c | A backslash character followed by any character not described in this table or in the table in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ). | Undefined

A regular expression can be matched against a specific field or string by using one of the two regular expression matching operators, '~' and "!~" . These operators shall interpret their right-hand operand as a regular expression and their left-hand operand as a string. If the regular expression matches the string, the '~' expression shall evaluate to a value of 1, and the "!~" expression shall evaluate to a value of 0. (The regular expression matching operation is as defined by the term matched in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.1, Regular Expression Definitions, where a match occurs on any part of the string unless the regular expression is limited with the circumflex or dollar sign special characters.) If the regular expression does not match the string, the '~' expression shall evaluate to a value of 0, and the "!~" expression shall evaluate to a value of 1. If the right-hand operand is any expression other than the lexical token ERE, the string value of the expression shall be interpreted as an extended regular expression, including the escape conventions described above. Note that these same escape conventions shall also be applied in determining the value of a string literal (the lexical token STRING), and thus shall be applied a second time when a string literal is used in this context.

When an ERE token appears as an expression in any context other than as the right-hand of the '~' or "!~" operator or as one of the built-in function arguments described below, the value of the resulting expression shall be the equivalent of:

$0 ~ /ere/

The ere argument to the gsub, match, sub functions, and the fs argument to the split function (see String Functions ) shall be interpreted as extended regular expressions. These can be either ERE tokens or arbitrary expressions, and shall be interpreted in the same manner as the right-hand side of the '~' or "!~" operator.

An extended regular expression can be used to separate fields by using the -F ERE option or by assigning a string containing the expression to the built-in variable FS. The default value of the FS variable shall be a single <space>. The following describes FS behavior:

1.
If FS is a null string, the behavior is unspecified.

2.
If FS is a single character:
a.
If FS is <space>, skip leading and trailing <blank>s; fields shall be delimited by sets of one or more <blank>s.

b.
Otherwise, if FS is any other character c, fields shall be delimited by each single occurrence of c.

3.
Otherwise, the string value of FS shall be considered to be an extended regular expression. Each occurrence of a sequence matching the extended regular expression shall delimit fields.

Except for the '~' and "!~" operators, and in the gsub, match, split, and sub built-in functions, ERE matching shall be based on input records; that is, record separator characters (the first character of the value of the variable RS, <newline> by default) cannot be embedded in the expression, and no expression shall match the record separator character. If the record separator is not <newline>, <newline>s embedded in the expression can be matched. For the '~' and "!~" operators, and in those four built-in functions, ERE matching shall be based on text strings; that is, any character (including <newline> and the record separator) can be embedded in the pattern, and an appropriate pattern shall match any character. However, in all awk ERE matching, the use of one or more NUL characters in the pattern, input record, or text string produces undefined results.

Patterns

A pattern is any valid expression, a range specified by two expressions separated by a comma, or one of the two special patterns BEGIN or END.

Special Patterns

The awk utility shall recognize two special patterns, BEGIN and END. Each BEGIN pattern shall be matched once and its associated action executed before the first record of input is read (except possibly by use of the getline function-see Input/Output and General Functions - in a prior BEGIN action) and before command line assignment is done. Each END pattern shall be matched once and its associated action executed after the last record of input has been read. These two patterns shall have associated actions.

BEGIN and END shall not combine with other patterns. Multiple BEGIN and END patterns shall be allowed. The actions associated with the BEGIN patterns shall be executed in the order specified in the program, as are the END actions. An END pattern can precede a BEGIN pattern in a program.

If an awk program consists of only actions with the pattern BEGIN, and the BEGIN action contains no getline function, awk shall exit without reading its input when the last statement in the last BEGIN action is executed. If an awk program consists of only actions with the pattern END or only actions with the patterns BEGIN and END, the input shall be read before the statements in the END actions are executed.

Expression Patterns

An expression pattern shall be evaluated as if it were an expression in a Boolean context. If the result is true, the pattern shall be considered to match, and the associated action (if any) shall be executed. If the result is false, the action shall not be executed.

Pattern Ranges

A pattern range consists of two expressions separated by a comma; in this case, the action shall be performed for all records between a match of the first expression and the following match of the second expression, inclusive. At this point, the pattern range can be repeated starting at input records subsequent to the end of the matched range.

Actions

An action is a sequence of statements as shown in the grammar in Grammar . Any single statement can be replaced by a statement list enclosed in braces. The application shall ensure that statements in a statement list are separated by <newline>s or semicolons. Statements in a statement list shall be executed sequentially in the order that they appear.

The expression acting as the conditional in an if statement shall be evaluated and if it is non-zero or non-null, the following statement shall be executed; otherwise, if else is present, the statement following the else shall be executed.

The if, while, do... while, for, break, and continue statements are based on the ISO C standard (see Concepts Derived from the ISO C Standard ), except that the Boolean expressions shall be treated as described in Expressions in awk , and except in the case of:

for (variable in array)

which shall iterate, assigning each index of array to variable in an unspecified order. The results of adding new elements to array within such a for loop are undefined. If a break or continue statement occurs outside of a loop, the behavior is undefined.

The delete statement shall remove an individual array element. Thus, the following code deletes an entire array:

for (index in array)
    delete array[index]

The next statement shall cause all further processing of the current input record to be abandoned. The behavior is undefined if a next statement appears or is invoked in a BEGIN or END action.

The exit statement shall invoke all END actions in the order in which they occur in the program source and then terminate the program without reading further input. An exit statement inside an END action shall terminate the program without further execution of END actions. If an expression is specified in an exit statement, its numeric value shall be the exit status of awk, unless subsequent errors are encountered or a subsequent exit statement with an expression is executed.

Output Statements

Both print and printf statements shall write to standard output by default. The output shall be written to the location specified by output_redirection if one is supplied, as follows:

> expression>> expression| expression

In all cases, the expression shall be evaluated to produce a string that is used as a pathname into which to write (for '>' or ">>" ) or as a command to be executed (for '|' ). Using the first two forms, if the file of that name is not currently open, it shall be opened, creating it if necessary and using the first form, truncating the file. The output then shall be appended to the file. As long as the file remains open, subsequent calls in which expression evaluates to the same string value shall simply append output to the file. The file remains open until the close function (see Input/Output and General Functions ) is called with an expression that evaluates to the same string value.

The third form shall write output onto a stream piped to the input of a command. The stream shall be created if no stream is currently open with the value of expression as its command name. The stream created shall be equivalent to one created by a call to the popen() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 with the value of expression as the command argument and a value of w as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall write output to the existing stream. The stream shall remain open until the close function (see Input/Output and General Functions ) is called with an expression that evaluates to the same string value. At that time, the stream shall be closed as if by a call to the pclose() function defined in the System Interfaces volume of IEEE Std 1003.1-2001.

As described in detail by the grammar in Grammar , these output statements shall take a comma-separated list of expressions referred to in the grammar by the non-terminal symbols expr_list, print_expr_list, or print_expr_list_opt. This list is referred to here as the expression list, and each member is referred to as an expression argument.

The print statement shall write the value of each expression argument onto the indicated output stream separated by the current output field separator (see variable OFS above), and terminated by the output record separator (see variable ORS above). All expression arguments shall be taken as strings, being converted if necessary; this conversion shall be as described in Expressions in awk , with the exception that the printf format in OFMT shall be used instead of the value in CONVFMT. An empty expression list shall stand for the whole input record ($0).

The printf statement shall produce output based on a notation similar to the File Format Notation used to describe file formats in this volume of IEEE Std 1003.1-2001 (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation). Output shall be produced as specified with the first expression argument as the string format and subsequent expression arguments as the strings arg1 to argn, inclusive, with the following exceptions:

1.
The format shall be an actual character string rather than a graphical representation. Therefore, it cannot contain empty character positions. The <space> in the format string, in any context other than a flag of a conversion specification, shall be treated as an ordinary character that is copied to the output.

2.
If the character set contains a ' ' character and that character appears in the format string, it shall be treated as an ordinary character that is copied to the output.

3.
The escape sequences beginning with a backslash character shall be treated as sequences of ordinary characters that are copied to the output. Note that these same sequences shall be interpreted lexically by awk when they appear in literal strings, but they shall not be treated specially by the printf statement.

4.
A field width or precision can be specified as the '*' character instead of a digit string. In this case the next argument from the expression list shall be fetched and its numeric value taken as the field width or precision.

5.
The implementation shall not precede or follow output from the d or u conversion specifier characters with <blank>s not specified by the format string.

6.
The implementation shall not precede output from the o conversion specifier character with leading zeros not specified by the format string.

7.
For the c conversion specifier character: if the argument has a numeric value, the character whose encoding is that value shall be output. If the value is zero or is not the encoding of any character in the character set, the behavior is undefined. If the argument does not have a numeric value, the first character of the string value shall be output; if the string does not contain any characters, the behavior is undefined.

8.
For each conversion specification that consumes an argument, the next expression argument shall be evaluated. With the exception of the c conversion specifier character, the value shall be converted (according to the rules specified in Expressions in awk ) to the appropriate type for the conversion specification.

9.
If there are insufficient expression arguments to satisfy all the conversion specifications in the format string, the behavior is undefined.

10.
If any character sequence in the format string begins with a '%' character, but does not form a valid conversion specification, the behavior is unspecified.

Both print and printf can output at least {LINE_MAX} bytes.

Functions

The awk language has a variety of built-in functions: arithmetic, string, input/output, and general.

Arithmetic Functions

The arithmetic functions, except for int, shall be based on the ISO C standard (see Concepts Derived from the ISO C Standard ). The behavior is undefined in cases where the ISO C standard specifies that an error be returned or that the behavior is undefined. Although the grammar (see Grammar ) permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the "[]" brackets), such use is undefined.

atan2(y,x)
Return arctangent of y/x in radians in the range [-pi,pi].
cos(x)
Return cosine of x, where x is in radians.
sin(x)
Return sine of x, where x is in radians.
exp(x)
Return the exponential function of x.
log(x)
Return the natural logarithm of x.
sqrt(x)
Return the square root of x.
int(x)
Return the argument truncated to an integer. Truncation shall be toward 0 when x>0.
rand()
Return a random number n, such that 0<=n<1.
srand([expr])
Set the seed value for rand to expr or use the time of day if expr is omitted. The previous seed value shall be returned.

String Functions

The string functions in the following list shall be supported. Although the grammar (see Grammar ) permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the "[]" brackets), such use is undefined.

gsub(ere, repl[, in])
Behave like sub (see below), except that it shall replace all occurrences of the regular expression (like the ed utility global substitute) in $0 or in the in argument, when specified.
index(s, t)
Return the position, in characters, numbering from 1, in string s where string t first occurs, or zero if it does not occur at all.
length[([s])]
Return the length, in characters, of its argument taken as a string, or of the whole record, $0, if there is no argument.
match(s, ere)
Return the position, in characters, numbering from 1, in string s where the extended regular expression ere occurs, or zero if it does not occur at all. RSTART shall be set to the starting position (which is the same as the returned value), zero if no match is found; RLENGTH shall be set to the length of the matched string, -1 if no match is found.
split(s, a[, fs ])
Split the string s into array elements a[1], a[2], ..., a[n], and return n. All elements of the array shall be deleted before the split is performed. The separation shall be done with the ERE fs or with the field separator FS if fs is not given. Each array element shall have a string value when created and, if appropriate, the array element shall be considered a numeric string (see Expressions in awk ). The effect of a null string as the value of fs is unspecified.
sprintf(fmt, expr, expr, ...)
Format the expressions according to the printf format given by fmt and return the resulting string.
sub(ere, repl[, in ])
Substitute the string repl in place of the first instance of the extended regular expression ERE in string in and return the number of substitutions. An ampersand ( '&' ) appearing in the string repl shall be replaced by the string from in that matches the ERE. An ampersand preceded with a backslash ( '\' ) shall be interpreted as the literal ampersand character. An occurrence of two consecutive backslashes shall be interpreted as just a single literal backslash character. Any other occurrence of a backslash (for example, preceding any other character) shall be treated as a literal backslash character. Note that if repl is a string literal (the lexical token STRING; see Grammar ), the handling of the ampersand character occurs after any lexical processing, including any lexical backslash escape sequence processing. If in is specified and it is not an lvalue (see Expressions in awk ), the behavior is undefined. If in is omitted, awk shall use the current record ($0) in its place.
substr(s, m[, n ])
Return the at most n-character substring of s that begins at position m, numbering from 1. If n is omitted, or if n specifies more characters than are left in the string, the length of the substring shall be limited by the length of the string s.
tolower(s)
Return a string based on the string s. Each character in s that is an uppercase letter specified to have a tolower mapping by the LC_CTYPE category of the current locale shall be replaced in the returned string by the lowercase letter specified by the mapping. Other characters in s shall be unchanged in the returned string.
toupper(s)
Return a string based on the string s. Each character in s that is a lowercase letter specified to have a toupper mapping by the LC_CTYPE category of the current locale is replaced in the returned string by the uppercase letter specified by the mapping. Other characters in s are unchanged in the returned string.

All of the preceding functions that take ERE as a parameter expect a pattern or a string valued expression that is a regular expression as defined in Regular Expressions .

Input/Output and General Functions

The input/output and general functions are:

close(expression)
Close the file or pipe opened by a print or printf statement or a call to getline with the same string-valued expression. The limit on the number of open expression arguments is implementation-defined. If the close was successful, the function shall return zero; otherwise, it shall return non-zero.
expression | getline [var]
Read a record of input from a stream piped from the output of a command. The stream shall be created if no stream is currently open with the value of expression as its command name. The stream created shall be equivalent to one created by a call to the popen() function with the value of expression as the command argument and a value of r as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall read subsequent records from the stream. The stream shall remain open until the close function is called with an expression that evaluates to the same string value. At that time, the stream shall be closed as if by a call to the pclose() function. If var is omitted, $0 and NF shall be set; otherwise, var shall be set and, if appropriate, it shall be considered a numeric string (see Expressions in awk ).

The getline operator can form ambiguous constructs when there are unparenthesized operators (including concatenate) to the left of the '|' (to the beginning of the expression containing getline). In the context of the '$' operator, '|' shall behave as if it had a lower precedence than '$' . The result of evaluating other operators is unspecified, and conforming applications shall parenthesize properly all such usages.

getline
Set $0 to the next input record from the current input file. This form of getline shall set the NF, NR, and FNR variables.
getline var
Set variable var to the next input record from the current input file and, if appropriate, var shall be considered a numeric string (see Expressions in awk ). This form of getline shall set the FNR and NR variables.
getline [var] < expression
Read the next record of input from a named file. The expression shall be evaluated to produce a string that is used as a pathname. If the file of that name is not currently open, it shall be opened. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall read subsequent records from the file. The file shall remain open until the close function is called with an expression that evaluates to the same string value. If var is omitted, $0 and NF shall be set; otherwise, var shall be set and, if appropriate, it shall be considered a numeric string (see Expressions in awk ).

The getline operator can form ambiguous constructs when there are unparenthesized binary operators (including concatenate) to the right of the '<' (up to the end of the expression containing the getline). The result of evaluating such a construct is unspecified, and conforming applications shall parenthesize properly all such usages.

system(expression)
Execute the command given by expression in a manner equivalent to the system() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 and return the exit status of the command.

All forms of getline shall return 1 for successful input, zero for end-of-file, and -1 for an error.

Where strings are used as the name of a file or pipeline, the application shall ensure that the strings are textually identical. The terminology "same string value" implies that "equivalent strings", even those that differ only by <space>s, represent different files.

User-Defined Functions

The awk language also provides user-defined functions. Such functions can be defined as:

function name([parameter, ...]) { statements }

A function can be referred to anywhere in an awk program; in particular, its use can precede its definition. The scope of a function is global.

Function parameters, if present, can be either scalars or arrays; the behavior is undefined if an array name is passed as a parameter that the function uses as a scalar, or if a scalar expression is passed as a parameter that the function uses as an array. Function parameters shall be passed by value if scalar and by reference if array name.

The number of parameters in the function definition need not match the number of parameters in the function call. Excess formal parameters can be used as local variables. If fewer arguments are supplied in a function call than are in the function definition, the extra parameters that are used in the function body as scalars shall evaluate to the uninitialized value until they are otherwise initialized, and the extra parameters that are used in the function body as arrays shall be treated as uninitialized arrays where each element evaluates to the uninitialized value until otherwise initialized.

When invoking a function, no white space can be placed between the function name and the opening parenthesis. Function calls can be nested and recursive calls can be made upon functions. Upon return from any nested or recursive function call, the values of all of the calling function's parameters shall be unchanged, except for array parameters passed by reference. The return statement can be used to return a value. If a return statement appears outside of a function definition, the behavior is undefined.

In the function definition, <newline>s shall be optional before the opening brace and after the closing brace. Function definitions can appear anywhere in the program where a pattern-action pair is allowed.

Grammar

The grammar in this section and the lexical conventions in the following section shall together describe the syntax for awk programs. The general conventions for this style of grammar are described in Grammar Conventions . A valid program can be represented as the non-terminal symbol program in the grammar. This formal syntax shall take precedence over the preceding text syntax description.

%token NAME NUMBER STRING ERE
%token FUNC_NAME   /* Name followed by '(' without white space. */

/* Keywords  */
%token       Begin   End
/*          'BEGIN' 'END'                            */

%token       Break   Continue   Delete   Do   Else
/*          'break' 'continue' 'delete' 'do' 'else'  */

%token       Exit   For   Function   If   In
/*          'exit' 'for' 'function' 'if' 'in'        */

%token       Next   Print   Printf   Return   While
/*          'next' 'print' 'printf' 'return' 'while' */

/* Reserved function names */
%token BUILTIN_FUNC_NAME
            /* One token for the following:
             * atan2 cos sin exp log sqrt int rand srand
             * gsub index length match split sprintf sub
             * substr tolower toupper close system
             */
%token GETLINE
            /* Syntactically different from other built-ins. */

/* Two-character tokens. */
%token ADD_ASSIGN SUB_ASSIGN MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN POW_ASSIGN
/*     '+='       '-='       '*='       '/='       '%='       '^=' */

%token OR   AND  NO_MATCH   EQ   LE   GE   NE   INCR  DECR  APPEND
/*     '||' '&&' '!~' '==' '<=' '>=' '!=' '++'  '--'  '>>'   */

/* One-character tokens. */
%token '{' '}' '(' ')' '[' ']' ',' ';' NEWLINE
%token '+' '-' '*' '%' '^' '!' '>' '<' '|' '?' ':' '~' '$' '='

%start program
%%

program          : item_list
                 | actionless_item_list
                 ;

item_list        : newline_opt
                 | actionless_item_list item terminator
                 | item_list            item terminator
                 | item_list          action terminator
                 ;

actionless_item_list : item_list            pattern terminator
                 | actionless_item_list pattern terminator
                 ;

item             : pattern action
                 | Function NAME      '(' param_list_opt ')'
                       newline_opt action
                 | Function FUNC_NAME '(' param_list_opt ')'
                       newline_opt action
                 ;

param_list_opt   : /* empty */
                 | param_list
                 ;

param_list       : NAME
                 | param_list ',' NAME
                 ;

pattern          : Begin
                 | End
                 | expr
                 | expr ',' newline_opt expr
                 ;

action           : '{' newline_opt                             '}'
                 | '{' newline_opt terminated_statement_list   '}'
                 | '{' newline_opt unterminated_statement_list '}'
                 ;

terminator       : terminator ';'
                 | terminator NEWLINE
                 |            ';'
                 |            NEWLINE
                 ;

terminated_statement_list : terminated_statement
                 | terminated_statement_list terminated_statement
                 ;

unterminated_statement_list : unterminated_statement
                 | terminated_statement_list unterminated_statement
                 ;

terminated_statement : action newline_opt
                 | If '(' expr ')' newline_opt terminated_statement
                 | If '(' expr ')' newline_opt terminated_statement
                       Else newline_opt terminated_statement
                 | While '(' expr ')' newline_opt terminated_statement
                 | For '(' simple_statement_opt ';'
                      expr_opt ';' simple_statement_opt ')' newline_opt
                      terminated_statement
                 | For '(' NAME In NAME ')' newline_opt
                      terminated_statement
                 | ';' newline_opt
                 | terminatable_statement NEWLINE newline_opt
                 | terminatable_statement ';'     newline_opt
                 ;

unterminated_statement : terminatable_statement
                 | If '(' expr ')' newline_opt unterminated_statement
                 | If '(' expr ')' newline_opt terminated_statement
                      Else newline_opt unterminated_statement
                 | While '(' expr ')' newline_opt unterminated_statement
                 | For '(' simple_statement_opt ';'
                  expr_opt ';' simple_statement_opt ')' newline_opt
                      unterminated_statement
                 | For '(' NAME In NAME ')' newline_opt
                      unterminated_statement
                 ;

terminatable_statement : simple_statement
                 | Break
                 | Continue
                 | Next
                 | Exit expr_opt
                 | Return expr_opt
                 | Do newline_opt terminated_statement While '(' expr ')'
                 ;

simple_statement_opt : /* empty */
                 | simple_statement
                 ;

simple_statement : Delete NAME '[' expr_list ']'
                 | expr
                 | print_statement
                 ;

print_statement  : simple_print_statement
                 | simple_print_statement output_redirection
                 ;

simple_print_statement : Print  print_expr_list_opt
                 | Print  '(' multiple_expr_list ')'
                 | Printf print_expr_list
                 | Printf '(' multiple_expr_list ')'
                 ;

output_redirection : '>'    expr
                 | APPEND expr
                 | '|'    expr
                 ;

expr_list_opt    : /* empty */
                 | expr_list
                 ;

expr_list        : expr
                 | multiple_expr_list
                 ;

multiple_expr_list : expr ',' newline_opt expr
                 | multiple_expr_list ',' newline_opt expr
                 ;

expr_opt         : /* empty */
                 | expr
                 ;

expr             : unary_expr
                 | non_unary_expr
                 ;

unary_expr       : '+' expr
                 | '-' expr
                 | unary_expr '^'      expr
                 | unary_expr '*'      expr
                 | unary_expr '/'      expr
                 | unary_expr '%'      expr
                 | unary_expr '+'      expr
                 | unary_expr '-'      expr
                 | unary_expr          non_unary_expr
                 | unary_expr '<'      expr
                 | unary_expr LE       expr
                 | unary_expr NE       expr
                 | unary_expr EQ       expr
                 | unary_expr '>'      expr
                 | unary_expr GE       expr
                 | unary_expr '~'      expr
                 | unary_expr NO_MATCH expr
                 | unary_expr In NAME
                 | unary_expr AND newline_opt expr
                 | unary_expr OR  newline_opt expr
                 | unary_expr '?' expr ':' expr
                 | unary_input_function
                 ;

non_unary_expr   : '(' expr ')'
                 | '!' expr
                 | non_unary_expr '^'      expr
                 | non_unary_expr '*'      expr
                 | non_unary_expr '/'      expr
                 | non_unary_expr '%'      expr
                 | non_unary_expr '+'      expr
                 | non_unary_expr '-'      expr
                 | non_unary_expr          non_unary_expr
                 | non_unary_expr '<'      expr
                 | non_unary_expr LE       expr
                 | non_unary_expr NE       expr
                 | non_unary_expr EQ       expr
                 | non_unary_expr '>'      expr
                 | non_unary_expr GE       expr
                 | non_unary_expr '~'      expr
                 | non_unary_expr NO_MATCH expr
                 | non_unary_expr In NAME
                 | '(' multiple_expr_list ')' In NAME
                 | non_unary_expr AND newline_opt expr
                 | non_unary_expr OR  newline_opt expr
                 | non_unary_expr '?' expr ':' expr
                 | NUMBER
                 | STRING
                 | lvalue
                 | ERE
                 | lvalue INCR
                 | lvalue DECR
                 | INCR lvalue
                 | DECR lvalue
                 | lvalue POW_ASSIGN expr
                 | lvalue MOD_ASSIGN expr
                 | lvalue MUL_ASSIGN expr
                 | lvalue DIV_ASSIGN expr
                 | lvalue ADD_ASSIGN expr
                 | lvalue SUB_ASSIGN expr
                 | lvalue '=' expr
                 | FUNC_NAME '(' expr_list_opt ')'
                      /* no white space allowed before '(' */
                 | BUILTIN_FUNC_NAME '(' expr_list_opt ')'
                 | BUILTIN_FUNC_NAME
                 | non_unary_input_function
                 ;

print_expr_list_opt : /* empty */
                 | print_expr_list
                 ;

print_expr_list  : print_expr
                 | print_expr_list ',' newline_opt print_expr
                 ;

print_expr       : unary_print_expr
                 | non_unary_print_expr
                 ;

unary_print_expr : '+' print_expr
                 | '-' print_expr
                 | unary_print_expr '^'      print_expr
                 | unary_print_expr '*'      print_expr
                 | unary_print_expr '/'      print_expr
                 | unary_print_expr '%'      print_expr
                 | unary_print_expr '+'      print_expr
                 | unary_print_expr '-'      print_expr
                 | unary_print_expr          non_unary_print_expr
                 | unary_print_expr '~'      print_expr
                 | unary_print_expr NO_MATCH print_expr
                 | unary_print_expr In NAME
                 | unary_print_expr AND newline_opt print_expr
                 | unary_print_expr OR  newline_opt print_expr
                 | unary_print_expr '?' print_expr ':' print_expr
                 ;

non_unary_print_expr : '(' expr ')'
                 | '!' print_expr
                 | non_unary_print_expr '^'      print_expr
                 | non_unary_print_expr '*'      print_expr
                 | non_unary_print_expr '/'      print_expr
                 | non_unary_print_expr '%'      print_expr
                 | non_unary_print_expr '+'      print_expr
                 | non_unary_print_expr '-'      print_expr
                 | non_unary_print_expr          non_unary_print_expr
                 | non_unary_print_expr '~'      print_expr
                 | non_unary_print_expr NO_MATCH print_expr
                 | non_unary_print_expr In NAME
                 | '(' multiple_expr_list ')' In NAME
                 | non_unary_print_expr AND newline_opt print_expr
                 | non_unary_print_expr OR  newline_opt print_expr
                 | non_unary_print_expr '?' print_expr ':' print_expr
                 | NUMBER
                 | STRING
                 | lvalue
                 | ERE
                 | lvalue INCR
                 | lvalue DECR
                 | INCR lvalue
                 | DECR lvalue
                 | lvalue POW_ASSIGN print_expr
                 | lvalue MOD_ASSIGN print_expr
                 | lvalue MUL_ASSIGN print_expr
                 | lvalue DIV_ASSIGN print_expr
                 | lvalue ADD_ASSIGN print_expr
                 | lvalue SUB_ASSIGN print_expr
                 | lvalue '=' print_expr
                 | FUNC_NAME '(' expr_list_opt ')'
                     /* no white space allowed before '(' */
                 | BUILTIN_FUNC_NAME '(' expr_list_opt ')'
                 | BUILTIN_FUNC_NAME
                 ;

lvalue           : NAME
                 | NAME '[' expr_list ']'
                 | '$' expr
                 ;

non_unary_input_function : simple_get
                 | simple_get '<' expr
                 | non_unary_expr '|' simple_get
                 ;

unary_input_function : unary_expr '|' simple_get
                 ;

simple_get       : GETLINE
                 | GETLINE lvalue
                 ;

newline_opt      : /* empty */
                 | newline_opt NEWLINE
                 ;

This grammar has several ambiguities that shall be resolved as follows:

*
Operator precedence and associativity shall be as described in Expressions in Decreasing Precedence in awk .

*
In case of ambiguity, an else shall be associated with the most immediately preceding if that would satisfy the grammar.

*
In some contexts, a slash ( '/' ) that is used to surround an ERE could also be the division operator. This shall be resolved in such a way that wherever the division operator could appear, a slash is assumed to be the division operator. (There is no unary division operator.)

One convention that might not be obvious from the formal grammar is where <newline>s are acceptable. There are several obvious placements such as terminating a statement, and a backslash can be used to escape <newline>s between any lexical tokens. In addition, <newline>s without backslashes can follow a comma, an open brace, logical AND operator ( "&&" ), logical OR operator ( "||" ), the do keyword, the else keyword, and the closing parenthesis of an if, for, or while statement. For example:

{ print  $1,
         $2 }

Lexical Conventions

The lexical conventions for awk programs, with respect to the preceding grammar, shall be as follows:

1.
Except as noted, awk shall recognize the longest possible token or delimiter beginning at a given point.

2.
A comment shall consist of any characters beginning with the number sign character and terminated by, but excluding the next occurrence of, a <newline>. Comments shall have no effect, except to delimit lexical tokens.

3.
The <newline> shall be recognized as the token NEWLINE.

4.
A backslash character immediately followed by a <newline> shall have no effect.

5.
The token STRING shall represent a string constant. A string constant shall begin with the character ' .' Within a string constant, a backslash character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ). In addition, the escape sequences in Expressions in Decreasing Precedence in awk shall be recognized. A <newline> shall not occur within a string constant. A string constant shall be terminated by the first unescaped occurrence of the character '' after the one that begins the string constant. The value of the string shall be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting '' characters.

6.
The token ERE represents an extended regular expression constant. An ERE constant shall begin with the slash character. Within an ERE constant, a backslash character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation. In addition, the escape sequences in Expressions in Decreasing Precedence in awk shall be recognized. The application shall ensure that a <newline> does not occur within an ERE constant. An ERE constant shall be terminated by the first unescaped occurrence of the slash character after the one that begins the ERE constant. The extended regular expression represented by the ERE constant shall be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting slash characters.

7.
A <blank> shall have no effect, except to delimit lexical tokens or within STRING or ERE tokens.

8.
The token NUMBER shall represent a numeric constant. Its form and numeric value shall be equivalent to either of the tokens floating-constant or integer-constant as specified by the ISO C standard, with the following exceptions:
a.
An integer constant cannot begin with 0x or include the hexadecimal digits 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'A' , 'B' , 'C' , 'D' , 'E' , or 'F' .

b.
The value of an integer constant beginning with 0 shall be taken in decimal rather than octal.

c.
An integer constant cannot include a suffix ( 'u' , 'U' , 'l' , or 'L' ).

d.
A floating constant cannot include a suffix ( 'f' , 'F' , 'l' , or 'L' ).

If the value is too large or too small to be representable (see Concepts Derived from the ISO C Standard ), the behavior is undefined.

9.
A sequence of underscores, digits, and alphabetics from the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set), beginning with an underscore or alphabetic, shall be considered a word.

10.
The following words are keywords that shall be recognized as individual tokens; the name of the token is the same as the keyword:

BEGIN
break
continue

delete
do
else

END
exit
for

function
getline
if

in
next
print

printf
return
while

11.
The following words are names of built-in functions and shall be recognized as the token BUILTIN_FUNC_NAME:

atan2
close
cos
exp

gsub
index
int
length

log
match
rand
sin

split
sprintf
sqrt
srand

sub
substr
system
tolower

toupper

The above-listed keywords and names of built-in functions are considered reserved words.

12.
The token NAME shall consist of a word that is not a keyword or a name of a built-in function and is not followed immediately (without any delimiters) by the '(' character.

13.
The token FUNC_NAME shall consist of a word that is not a keyword or a name of a built-in function, followed immediately (without any delimiters) by the '(' character. The '(' character shall not be included as part of the token.

14.
The following two-character sequences shall be recognized as the named tokens:
Token Name Sequence Token Name Sequence
ADD_ASSIGN += NO_MATCH !~
SUB_ASSIGN -= EQ ==
MUL_ASSIGN *= LE <=
DIV_ASSIGN /= GE >=
MOD_ASSIGN %= NE !=
POW_ASSIGN ^= INCR ++
OR || DECR --
AND && APPEND >>

15.
The following single characters shall be recognized as tokens whose names are the character:

<newline> { } ( ) [ ] , ; + - * % ^ ! > < | ? : ~ $ =

There is a lexical ambiguity between the token ERE and the tokens '/' and DIV_ASSIGN. When an input sequence begins with a slash character in any syntactic context where the token '/' or DIV_ASSIGN could appear as the next token in a valid program, the longer of those two tokens that can be recognized shall be recognized. In any other syntactic context where the token ERE could appear as the next token in a valid program, the token ERE shall be recognized.

EXIT STATUS

The following exit values shall be returned:

0
All input files were processed successfully.
>0
An error occurred.

The exit status can be altered within the program by using an exit expression.

CONSEQUENCES OF ERRORS

If any file operand is specified and the named file cannot be accessed, awk shall write a diagnostic message to standard error and terminate without any further action.

If the program specified by either the program operand or a progfile operand is not a valid awk program (as specified in the EXTENDED DESCRIPTION section), the behavior is undefined.

The following sections are informative.

APPLICATION USAGE

The index, length, match, and substr functions should not be confused with similar functions in the ISO C standard; the awk versions deal with characters, while the ISO C standard deals with bytes.

Because the concatenation operation is represented by adjacent expressions rather than an explicit operator, it is often necessary to use parentheses to enforce the proper evaluation precedence.

EXAMPLES

The awk program specified in the command line is most easily specified within single-quotes (for example, program') for applications using sh, because awk programs commonly contain characters that are special to the shell, including double-quotes. In the cases where an awk program contains single-quote characters, it is usually easiest to specify most of the program as strings within single-quotes concatenated by the shell with quoted single-quote characters. For example:

awk '/'\''/ { print "quote:", $0 }'

prints all lines from the standard input containing a single-quote character, prefixed with quote:.

The following are examples of simple awk programs:

1.
Write to the standard output all input lines for which field 3 is greater than 5:

$3 > 5

2.
Write every tenth line:

(NR % 10) == 0

3.
Write any line with a substring matching the regular expression:

/(G|D)(2[0-9][[:alpha:]]*)/

4.
Print any line with a substring containing a 'G' or 'D' , followed by a sequence of digits and characters. This example uses character classes digit and alpha to match language-independent digit and alphabetic characters respectively:

/(G|D)([[:digit:][:alpha:]]*)/

5.
Write any line in which the second field matches the regular expression and the fourth field does not:

$2 ~ /xyz/ && $4 !~ /xyz/

6.
Write any line in which the second field contains a backslash:

$2 ~ /\\/

7.
Write any line in which the second field contains a backslash. Note that backslash escapes are interpreted twice; once in lexical processing of the string and once in processing the regular expression:

$2 ~ "\\\\"

8.
Write the second to the last and the last field in each line. Separate the fields by a colon:

{OFS=":";print $(NF-1), $NF}

9.
Write the line number and number of fields in each line. The three strings representing the line number, the colon, and the number of fields are concatenated and that string is written to standard output:

{print NR ":" NF}

10.
Write lines longer than 72 characters:

length($0) > 72

11.
Write the first two fields in opposite order separated by OFS:

{ print $2, $1 }

12.
Same, with input fields separated by a comma or <space>s and <tab>s, or both:

BEGIN { FS = ",[ \t]*|[ \t]+" }
      { print $2, $1 }

13.
Add up the first column, print sum, and average:

     {s += $1 }
END   {print "sum is ", s, " average is", s/NR}

14.
Write fields in reverse order, one per line (many lines out for each line in):

{ for (i = NF; i > 0; --i) print $i }

15.
Write all lines between occurrences of the strings start and stop:

/start/, /stop/

16.
Write all lines whose first field is different from the previous one:

$1 != prev { print; prev = $1 }

17.
Simulate echo:

BEGIN  {
        for (i = 1; i < ARGC; ++i)
        printf("%s%s", ARGV[i], i==ARGC-1?"\n":" ")
}

18.
Write the path prefixes contained in the PATH environment variable, one per line:

BEGIN  {
        n = split (ENVIRON["PATH"], path, ":")
        for (i = 1; i <= n; ++i)
        print path[i]
}

19.
If there is a file named input containing page headers of the form:

Page #

and a file named program that contains:

/Page/   { $2 = n++; }
         { print }

then the command line:

awk -f program n=5 input

prints the file input, filling in page numbers starting at 5.

RATIONALE

This description is based on the new awk, "nawk", (see the referenced The AWK Programming Language), which introduced a number of new features to the historical awk:

1.
New keywords: delete, do, function, return

2.
New built-in functions: atan2, close, cos, gsub, match, rand, sin, srand, sub, system

3.
New predefined variables: FNR, ARGC, ARGV, RSTART, RLENGTH, SUBSEP

4.
New expression operators: ?, :, ,, ^

5.
The FS variable and the third argument to split, now treated as extended regular expressions.

6.
The operator precedence, changed to more closely match the C language. Two examples of code that operate differently are:

while ( n /= 10 > 1) ...
if (!"wk" ~ /bwk/) ...

Several features have been added based on newer implementations of awk:

*
Multiple instances of -f progfile are permitted.

*
The new option -v assignment.

*
The new predefined variable ENVIRON.

*
New built-in functions toupper and tolower.

*
More formatting capabilities are added to printf to match the ISO C standard.

The overall awk syntax has always been based on the C language, with a few features from the shell command language and other sources. Because of this, it is not completely compatible with any other language, which has caused confusion for some users. It is not the intent of the standard developers to address such issues. A few relatively minor changes toward making the language more compatible with the ISO C standard were made; most of these changes are based on similar changes in recent implementations, as described above. There remain several C-language conventions that are not in awk. One of the notable ones is the comma operator, which is commonly used to specify multiple expressions in the C language for statement. Also, there are various places where awk is more restrictive than the C language regarding the type of expression that can be used in a given context. These limitations are due to the different features that the awk language does provide.

Regular expressions in awk have been extended somewhat from historical implementations to make them a pure superset of extended regular expressions, as defined by IEEE Std 1003.1-2001 (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.4, Extended Regular Expressions). The main extensions are internationalization features and interval expressions. Historical implementations of awk have long supported backslash escape sequences as an extension to extended regular expressions, and this extension has been retained despite inconsistency with other utilities. The number of escape sequences recognized in both extended regular expressions and strings has varied (generally increasing with time) among implementations. The set specified by IEEE Std 1003.1-2001 includes most sequences known to be supported by popular implementations and by the ISO C standard. One sequence that is not supported is hexadecimal value escapes beginning with '\x' . This would allow values expressed in more than 9 bits to be used within awk as in the ISO C standard. However, because this syntax has a non-deterministic length, it does not permit the subsequent character to be a hexadecimal digit. This limitation can be dealt with in the C language by the use of lexical string concatenation. In the awk language, concatenation could also be a solution for strings, but not for extended regular expressions (either lexical ERE tokens or strings used dynamically as regular expressions). Because of this limitation, the feature has not been added to IEEE Std 1003.1-2001.

When a string variable is used in a context where an extended regular expression normally appears (where the lexical token ERE is used in the grammar) the string does not contain the literal slashes.

Some versions of awk allow the form:

func name(args, ... ) { statements }

This has been deprecated by the authors of the language, who asked that it not be specified.

Historical implementations of awk produce an error if a next statement is executed in a BEGIN action, and cause awk to terminate if a next statement is executed in an END action. This behavior has not been documented, and it was not believed that it was necessary to standardize it.

The specification of conversions between string and numeric values is much more detailed than in the documentation of historical implementations or in the referenced The AWK Programming Language. Although most of the behavior is designed to be intuitive, the details are necessary to ensure compatible behavior from different implementations. This is especially important in relational expressions since the types of the operands determine whether a string or numeric comparison is performed. From the perspective of an application writer, it is usually sufficient to expect intuitive behavior and to force conversions (by adding zero or concatenating a null string) when the type of an expression does not obviously match what is needed. The intent has been to specify historical practice in almost all cases. The one exception is that, in historical implementations, variables and constants maintain both string and numeric values after their original value is converted by any use. This means that referencing a variable or constant can have unexpected side effects. For example, with historical implementations the following program:

{
    a = "+2"
    b = 2
    if (NR % 2)
        c = a + b
    if (a == b)
        print "numeric comparison"
    else
        print "string comparison"
}

would perform a numeric comparison (and output numeric comparison) for each odd-numbered line, but perform a string comparison (and output string comparison) for each even-numbered line. IEEE Std 1003.1-2001 ensures that comparisons will be numeric if necessary. With historical implementations, the following program:

BEGIN {
    OFMT = "%e"
    print 3.14
    OFMT = "%f"
    print 3.14
}

would output "3.140000e+00" twice, because in the second print statement the constant "3.14" would have a string value from the previous conversion. IEEE Std 1003.1-2001 requires that the output of the second print statement be "3.140000" . The behavior of historical implementations was seen as too unintuitive and unpredictable.

It was pointed out that with the rules contained in early drafts, the following script would print nothing:

BEGIN {
    y[1.5] = 1
    OFMT = "%e"
    print y[1.5]
}

Therefore, a new variable, CONVFMT, was introduced. The OFMT variable is now restricted to affecting output conversions of numbers to strings and CONVFMT is used for internal conversions, such as comparisons or array indexing. The default value is the same as that for OFMT, so unless a program changes CONVFMT (which no historical program would do), it will receive the historical behavior associated with internal string conversions.

The POSIX awk lexical and syntactic conventions are specified more formally than in other sources. Again the intent has been to specify historical practice. One convention that may not be obvious from the formal grammar as in other verbal descriptions is where <newline>s are acceptable. There are several obvious placements such as terminating a statement, and a backslash can be used to escape <newline>s between any lexical tokens. In addition, <newline>s without backslashes can follow a comma, an open brace, a logical AND operator ( "&&" ), a logical OR operator ( "||" ), the do keyword, the else keyword, and the closing parenthesis of an if, for, or while statement. For example:

{ print $1,
        $2 }

The requirement that awk add a trailing <newline> to the program argument text is to simplify the grammar, making it match a text file in form. There is no way for an application or test suite to determine whether a literal <newline> is added or whether awk simply acts as if it did.

IEEE Std 1003.1-2001 requires several changes from historical implementations in order to support internationalization. Probably the most subtle of these is the use of the decimal-point character, defined by the LC_NUMERIC category of the locale, in representations of floating-point numbers. This locale-specific character is used in recognizing numeric input, in converting between strings and numeric values, and in formatting output. However, regardless of locale, the period character (the decimal-point character of the POSIX locale) is the decimal-point character recognized in processing awk programs (including assignments in command line arguments). This is essentially the same convention as the one used in the ISO C standard. The difference is that the C language includes the setlocale() function, which permits an application to modify its locale. Because of this capability, a C application begins executing with its locale set to the C locale, and only executes in the environment-specified locale after an explicit call to setlocale(). However, adding such an elaborate new feature to the awk language was seen as inappropriate for IEEE Std 1003.1-2001. It is possible to execute an awk program explicitly in any desired locale by setting the environment in the shell.

The undefined behavior resulting from NULs in extended regular expressions allows future extensions for the GNU gawk program to process binary data.

The behavior in the case of invalid awk programs (including lexical, syntactic, and semantic errors) is undefined because it was considered overly limiting on implementations to specify. In most cases such errors can be expected to produce a diagnostic and a non-zero exit status. However, some implementations may choose to extend the language in ways that make use of certain invalid constructs. Other invalid constructs might be deemed worthy of a warning, but otherwise cause some reasonable behavior. Still other constructs may be very difficult to detect in some implementations. Also, different implementations might detect a given error during an initial parsing of the program (before reading any input files) while others might detect it when executing the program after reading some input. Implementors should be aware that diagnosing errors as early as possible and producing useful diagnostics can ease debugging of applications, and thus make an implementation more usable.

The unspecified behavior from using multi-character RS values is to allow possible future extensions based on extended regular expressions used for record separators. Historical implementations take the first character of the string and ignore the others.

Unspecified behavior when split( string, array, <null>) is used is to allow a proposed future extension that would split up a string into an array of individual characters.

In the context of the getline function, equally good arguments for different precedences of the | and < operators can be made. Historical practice has been that:

getline < "a" "b"

is parsed as:

( getline < "a" ) "b"

although many would argue that the intent was that the file ab should be read. However:

getline < "x" + 1

parses as:

getline < ( "x" + 1 )

Similar problems occur with the | version of getline, particularly in combination with $. For example:

$"echo hi" | getline

(This situation is particularly problematic when used in a print statement, where the |getline part might be a redirection of the print.)

Since in most cases such constructs are not (or at least should not) be used (because they have a natural ambiguity for which there is no conventional parsing), the meaning of these constructs has been made explicitly unspecified. (The effect is that a conforming application that runs into the problem must parenthesize to resolve the ambiguity.) There appeared to be few if any actual uses of such constructs.

Grammars can be written that would cause an error under these circumstances. Where backwards-compatibility is not a large consideration, implementors may wish to use such grammars.

Some historical implementations have allowed some built-in functions to be called without an argument list, the result being a default argument list chosen in some "reasonable" way. Use of length as a synonym for length($0) is the only one of these forms that is thought to be widely known or widely used; this particular form is documented in various places (for example, most historical awk reference pages, although not in the referenced The AWK Programming Language) as legitimate practice. With this exception, default argument lists have always been undocumented and vaguely defined, and it is not at all clear how (or if) they should be generalized to user-defined functions. They add no useful functionality and preclude possible future extensions that might need to name functions without calling them. Not standardizing them seems the simplest course. The standard developers considered that length merited special treatment, however, since it has been documented in the past and sees possibly substantial use in historical programs. Accordingly, this usage has been made legitimate, but Issue 5 removed the obsolescent marking for XSI-conforming implementations and many otherwise conforming applications depend on this feature.

In sub and gsub, if repl is a string literal (the lexical token STRING), then two consecutive backslash characters should be used in the string to ensure a single backslash will precede the ampersand when the resultant string is passed to the function. (For example, to specify one literal ampersand in the replacement string, use gsub( ERE, "\\&" ).)

Historically the only special character in the repl argument of sub and gsub string functions was the ampersand ( '&' ) character and preceding it with the backslash character was used to turn off its special meaning.

The description in the ISO POSIX-2:1993 standard introduced behavior such that the backslash character was another special character and it was unspecified whether there were any other special characters. This description introduced several portability problems, some of which are described below, and so it has been replaced with the more historical description. Some of the problems include:

*
Historically, to create the replacement string, a script could use gsub( ERE, "\\&" ), but with the ISO POSIX-2:1993 standard wording, it was necessary to use gsub( ERE, "\\\\&" ). Backslash characters are doubled here because all string literals are subject to lexical analysis, which would reduce each pair of backslash characters to a single backslash before being passed to gsub.

*
Since it was unspecified what the special characters were, for portable scripts to guarantee that characters are printed literally, each character had to be preceded with a backslash. (For example, a portable script had to use gsub( ERE, "\\h\\i" ) to produce a replacement string of "hi" .)

The description for comparisons in the ISO POSIX-2:1993 standard did not properly describe historical practice because of the way numeric strings are compared as numbers. The current rules cause the following code:

if (0 == "000")
    print "strange, but true"
else
    print "not true"

to do a numeric comparison, causing the if to succeed. It should be intuitively obvious that this is incorrect behavior, and indeed, no historical implementation of awk actually behaves this way.

To fix this problem, the definition of numeric string was enhanced to include only those values obtained from specific circumstances (mostly external sources) where it is not possible to determine unambiguously whether the value is intended to be a string or a numeric.

Variables that are assigned to a numeric string shall also be treated as a numeric string. (For example, the notion of a numeric string can be propagated across assignments.) In comparisons, all variables having the uninitialized value are to be treated as a numeric operand evaluating to the numeric value zero.

Uninitialized variables include all types of variables including scalars, array elements, and fields. The definition of an uninitialized value in Variables and Special Variables is necessary to describe the value placed on uninitialized variables and on fields that are valid (for example, < $NF) but have no characters in them and to describe how these variables are to be used in comparisons. A valid field, such as $1, that has no characters in it can be obtained from an input line of "\t\t" when FS= '\t' . Historically, the comparison ( $1<10) was done numerically after evaluating $1 to the value zero.

The phrase "... also shall have the numeric value of the numeric string" was removed from several sections of the ISO POSIX-2:1993 standard because is specifies an unnecessary implementation detail. It is not necessary for IEEE Std 1003.1-2001 to specify that these objects be assigned two different values. It is only necessary to specify that these objects may evaluate to two different values depending on context.

The description of numeric string processing is based on the behavior of the atof() function in the ISO C standard. While it is not a requirement for an implementation to use this function, many historical implementations of awk do. In the ISO C standard, floating-point constants use a period as a decimal point character for the language itself, independent of the current locale, but the atof() function and the associated strtod() function use the decimal point character of the current locale when converting strings to numeric values. Similarly in awk, floating-point constants in an awk script use a period independent of the locale, but input strings use the decimal point character of the locale.

FUTURE DIRECTIONS

None.

SEE ALSO

Grammar Conventions , grep , lex , sed , the System Interfaces volume of IEEE Std 1003.1-2001, atof(), exec, popen(), setlocale(), strtod()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cal(1p)

CAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cal - print a calendar

SYNOPSIS

cal [[month] year ]

DESCRIPTION

The cal utility shall write a calendar to standard output using the Julian calendar for dates from January 1, 1 through September 2, 1752 and the Gregorian calendar for dates from September 14, 1752 through December 31, 9999 as though the Gregorian calendar had been adopted on September 14, 1752.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

month
Specify the month to be displayed, represented as a decimal integer from 1 (January) to 12 (December). The default shall be the current month.
year
Specify the year for which the calendar is displayed, represented as a decimal integer from 1 to 9999. The default shall be the current year.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cal:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error, and informative messages written to standard output.
LC_TIME
Determine the format and contents of the calendar.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone used to calculate the value of the current month.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be used to display the calendar, in an unspecified format.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Note that:

cal 83

refers to A.D. 83, not 1983.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

A future version of IEEE Std 1003.1-2001 may support locale-specific recognition of the date of adoption of the Gregorian calendar.

SEE ALSO

None.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


exec(1p)

EXEC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

exec - execute commands and open, close, or copy file descriptors

SYNOPSIS

exec [command [argument ...]]

DESCRIPTION

The exec utility shall open, close, and/or copy file descriptors as specified by any redirections as part of the command.

If exec is specified without command or arguments, and any file descriptors with numbers greater than 2 are opened with associated redirection statements, it is unspecified whether those file descriptors remain open when the shell invokes another utility. Scripts concerned that child shells could misuse open file descriptors can always close them explicitly, as shown in one of the following examples.

If exec is specified with command, it shall replace the shell with command without creating a new process. If arguments are specified, they shall be arguments to command. Redirection affects the current shell execution environment.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If command is specified, exec shall not return to the shell; rather, the exit status of the process shall be the exit status of the program implementing command, which overlaid the shell. If command is not found, the exit status shall be 127. If command is found, but it is not an executable utility, the exit status shall be 126. If a redirection error occurs (see Consequences of Shell Errors ), the shell shall exit with a value in the range 1-125. Otherwise, exec shall return a zero exit status.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Open readfile as file descriptor 3 for reading:

exec 3< readfile

Open writefile as file descriptor 4 for writing:

exec 4> writefile

Make file descriptor 5 a copy of file descriptor 0:

exec 5<&0

Close file descriptor 3:

exec 3<&-

Cat the file maggie by replacing the current shell with the cat utility:

exec cat maggie

RATIONALE

Most historical implementations were not conformant in that:

foo=bar exec cmd

did not pass foo to cmd.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cat(1p)

CAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cat - concatenate and print files

SYNOPSIS

cat [-u][file ...]

DESCRIPTION

The cat utility shall read files in sequence and shall write their contents to the standard output in the same sequence.

OPTIONS

The cat utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-u
Write bytes from the input file to the standard output without delay as each is read.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If no file operands are specified, the standard input shall be used. If a file is '-' , the cat utility shall read from the standard input at that point in the sequence. The cat utility shall not close and reopen standard input when it is referenced in this way, but shall accept multiple occurrences of '-' as a file operand.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' . See the INPUT FILES section.

INPUT FILES

The input files can be any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cat:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall contain the sequence of bytes read from the input files. Nothing else shall be written to the standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were output successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The -u option has value in prototyping non-blocking reads from FIFOs. The intent is to support the following sequence:

mkfifo foo
cat -u foo > /dev/tty13 &
cat -u > foo

It is unspecified whether standard output is or is not buffered in the default case. This is sometimes of interest when standard output is associated with a terminal, since buffering may delay the output. The presence of the -u option guarantees that unbuffered I/O is available. It is implementation-defined whether the cat utility buffers output if the -u option is not specified. Traditionally, the -u option is implemented using the equivalent of the setvbuf() function defined in the System Interfaces volume of IEEE Std 1003.1-2001.

EXAMPLES

The following command:

cat myfile

writes the contents of the file myfile to standard output.

The following command:

cat doc1 doc2 > doc.all

concatenates the files doc1 and doc2 and writes the result to doc.all.

Because of the shell language mechanism used to perform output redirection, a command such as this:

cat doc doc.end > doc

causes the original data in doc to be lost.

The command:

cat start - middle - end > file

when standard input is a terminal, gets two arbitrary pieces of input from the terminal with a single invocation of cat. Note, however, that if standard input is a regular file, this would be equivalent to the command:

cat start - middle /dev/null end > file

because the entire contents of the file would be consumed by cat the first time '-' was used as a file operand and an end-of-file condition would be detected immediately when '-' was referenced the second time.

RATIONALE

Historical versions of the cat utility include the options -e, -t, and -v, which permit the ends of lines, <tab>s, and invisible characters, respectively, to be rendered visible in the output. The standard developers omitted these options because they provide too fine a degree of control over what is made visible, and similar output can be obtained using a command such as:

sed -n -e 's/$/$/' -e l pathname

The -s option was omitted because it corresponds to different functions in BSD and System V-based systems. The BSD -s option to squeeze blank lines can be accomplished by the shell script shown in the following example:

sed -n '
# Write non-empty lines.
/./   {
      p
      d
      }
# Write a single empty line, then look for more empty lines.
/^$/  p
# Get next line, discard the held <newline> (empty line),
# and look for more empty lines.
:Empty
/^$/  {
      N
      s/.//
      b Empty
      }
# Write the non-empty line before going back to search
# for the first in a set of empty lines.
      p

The System V -s option to silence error messages can be accomplished by redirecting the standard error. Note that the BSD documentation for cat uses the term "blank line" to mean the same as the POSIX "empty line'': a line consisting only of a <newline>.

The BSD -n option was omitted because similar functionality can be obtained from the -n option of the pr utility.

FUTURE DIRECTIONS

None.

SEE ALSO

more , the System Interfaces volume of IEEE Std 1003.1-2001, setvbuf()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


exit(1p)

EXIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

exit - cause the shell to exit

SYNOPSIS

exit [n]

DESCRIPTION

The exit utility shall cause the shell to exit with the exit status specified by the unsigned decimal integer n. If n is specified, but its value is not between 0 and 255 inclusively, the exit status is undefined.

A trap on EXIT shall be executed before the shell terminates, except when the exit utility is invoked in that trap itself, in which case the shell shall exit immediately.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The exit status shall be n, if specified. Otherwise, the value shall be the exit value of the last command executed, or zero if no command was executed. When exit is executed in a trap action, the last command is considered to be the command that executed immediately preceding the trap action.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Exit with a true value:

exit 0

Exit with a false value:

exit 1

RATIONALE

As explained in other sections, certain exit status values have been reserved for special uses and should be used by applications only for those purposes:

126
A file to be executed was found, but it was not an executable utility.
127
A utility to be executed was not found.
>128
A command was interrupted by a signal.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stty(1p)

STTY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stty - set the options for a terminal

SYNOPSIS

stty [ -a| -g]

stty operands

DESCRIPTION

The stty utility shall set or report on terminal I/O characteristics for the device that is its standard input. Without options or operands specified, it shall report the settings of certain characteristics, usually those that differ from implementation-defined defaults. Otherwise, it shall modify the terminal state according to the specified operands. Detailed information about the modes listed in the first five groups below are described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface. Operands in the Combination Modes group (see Combination Modes ) are implemented using operands in the previous groups. Some combinations of operands are mutually-exclusive on some terminal types; the results of using such combinations are unspecified.

Typical implementations of this utility require a communications line configured to use the termios interface defined in the System Interfaces volume of IEEE Std 1003.1-2001. On systems where none of these lines are available, and on lines not currently configured to support the termios interface, some of the operands need not affect terminal characteristics.

OPTIONS

The stty utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Write to standard output all the current settings for the terminal.
-g
Write to standard output all the current settings in an unspecified form that can be used as arguments to another invocation of the stty utility on the same system. The form used shall not contain any characters that would require quoting to avoid word expansion by the shell; see Word Expansions .

OPERANDS

The following operands shall be supported to set the terminal characteristics.

Control Modes

parenb (-parenb)
Enable (disable) parity generation and detection. This shall have the effect of setting (not setting) PARENB in the termios c_cflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
parodd (-parodd)

Select odd (even) parity. This shall have the effect of setting (not setting) PARODD in the termios c_cflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

cs5 cs6 cs7 cs8
Select character size, if possible. This shall have the effect of setting CS5, CS6, CS7, and CS8, respectively, in the termios c_cflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
number
Set terminal baud rate to the number given, if possible. If the baud rate is set to zero, the modem control lines shall no longer be asserted. This shall have the effect of setting the input and output termios baud rate values as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ispeed number
Set terminal input baud rate to the number given, if possible. If the input baud rate is set to zero, the input baud rate shall be specified by the value of the output baud rate. This shall have the effect of setting the input termios baud rate values as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ospeed number
Set terminal output baud rate to the number given, if possible. If the output baud rate is set to zero, the modem control lines shall no longer be asserted. This shall have the effect of setting the output termios baud rate values as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
hupcl (-hupcl)
Stop asserting modem control lines (do not stop asserting modem control lines) on last close. This shall have the effect of setting (not setting) HUPCL in the termios c_cflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
hup (-hup)
Equivalent to hupcl( -hupcl).
cstopb (-cstopb)
Use two (one) stop bits per character. This shall have the effect of setting (not setting) CSTOPB in the termios c_cflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
cread (-cread)
Enable (disable) the receiver. This shall have the effect of setting (not setting) CREAD in the termios c_cflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
clocal (-clocal)
Assume a line without (with) modem control. This shall have the effect of setting (not setting) CLOCAL in the termios c_cflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

It is unspecified whether stty shall report an error if an attempt to set a Control Mode fails.

Input Modes

ignbrk (-ignbrk)
Ignore (do not ignore) break on input. This shall have the effect of setting (not setting) IGNBRK in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
brkint (-brkint)
Signal (do not signal) INTR on break. This shall have the effect of setting (not setting) BRKINT in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ignpar (-ignpar)
Ignore (do not ignore) bytes with parity errors. This shall have the effect of setting (not setting) IGNPAR in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
parmrk (-parmrk)

Mark (do not mark) parity errors. This shall have the effect of setting (not setting) PARMRK in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

inpck (-inpck)
Enable (disable) input parity checking. This shall have the effect of setting (not setting) INPCK in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
istrip (-istrip)
Strip (do not strip) input characters to seven bits. This shall have the effect of setting (not setting) ISTRIP in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
inlcr (-inlcr)
Map (do not map) NL to CR on input. This shall have the effect of setting (not setting) INLCR in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
igncr (-igncr)
Ignore (do not ignore) CR on input. This shall have the effect of setting (not setting) IGNCR in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
icrnl (-icrnl)
Map (do not map) CR to NL on input. This shall have the effect of setting (not setting) ICRNL in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ixon (-ixon)
Enable (disable) START/STOP output control. Output from the system is stopped when the system receives STOP and started when the system receives START. This shall have the effect of setting (not setting) IXON in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ixany (-ixany)
Allow any character to restart output. This shall have the effect of setting (not setting) IXANY in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ixoff (-ixoff)
Request that the system send (not send) STOP characters when the input queue is nearly full and START characters to resume data transmission. This shall have the effect of setting (not setting) IXOFF in the termios c_iflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

Output Modes

opost (-opost)
Post-process output (do not post-process output; ignore all other output modes). This shall have the effect of setting (not setting) OPOST in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ocrnl (-ocrnl)
Map (do not map) CR to NL on output This shall have the effect of setting (not setting) OCRNL in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
onocr (-onocr)
Do not (do) output CR at column zero. This shall have the effect of setting (not setting) ONOCR in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
onlret (-onlret)
The terminal newline key performs (does not perform) the CR function. This shall have the effect of setting (not setting) ONLRET in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ofill (-ofill)
Use fill characters (use timing) for delays. This shall have the effect of setting (not setting) OFILL in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ofdel (-ofdel)
Fill characters are DELs (NULs). This shall have the effect of setting (not setting) OFDEL in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
cr0 cr1 cr2 cr3
Select the style of delay for CRs. This shall have the effect of setting CRDLY to CR0, CR1, CR2, or CR3, respectively, in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
nl0 nl1
Select the style of delay for NL. This shall have the effect of setting NLDLY to NL0 or NL1, respectively, in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
tab0 tab1 tab2 tab3

Select the style of delay for horizontal tabs. This shall have the effect of setting TABDLY to TAB0, TAB1, TAB2, or TAB3, respectively, in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface. Note that TAB3 has the effect of expanding <tab>s to <space>s.

tabs (-tabs)
Synonym for tab0 ( tab3).
bs0 bs1
Select the style of delay for backspaces. This shall have the effect of setting BSDLY to BS0 or BS1, respectively, in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
ff0 ff1
Select the style of delay for form-feeds. This shall have the effect of setting FFDLY to FF0 or FF1, respectively, in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
vt0 vt1
Select the style of delay for vertical-tabs. This shall have the effect of setting VTDLY to VT0 or VT1, respectively, in the termios c_oflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

Local Modes

isig (-isig)
Enable (disable) the checking of characters against the special control characters INTR, QUIT, and SUSP. This shall have the effect of setting (not setting) ISIG in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
icanon (-icanon)
Enable (disable) canonical input (ERASE and KILL processing). This shall have the effect of setting (not setting) ICANON in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
iexten (-iexten)
Enable (disable) any implementation-defined special control characters not currently controlled by icanon, isig, ixon, or ixoff. This shall have the effect of setting (not setting) IEXTEN in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
echo (-echo)
Echo back (do not echo back) every character typed. This shall have the effect of setting (not setting) ECHO in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
echoe (-echoe)
The ERASE character visually erases (does not erase) the last character in the current line from the display, if possible. This shall have the effect of setting (not setting) ECHOE in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
echok (-echok)
Echo (do not echo) NL after KILL character. This shall have the effect of setting (not setting) ECHOK in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
echonl (-echonl)
Echo (do not echo) NL, even if echo is disabled. This shall have the effect of setting (not setting) ECHONL in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
noflsh (-noflsh)
Disable (enable) flush after INTR, QUIT, SUSP. This shall have the effect of setting (not setting) NOFLSH in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.
tostop (-tostop)
Send SIGTTOU for background output. This shall have the effect of setting (not setting) TOSTOP in the termios c_lflag field, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

Special Control Character Assignments

<control>-character string

Set <control>-character to string. If <control>-character is one of the character sequences in the first column of the following table, the corresponding Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface control character from the second column shall be recognized. This has the effect of setting the corresponding element of the termios c_cc array (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers, <termios.h>).

Table: Control Character Names in stty
Control Character c_cc Subscript Description
eof VEOF EOF character
eol VEOL EOL character
erase VERASE ERASE character
intr VINTR INTR character
kill VKILL KILL character
quit VQUIT QUIT character
susp VSUSP SUSP character
start VSTART START character
stop VSTOP STOP character

If string is a single character, the control character shall be set to that character. If string is the two-character sequence "^-" or the string undef, the control character shall be set to _POSIX_VDISABLE , if it is in effect for the device; if _POSIX_VDISABLE is not in effect for the device, it shall be treated as an error. In the POSIX locale, if string is a two-character sequence beginning with circumflex ( '^' ), and the second character is one of those listed in the "^c" column of the following table, the control character shall be set to the corresponding character value in the Value column of the table.

Table: Circumflex Control Characters in stty
^c | Value | ^c | Value | ^c | Value
a, A | <SOH> | l, L | <FF> | w, W | <ETB>
b, B | <STX> | m, M | <CR> | x, X | <CAN>
c, C | <ETX> | n, N | <SO> | y, Y | <EM>
d, D | <EOT> | o, O | <SI> | z, Z | <SUB>
e, E | <ENQ> | p, P | <DLE> | [ | <ESC>
f, F | <ACK> | q, Q | <DC1> | \ | <FS>
g, G | <BEL> | r, R | <DC2> | ] | <GS>
h, H | <BS> | s, S | <DC3> | ^ | <RS>
i, I | <HT> | t, T | <DC4> |  | <US>
j, J | <LF> | u, U | <NAK> | ? | <DEL>
k, K | <VT> | v, V | <SYN> |  |
min number

Set the value of MIN to number. MIN is used in non-canonical mode input processing ( icanon).

time number

Set the value of TIME to number. TIME is used in non-canonical mode input processing ( icanon).

Combination Modes

saved settings

Set the current terminal characteristics to the saved settings produced by the -g option.

evenp or parity

Enable parenb and cs7; disable parodd.

oddp

Enable parenb, cs7, and parodd.

-parity, -evenp, or -oddp

Disable parenb, and set cs8.

raw (-raw or cooked)

Enable (disable) raw input and output. Raw mode shall be equivalent to setting:

stty cs8 erase ^- kill ^- intr ^- \
    quit ^- eof ^- eol ^- -post -inpck
nl (-nl)

Disable (enable) icrnl. In addition, -nl unsets inlcr and igncr.

ek
Reset ERASE and KILL characters back to system defaults.
sane

Reset all modes to some reasonable, unspecified, values.

STDIN

Although no input is read from standard input, standard input shall be used to get the current terminal I/O characteristics and to set new terminal I/O characteristics.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of stty:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
This variable determines the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments) and which characters are in the class print.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If operands are specified, no output shall be produced.

If the -g option is specified, stty shall write to standard output the current settings in a form that can be used as arguments to another instance of stty on the same system.

If the -a option is specified, all of the information as described in the OPERANDS section shall be written to standard output. Unless otherwise specified, this information shall be written as <space>-separated tokens in an unspecified format, on one or more lines, with an unspecified number of tokens per line. Additional information may be written.

If no options or operands are specified, an unspecified subset of the information written for the -a option shall be written.

If speed information is written as part of the default output, or if the -a option is specified and if the terminal input speed and output speed are the same, the speed information shall be written as follows:

"speed %d baud;", <speed>

Otherwise, speeds shall be written as:

"ispeed %d baud; ospeed %d baud;", <ispeed>, <ospeed>

In locales other than the POSIX locale, the word baud may be changed to something more appropriate in those locales.

If control characters are written as part of the default output, or if the -a option is specified, control characters shall be written as:

"%s = %s;", <control-character name>, <value>

where <value> is either the character, or some visual representation of the character if it is non-printable, or the string undef if the character is disabled.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The terminal options were read or set successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The -g flag is designed to facilitate the saving and restoring of terminal state from the shell level. For example, a program may:

saveterm="$(stty -g)"       # save terminal state
stty (new settings)         # set new state
...                         # ...
stty $saveterm              # restore terminal state

Since the format is unspecified, the saved value is not portable across systems.

Since the -a format is so loosely specified, scripts that save and restore terminal settings should use the -g option.

EXAMPLES

None.

RATIONALE

The original stty description was taken directly from System V and reflected the System V terminal driver termio. It has been modified to correspond to the terminal driver termios.

Output modes are specified only for XSI-conformant systems. All implementations are expected to provide stty operands corresponding to all of the output modes they support.

The stty utility is primarily used to tailor the user interface of the terminal, such as selecting the preferred ERASE and KILL characters. As an application programming utility, stty can be used within shell scripts to alter the terminal settings for the duration of the script.

The termios section states that individual disabling of control characters is possible through the option _POSIX_VDISABLE. If enabled, two conventions currently exist for specifying this: System V uses "^-" , and BSD uses undef. Both are accepted by stty in this volume of IEEE Std 1003.1-2001. The other BSD convention of using the letter 'u' was rejected because it conflicts with the actual letter 'u' , which is an acceptable value for a control character.

Early proposals did not specify the mapping of "^c" to control characters because the control characters were not specified in the POSIX locale character set description file requirements. The control character set is now specified in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 3, Definitions so the historical mapping is specified. Note that although the mapping corresponds to control-character key assignments on many terminals that use the ISO/IEC 646:1991 standard (or ASCII) character encodings, the mapping specified here is to the control characters, not their keyboard encodings.

Since termios supports separate speeds for input and output, two new options were added to specify each distinctly.

Some historical implementations use standard input to get and set terminal characteristics; others use standard output. Since input from a login TTY is usually restricted to the owner while output to a TTY is frequently open to anyone, using standard input provides fewer chances of accidentally (or maliciously) altering the terminal settings of other users. Using standard input also allows stty -a and stty -g output to be redirected for later use. Therefore, usage of standard input is required by this volume of IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


compress(1p)

COMPRESS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

compress - compress data

SYNOPSIS

compress [-fv][-b bits][file ...]

compress [-cfv][-b bits][file]

DESCRIPTION

The compress utility shall attempt to reduce the size of the named files by using adaptive Lempel-Ziv coding algorithm.

Note:
Lempel-Ziv is US Patent 4464650, issued to William Eastman, Abraham Lempel, Jacob Ziv, Martin Cohn on August 7th, 1984, and assigned to Sperry Corporation.

Lempel-Ziv-Welch compression is covered by US Patent 4558302, issued to Terry A. Welch on December 10th, 1985, and assigned to Sperry Corporation.

On systems not supporting adaptive Lempel-Ziv coding algorithm, the input files shall not be changed and an error value greater than two shall be returned. Except when the output is to the standard output, each file shall be replaced by one with the extension .Z. If the invoking process has appropriate privileges, the ownership, modes, access time, and modification time of the original file are preserved. If appending the .Z to the filename would make the name exceed {NAME_MAX} bytes, the command shall fail. If no files are specified, the standard input shall be compressed to the standard output.

OPTIONS

The compress utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-b bits
Specify the maximum number of bits to use in a code. For a conforming application, the bits argument shall be:

9 <= bits <= 14

The implementation may allow bits values of greater than 14. The default is 14, 15, or 16.

-c
Cause compress to write to the standard output; the input file is not changed, and no .Z files are created.
-f
Force compression of file, even if it does not actually reduce the size of the file, or if the corresponding file .Z file already exists. If the -f option is not given, and the process is not running in the background, the user is prompted as to whether an existing file .Z file should be overwritten.
-v
Write the percentage reduction of each file to standard error.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be compressed.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' .

INPUT FILES

If file operands are specified, the input files contain the data to be compressed.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of compress:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If no file operands are specified, or if a file operand is '-' , or if the -c option is specified, the standard output contains the compressed output.

STDERR

The standard error shall be used only for diagnostic and prompt messages and the output from -v.

OUTPUT FILES

The output files shall contain the compressed output. The format of compressed files is unspecified and interchange of such files between implementations (including access via unspecified file sharing mechanisms) is not required by IEEE Std 1003.1-2001.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
1
An error occurred.
2
One or more files were not compressed because they would have increased in size (and the -f option was not specified).
>2
An error occurred.

CONSEQUENCES OF ERRORS

The input file shall remain unmodified.

The following sections are informative.

APPLICATION USAGE

The amount of compression obtained depends on the size of the input, the number of bits per code, and the distribution of common substrings. Typically, text such as source code or English is reduced by 50-60%. Compression is generally much better than that achieved by Huffman coding or adaptive Huffman coding ( compact), and takes less time to compute.

Although compress strictly follows the default actions upon receipt of a signal or when an error occurs, some unexpected results may occur. In some implementations it is likely that a partially compressed file is left in place, alongside its uncompressed input file. Since the general operation of compress is to delete the uncompressed file only after the .Z file has been successfully filled, an application should always carefully check the exit status of compress before arbitrarily deleting files that have like-named neighbors with .Z suffixes.

The limit of 14 on the bits option-argument is to achieve portability to all systems (within the restrictions imposed by the lack of an explicit published file format). Some implementations based on 16-bit architectures cannot support 15 or 16-bit uncompression.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

uncompress , zcat

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


chmod(1p)

CHMOD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

chmod - change the file modes

SYNOPSIS

chmod [-R] mode file ...

DESCRIPTION

The chmod utility shall change any or all of the file mode bits of the file named by each file operand in the way specified by the mode operand.

It is implementation-defined whether and how the chmod utility affects any alternate or additional file access control mechanism (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.4, File Access Permissions) being used for the specified file.

Only a process whose effective user ID matches the user ID of the file, or a process with the appropriate privileges, shall be permitted to change the file mode bits of a file.

OPTIONS

The chmod utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-R
Recursively change file mode bits. For each file operand that names a directory, chmod shall change the file mode bits of the directory and all files in the file hierarchy below it.

OPERANDS

The following operands shall be supported:

mode
Represents the change to be made to the file mode bits of each file named by one of the file operands; see the EXTENDED DESCRIPTION section.
file
A pathname of a file whose file mode bits shall be modified.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of chmod:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The mode operand shall be either a symbolic_mode expression or a non-negative octal integer. The symbolic_mode form is described by the grammar later in this section.

Each clause shall specify an operation to be performed on the current file mode bits of each file. The operations shall be performed on each file in the order in which the clauses are specified.

The who symbols u, g, and o shall specify the user, group, and other parts of the file mode bits, respectively. A who consisting of the symbol a shall be equivalent to ugo.

The perm symbols r, w, and x represent the read, write, and execute/ search portions of file mode bits, respectively. The perm symbol s shall represent the set-user-ID-on-execution (when who contains or implies u) and set-group-ID-on-execution (when who contains or implies g) bits.

The perm symbol X shall represent the execute/search portion of the file mode bits if the file is a directory or if the current (unmodified) file mode bits have at least one of the execute bits (S_IXUSR, S_IXGRP, or S_IXOTH) set. It shall be ignored if the file is not a directory and none of the execute bits are set in the current file mode bits.

The permcopy symbols u, g, and o shall represent the current permissions associated with the user, group, and other parts of the file mode bits, respectively. For the remainder of this section, perm refers to the non-terminals perm and permcopy in the grammar.

If multiple actionlists are grouped with a single wholist in the grammar, each actionlist shall be applied in the order specified with that wholist. The op symbols shall represent the operation performed, as follows:

+
If perm is not specified, the '+' operation shall not change the file mode bits.

If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be set.

Otherwise, the file mode bits represented by the specified who and perm values shall be set.

-
If perm is not specified, the '-' operation shall not change the file mode bits.

If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be cleared.

Otherwise, the file mode bits represented by the specified who and perm values shall be cleared.

=
Clear the file mode bits specified by the who value, or, if no who value is specified, all of the file mode bits specified in this volume of IEEE Std 1003.1-2001.

If perm is not specified, the '=' operation shall make no further modifications to the file mode bits.

If who is not specified, the file mode bits represented by perm for the owner, group, and other permissions, except for those with corresponding bits in the file mode creation mask of the invoking process, shall be set.

Otherwise, the file mode bits represented by the specified who and perm values shall be set.

When using the symbolic mode form on a regular file, it is implementation-defined whether or not:

*
Requests to set the set-user-ID-on-execution or set-group-ID-on-execution bit when all execute bits are currently clear and none are being set are ignored.

*
Requests to clear all execute bits also clear the set-user-ID-on-execution and set-group-ID-on-execution bits.

*
Requests to clear the set-user-ID-on-execution or set-group-ID-on-execution bits when all execute bits are currently clear are ignored. However, if the command ls -l file writes an s in the position indicating that the set-user-ID-on-execution or set-group-ID-on-execution is set, the commands chmod u-s file or chmod g-s file, respectively, shall not be ignored.

When using the symbolic mode form on other file types, it is implementation-defined whether or not requests to set or clear the set-user-ID-on-execution or set-group-ID-on-execution bits are honored.

If the who symbol o is used in conjunction with the perm symbol s with no other who symbols being specified, the set-user-ID-on-execution and set-group-ID-on-execution bits shall not be modified. It shall not be an error to specify the who symbol o in conjunction with the perm symbol s.

The perm symbol t shall specify the S_ISVTX bit. When used with a file of type directory, it can be used with the who symbol a, or with no who symbol. It shall not be an error to specify a who symbol of u, g, or o in conjunction with the perm symbol t, but the meaning of these combinations is unspecified. The effect when using the perm symbol t with any file type other than directory is unspecified.

For an octal integer mode operand, the file mode bits shall be set absolutely.

For each bit set in the octal number, the corresponding file permission bit shown in the following table shall be set; all other file permission bits shall be cleared. For regular files, for each bit set in the octal number corresponding to the set-user-ID-on-execution or the set-group-ID-on-execution, bits shown in the following table shall be set; if these bits are not set in the octal number, they are cleared. For other file types, it is implementation-defined whether or not requests to set or clear the set-user-ID-on-execution or set-group-ID-on-execution bits are honored.
Octal | Mode Bit | Octal | Mode Bit | Octal | Mode Bit | Octal | Mode Bit
4000 | S_ISUID | 0400 | S_IRUSR | 0040 | S_IRGRP | 0004 | S_IROTH
2000 | S_ISGID | 0200 | S_IWUSR | 0020 | S_IWGRP | 0002 | S_IWOTH
1000 | S_ISVTX | 0100 | S_IXUSR | 0010 | S_IXGRP | 0001 | S_IXOTH

When bits are set in the octal number other than those listed in the table above, the behavior is unspecified.

Grammar for chmod

The grammar and lexical conventions in this section describe the syntax for the symbolic_mode operand. The general conventions for this style of grammar are described in Grammar Conventions . A valid symbolic_mode can be represented as the non-terminal symbol symbolic_mode in the grammar. This formal syntax shall take precedence over the preceding text syntax description.

The lexical processing is based entirely on single characters. Implementations need not allow <blank>s within the single argument being processed.

%start    symbolic_mode
%%

symbolic_mode    : clause
                 | symbolic_mode ',' clause
                 ;

clause           : actionlist
                 | wholist actionlist
                 ;

wholist          : who
                 | wholist who
                 ;

who              : 'u' | 'g' | 'o' | 'a'
                 ;

actionlist       : action
                 | actionlist action
                 ;

action           : op
                 | op permlist
                 | op permcopy
                 ;

permcopy         : 'u' | 'g' | 'o'
                 ;

op               : '+' | '-' | '='
                 ;

permlist         : perm
                 | perm permlist
                 ;

perm             : 'r' | 'w' | 'x' | 'X' | 's' | 't'
                 ;

EXIT STATUS

The following exit values shall be returned:

0
The utility executed successfully and all requested changes were made.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Some implementations of the chmod utility change the mode of a directory before the files in the directory when performing a recursive ( -R option) change; others change the directory mode after the files in the directory. If an application tries to remove read or search permission for a file hierarchy, the removal attempt fails if the directory is changed first; on the other hand, trying to re-enable permissions to a restricted hierarchy fails if directories are changed last. Users should not try to make a hierarchy inaccessible to themselves.

Some implementations of chmod never used the process' umask when changing modes; systems conformant with this volume of IEEE Std 1003.1-2001 do so when who is not specified. Note the difference between:

chmod a-w file

which removes all write permissions, and:

chmod -- -w file

which removes write permissions that would be allowed if file was created with the same umask.

Conforming applications should never assume that they know how the set-user-ID and set-group-ID bits on directories are interpreted.

EXAMPLES

Mode | Results
a+= | Equivalent to a+, a=; clears all file mode bits.
go+-w | Equivalent to go+, go- w; clears group and other write bits.
g=o-w | Equivalent to g= o, g- w; sets group bit to match other bits and then clears group write bit.
g-r+w | Equivalent to g- r, g+ w; clears group read bit and sets group write bit.
uo=g | Sets owner bits to match group bits and sets other bits to match group bits.

RATIONALE

The functionality of chmod is described substantially through references to concepts defined in the System Interfaces volume of IEEE Std 1003.1-2001. In this way, there is less duplication of effort required for describing the interactions of permissions. However, the behavior of this utility is not described in terms of the chmod() function from the System Interfaces volume of IEEE Std 1003.1-2001 because that specification requires certain side effects upon alternate file access control mechanisms that might not be appropriate, depending on the implementation.

Implementations that support mandatory file and record locking as specified by the 1984 /usr/group standard historically used the combination of set-group-ID bit set and group execute bit clear to indicate mandatory locking. This condition is usually set or cleared with the symbolic mode perm symbol l instead of the perm symbols s and x so that the mandatory locking mode is not changed without explicit indication that that was what the user intended. Therefore, the details on how the implementation treats these conditions must be defined in the documentation. This volume of IEEE Std 1003.1-2001 does not require mandatory locking (nor does the System Interfaces volume of IEEE Std 1003.1-2001), but does allow it as an extension. However, this volume of IEEE Std 1003.1-2001 does require that the ls and chmod utilities work consistently in this area. If ls -l file indicates that the set-group-ID bit is set, chmod g-s file must clear it (assuming appropriate privileges exist to change modes).

The System V and BSD versions use different exit status codes. Some implementations used the exit status as a count of the number of errors that occurred; this practice is unworkable since it can overflow the range of valid exit status values. This problem is avoided here by specifying only 0 and >0 as exit values.

The System Interfaces volume of IEEE Std 1003.1-2001 indicates that implementation-defined restrictions may cause the S_ISUID and S_ISGID bits to be ignored. This volume of IEEE Std 1003.1-2001 allows the chmod utility to choose to modify these bits before calling chmod() (or some function providing equivalent capabilities) for non-regular files. Among other things, this allows implementations that use the set-user-ID and set-group-ID bits on directories to enable extended features to handle these extensions in an intelligent manner.

The X perm symbol was adopted from BSD-based systems because it provides commonly desired functionality when doing recursive ( -R option) modifications. Similar functionality is not provided by the find utility. Historical BSD versions of chmod, however, only supported X with op+; it has been extended in this volume of IEEE Std 1003.1-2001 because it is also useful with op=. (It has also been added for op- even though it duplicates x, in this case, because it is intuitive and easier to explain.)

The grammar was extended with the permcopy non-terminal to allow historical-practice forms of symbolic modes like o= u -g (that is, set the "other" permissions to the permissions of "owner" minus the permissions of "group").

FUTURE DIRECTIONS

None.

SEE ALSO

ls , umask , the System Interfaces volume of IEEE Std 1003.1-2001, chmod()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cmp(1p)

CMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cmp - compare two files

SYNOPSIS

cmp [ -l | -s ] file1 file2

DESCRIPTION

The cmp utility shall compare two files. The cmp utility shall write no output if the files are the same. Under default options, if they differ, it shall write to standard output the byte and line number at which the first difference occurred. Bytes and lines shall be numbered beginning with 1.

OPTIONS

The cmp utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-l
(Lowercase ell.) Write the byte number (decimal) and the differing bytes (octal) for each difference.
-s
Write nothing for differing files; return exit status only.

OPERANDS

The following operands shall be supported:

file1
A pathname of the first file to be compared. If file1 is '-' , the standard input shall be used.
file2
A pathname of the second file to be compared. If file2 is '-' , the standard input shall be used.

If both file1 and file2 refer to standard input or refer to the same FIFO special, block special, or character special file, the results are undefined.

STDIN

The standard input shall be used only if the file1 or file2 operand refers to standard input. See the INPUT FILES section.

INPUT FILES

The input files can be any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cmp:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

In the POSIX locale, results of the comparison shall be written to standard output. When no options are used, the format shall be:

"%s %s differ: char %d, line %d\n", file1, file2,
    <byte number>, <line number>

When the -l option is used, the format shall be:

"%d %o %o\n", <byte number>, <differing byte>,
    <differing byte>

for each byte that differs. The first <differing byte> number is from file1 while the second is from file2. In both cases, <byte number> shall be relative to the beginning of the file, beginning with 1.

No output shall be written to standard output when the -s option is used.

STDERR

The standard error shall be used only for diagnostic messages. If file1 and file2 are identical for the entire length of the shorter file, in the POSIX locale the following diagnostic message shall be written, unless the -s option is specified:

"cmp: EOF on %s%s\n", <name of shorter file>, <additional info>

The <additional info> field shall either be null or a string that starts with a <blank> and contains no <newline>s. Some implementations report on the number of lines in this case.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The files are identical.
1
The files are different; this includes the case where one file is identical to the first part of the other.
>1
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Although input files to cmp can be any type, the results might not be what would be expected on character special device files or on file types not described by the System Interfaces volume of IEEE Std 1003.1-2001. Since this volume of IEEE Std 1003.1-2001 does not specify the block size used when doing input, comparisons of character special files need not compare all of the data in those files.

For files which are not text files, line numbers simply reflect the presence of a <newline>, without any implication that the file is organized into lines.

EXAMPLES

None.

RATIONALE

The global language in Utility Description Defaults indicates that using two mutually-exclusive options together produces unspecified results. Some System V implementations consider the option usage:

cmp -l -s ...

to be an error. They also treat:

cmp -s -l ...

as if no options were specified. Both of these behaviors are considered bugs, but are allowed.

The word char in the standard output format comes from historical usage, even though it is actually a byte number. When cmp is supported in other locales, implementations are encouraged to use the word byte or its equivalent in another language. Users should not interpret this difference to indicate that the functionality of the utility changed between locales.

Some implementations report on the number of lines in the identical-but-shorter file case. This is allowed by the inclusion of the <additional info> fields in the output format. The restriction on having a leading <blank> and no <newline>s is to make parsing for the filename easier. It is recognized that some filenames containing white-space characters make parsing difficult anyway, but the restriction does aid programs used on systems where the names are predominantly well behaved.

FUTURE DIRECTIONS

None.

SEE ALSO

comm , diff

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


expr(1p)

EXPR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

expr - evaluate arguments as an expression

SYNOPSIS

expr operand

DESCRIPTION

The expr utility shall evaluate an expression and write the result to standard output.

OPTIONS

None.

OPERANDS

The single expression evaluated by expr shall be formed from the operands, as described in the EXTENDED DESCRIPTION section. The application shall ensure that each of the expression operator symbols:

(  )  |  &  =  >  >=  <  <=  !=  +  -  *  /  %  :

and the symbols integer and string in the table are provided as separate arguments to expr.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of expr:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions and by the string comparison operators.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments) and the behavior of character classes within regular expressions.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The expr utility shall evaluate the expression and write the result, followed by a <newline>, to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The formation of the expression to be evaluated is shown in the following table. The symbols expr, expr1, and expr2 represent expressions formed from integer and string symbols and the expression operator symbols (all separate arguments) by recursive application of the constructs described in the table. The expressions are listed in order of increasing precedence, with equal-precedence operators grouped between horizontal lines. All of the operators shall be left-associative.
Expression | Description
expr1 | expr2 | Returns the evaluation of expr1 if it is neither null nor zero; otherwise, returns the evaluation of expr2 if it is not null; otherwise, zero.
expr1 & expr2 | Returns the evaluation of expr1 if neither expression evaluates to null or zero; otherwise, returns zero.
 | Returns the result of a decimal integer comparison if both arguments are integers; otherwise, returns the result of a string comparison using the locale-specific collation sequence. The result of each comparison is 1 if the specified relationship is true, or 0 if the relationship is false.
expr1 = expr2 | Equal.
expr1 > expr2 | Greater than.
expr1 >= expr2 | Greater than or equal.
expr1 < expr2 | Less than.
expr1 <= expr2 | Less than or equal.
expr1 != expr2 | Not equal.
expr1 + expr2 | Addition of decimal integer-valued arguments.
expr1 - expr2 | Subtraction of decimal integer-valued arguments.
expr1 * expr2 | Multiplication of decimal integer-valued arguments.
expr1 / expr2 | Integer division of decimal integer-valued arguments, producing an integer result.
expr1 % expr2 | Remainder of integer division of decimal integer-valued arguments.
expr1 : expr2 | Matching expression; see below.
( expr ) | Grouping symbols. Any expression can be placed within parentheses. Parentheses can be nested to a depth of {EXPR_NEST_MAX}.
integer | An argument consisting only of an (optional) unary minus followed by digits.
string | A string argument; see below.

Matching Expression

The ':' matching operator shall compare the string resulting from the evaluation of expr1 with the regular expression pattern resulting from the evaluation of expr2. Regular expression syntax shall be that defined in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions, except that all patterns are anchored to the beginning of the string (that is, only sequences starting at the first character of a string are matched by the regular expression) and, therefore, it is unspecified whether '^' is a special character in that context. Usually, the matching operator shall return a string representing the number of characters matched ( '0' on failure). Alternatively, if the pattern contains at least one regular expression subexpression "[\(...\)]" , the string corresponding to "\1" shall be returned.

String Operand

A string argument is an argument that cannot be identified as an integer argument or as one of the expression operator symbols shown in the OPERANDS section.

The use of string arguments length, substr, index, or match produces unspecified results.

EXIT STATUS

The following exit values shall be returned:

0
The expression evaluates to neither null nor zero.
1
The expression evaluates to null or zero.
2
Invalid expression.
>2
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

After argument processing by the shell, expr is not required to be able to tell the difference between an operator and an operand except by the value. If "$a" is '=' , the command:

expr $a = '='

looks like:

expr = = =

as the arguments are passed to expr (and they all may be taken as the '=' operator). The following works reliably:

expr X$a = X=

Also note that this volume of IEEE Std 1003.1-2001 permits implementations to extend utilities. The expr utility permits the integer arguments to be preceded with a unary minus. This means that an integer argument could look like an option. Therefore, the conforming application must employ the "--" construct of Guideline 10 of the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines to protect its operands if there is any chance the first operand might be a negative integer (or any string with a leading minus).

EXAMPLES

The expr utility has a rather difficult syntax:

*
Many of the operators are also shell control operators or reserved words, so they have to be escaped on the command line.

*
Each part of the expression is composed of separate arguments, so liberal usage of <blank>s is required. For example:
Invalid Valid
expr 1+2 expr 1 + 2
expr "1 + 2" expr 1 + 2
expr 1 + (2 * 3) expr 1 + \( 2 \* 3 \)

In many cases, the arithmetic and string features provided as part of the shell command language are easier to use than their equivalents in expr. Newly written scripts should avoid expr in favor of the new features within the shell; see Parameters and Variables and Arithmetic Expansion .

The following command:

a=$(expr $a + 1)

adds 1 to the variable a.

The following command, for "$a" equal to either /usr/abc/file or just file:

expr $a : '.*/\(.*\)' \| $a

returns the last segment of a pathname (that is, file). Applications should avoid the character '/' used alone as an argument; expr may interpret it as the division operator.

The following command:

expr "//$a" : '.*/\(.*\)'

is a better representation of the previous example. The addition of the "//" characters eliminates any ambiguity about the division operator and simplifies the whole expression. Also note that pathnames may contain characters contained in the IFS variable and should be quoted to avoid having "$a" expand into multiple arguments.

The following command:

expr "$VAR" : '.*'

returns the number of characters in VAR.

RATIONALE

In an early proposal, EREs were used in the matching expression syntax. This was changed to BREs to avoid breaking historical applications.

The use of a leading circumflex in the BRE is unspecified because many historical implementations have treated it as a special character, despite their system documentation. For example:

expr foo : ^foo     expr ^foo : ^foo

return 3 and 0, respectively, on those systems; their documentation would imply the reverse. Thus, the anchoring condition is left unspecified to avoid breaking historical scripts relying on this undocumented feature.

FUTURE DIRECTIONS

None.

SEE ALSO

Parameters and Variables , Arithmetic Expansion

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


colon(1p)

COLON

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

colon - null utility

SYNOPSIS

: [argument ...]

DESCRIPTION

This utility shall only expand command arguments. It is used when a command is needed, as in the then condition of an if command, but nothing is to be done by the command.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Zero.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

: ${X=abc}
if     false
then   :
else   echo $X
fi
abc

As with any of the special built-ins, the null utility can also have variable assignments and redirections associated with it, such as:

x=y : > z

which sets variable x to the value y (so that it persists after the null utility completes) and creates or truncates file z.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cut(1p)

CUT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cut - cut out selected fields of each line of a file

SYNOPSIS

cut -b list [-n] [file ...]

cut -c list [file ...]

cut -f list [-d delim][-s][file ...]

DESCRIPTION

The cut utility shall cut out bytes ( -b option), characters ( -c option), or character-delimited fields ( -f option) from each line in one or more files, concatenate them, and write them to standard output.

OPTIONS

The cut utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The application shall ensure that the option-argument list (see options -b, -c, and -f below) is a comma-separated list or <blank>-separated list of positive numbers and ranges. Ranges can be in three forms. The first is two positive numbers separated by a hyphen ( low- high), which represents all fields from the first number to the second number. The second is a positive number preceded by a hyphen (- high), which represents all fields from field number 1 to that number. The third is a positive number followed by a hyphen ( low-), which represents that number to the last field, inclusive. The elements in list can be repeated, can overlap, and can be specified in any order, but the bytes, characters, or fields selected shall be written in the order of the input data. If an element appears in the selection list more than once, it shall be written exactly once.

The following options shall be supported:

-b list
Cut based on a list of bytes. Each selected byte shall be output unless the -n option is also specified. It shall not be an error to select bytes not present in the input line.
-c list
Cut based on a list of characters. Each selected character shall be output. It shall not be an error to select characters not present in the input line.
-d delim
Set the field delimiter to the character delim. The default is the <tab>.
-f list
Cut based on a list of fields, assumed to be separated in the file by a delimiter character (see -d). Each selected field shall be output. Output fields shall be separated by a single occurrence of the field delimiter character. Lines with no field delimiters shall be passed through intact, unless -s is specified. It shall not be an error to select fields not present in the input line.
-n
Do not split characters. When specified with the -b option, each element in list of the form low- high (hyphen-separated numbers) shall be modified as follows:
*
If the byte selected by low is not the first byte of a character, low shall be decremented to select the first byte of the character originally selected by low. If the byte selected by high is not the last byte of a character, high shall be decremented to select the last byte of the character prior to the character originally selected by high, or zero if there is no prior character. If the resulting range element has high equal to zero or low greater than high, the list element shall be dropped from list for that input line without causing an error.

Each element in list of the form low- shall be treated as above with high set to the number of bytes in the current line, not including the terminating <newline>. Each element in list of the form - high shall be treated as above with low set to 1. Each element in list of the form num (a single number) shall be treated as above with low set to num and high set to num.

-s
Suppress lines with no delimiter characters, when used with the -f option. Unless specified, lines with no delimiters shall be passed through untouched.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If no file operands are specified, or if a file operand is '-' , the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' . See the INPUT FILES section.

INPUT FILES

The input files shall be text files, except that line lengths shall be unlimited.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cut:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The cut utility output shall be a concatenation of the selected bytes, characters, or fields (one of the following):

"%s\n", <concatenation of bytes>

"%s\n", <concatenation of characters>

"%s\n", <concatenation of fields and field delimiters>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were output successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Earlier versions of the cut utility worked in an environment where bytes and characters were considered equivalent (modulo <backspace> and <tab> processing in some implementations). In the extended world of multi-byte characters, the new -b option has been added. The -n option (used with -b) allows it to be used to act on bytes rounded to character boundaries. The algorithm specified for -n guarantees that:

cut -b 1-500 -n file > file1
cut -b 501- -n file > file2

ends up with all the characters in file appearing exactly once in file1 or file2. (There is, however, a <newline> in both file1 and file2 for each <newline> in file.)

EXAMPLES

Examples of the option qualifier list:

1,4,7
Select the first, fourth, and seventh bytes, characters, or fields and field delimiters.
1-3,8
Equivalent to 1,2,3,8.
-5,10
Equivalent to 1,2,3,4,5,10.
3-
Equivalent to third to last, inclusive.

The low- high forms are not always equivalent when used with -b and -n and multi-byte characters; see the description of -n.

The following command:

cut -d : -f 1,6 /etc/passwd

reads the System V password file (user database) and produces lines of the form:

<user ID>:<home directory>

Most utilities in this volume of IEEE Std 1003.1-2001 work on text files. The cut utility can be used to turn files with arbitrary line lengths into a set of text files containing the same data. The paste utility can be used to create (or recreate) files with arbitrary line lengths. For example, if file contains long lines:

cut -b 1-500 -n file > file1
cut -b 501- -n file > file2

creates file1 (a text file) with lines no longer than 500 bytes (plus the <newline>) and file2 that contains the remainder of the data from file. (Note that file2 is not a text file if there are lines in file that are longer than 500 + {LINE_MAX} bytes.) The original file can be recreated from file1 and file2 using the command:

paste -d "\0" file1 file2 > file

RATIONALE

Some historical implementations do not count <backspace>s in determining character counts with the -c option. This may be useful for using cut for processing nroff output. It was deliberately decided not to have the -c option treat either <backspace>s or <tab>s in any special fashion. The fold utility does treat these characters specially.

Unlike other utilities, some historical implementations of cut exit after not finding an input file, rather than continuing to process the remaining file operands. This behavior is prohibited by this volume of IEEE Std 1003.1-2001, where only the exit status is affected by this problem.

The behavior of cut when provided with either mutually-exclusive options or options that do not work logically together has been deliberately left unspecified in favor of global wording in Utility Description Defaults .

The OPTIONS section was changed in response to IEEE PASC Interpretation 1003.2 #149. The change represents historical practice on all known systems. The original standard was ambiguous on the nature of the output.

The list option-arguments are historically used to select the portions of the line to be written, but do not affect the order of the data. For example:

echo abcdefghi | cut -c6,2,4-7,1

yields "abdefg" .

A proposal to enhance cut with the following option:

-o
Preserve the selected field order. When this option is specified, each byte, character, or field (or ranges of such) shall be written in the order specified by the list option-argument, even if this requires multiple outputs of the same bytes, characters, or fields.

was rejected because this type of enhancement is outside the scope of the IEEE P1003.2b draft standard.

FUTURE DIRECTIONS

None.

SEE ALSO

grep , paste , Parameters and Variables

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dot(1p)

DOT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dot - execute commands in the current environment

SYNOPSIS

. file

DESCRIPTION

The shell shall execute commands from the file in the current environment.

If file does not contain a slash, the shell shall use the search path specified by PATH to find the directory containing file. Unlike normal command search, however, the file searched for by the dot utility need not be executable. If no readable file is found, a non-interactive shell shall abort; an interactive shell shall write a diagnostic message to standard error, but this condition shall not be considered a syntax error.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

See the DESCRIPTION.

ENVIRONMENT VARIABLES

See the DESCRIPTION.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Returns the value of the last command executed, or a zero exit status if no command is executed.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

cat foobar
foo=hello bar=world. foobar
echo $foo $bar
hello world

RATIONALE

Some older implementations searched the current directory for the file, even if the value of PATH disallowed it. This behavior was omitted from this volume of IEEE Std 1003.1-2001 due to concerns about introducing the susceptibility to trojan horses that the user might be trying to avoid by leaving dot out of PATH .

The KornShell version of dot takes optional arguments that are set to the positional parameters. This is a valid extension that allows a dot script to behave identically to a function.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


readonly(1p)

READONLY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

readonly - set the readonly attribute for variables

SYNOPSIS

readonly name[=word]...

readonly -p

DESCRIPTION

The variables whose names are specified shall be given the readonly attribute. The values of variables with the readonly attribute cannot be changed by subsequent assignment, nor can those variables be unset by the unset utility. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

The readonly special built-in shall support the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

When -p is specified, readonly writes to the standard output the names and values of all read-only variables, in the following format:

"readonly %s=%s\n", <name>, <value>

if name is set, and

"readonly %s\n", <name>

if name is unset.

The shell shall format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same value and readonly attribute-setting results in a shell execution environment in which:

1.
Variables with values at the time they were output do not have the readonly attribute set.

2.
Variables that were unset at the time they were output do not have a value at the time at which the saved output is reinput to the shell.

When no arguments are given, the results are unspecified.

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Zero.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

readonly HOME PWD

RATIONALE

Some historical shells preserve the readonly attribute across separate invocations. This volume of IEEE Std 1003.1-2001 allows this behavior, but does not require it.

The -p option allows portable access to the values that can be saved and then later restored using, for example, a dot script. Also see the RATIONALE for export for a description of the no-argument and -p output cases and a related example.

Read-only functions were considered, but they were omitted as not being historical practice or particularly useful. Furthermore, functions must not be read-only across invocations to preclude ``spoofing'' (spoofing is the term for the practice of creating a program that acts like a well-known utility with the intent of subverting the real intent of the user) of administrative or security-relevant (or security-conscious) shell scripts.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


gencat(1p)

GENCAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gencat - generate a formatted message catalog

SYNOPSIS

gencat catfile msgfile...

DESCRIPTION

The gencat utility shall merge the message text source file msgfile into a formatted message catalog catfile. The file catfile shall be created if it does not already exist. If catfile does exist, its messages shall be included in the new catfile. If set and message numbers collide, the new message text defined in msgfile shall replace the old message text currently contained in catfile.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

catfile
A pathname of the formatted message catalog. If '-' is specified, standard output shall be used. The format of the message catalog produced is unspecified.
msgfile
A pathname of a message text source file. If '-' is specified for an instance of msgfile, standard input shall be used. The format of message text source files is defined in the EXTENDED DESCRIPTION section.

STDIN

The standard input shall not be used unless a msgfile operand is specified as '-' .

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of gencat:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall not be used unless the catfile operand is specified as '-' .

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The content of a message text file shall be in the format defined as follows. Note that the fields of a message text source line are separated by a single <blank>. Any other <blank>s are considered to be part of the subsequent field.

$set n comment

This line specifies the set identifier of the following messages until the next $set or end-of-file appears. The n denotes the set identifier, which is defined as a number in the range [1, {NL_SETMAX}] (see the <limits.h> header defined in the Base Definitions volume of IEEE Std 1003.1-2001). The application shall ensure that set identifiers are presented in ascending order within a single source file, but need not be contiguous. Any string following the set identifier shall be treated as a comment. If no $set directive is specified in a message text source file, all messages shall be located in an implementation-defined default message set NL_SETD (see the <nl_types.h> header defined in the Base Definitions volume of IEEE Std 1003.1-2001).

$delset n comment

This line deletes message set n from an existing message catalog. The n denotes the set number [1, {NL_SETMAX}]. Any string following the set number shall be treated as a comment.

$ comment
A line beginning with '$' followed by a <blank> shall be treated as a comment.
m message-text

The m denotes the message identifier, which is defined as a number in the range [1, {NL_MSGMAX}] (see the <limits.h> header). The message-text shall be stored in the message catalog with the set identifier specified by the last $set directive, and with message identifier m. If the message-text is empty, and a <blank> field separator is present, an empty string shall be stored in the message catalog. If a message source line has a message number, but neither a field separator nor message-text, the existing message with that number (if any) shall be deleted from the catalog. The application shall ensure that message identifiers are in ascending order within a single set, but need not be contiguous. The application shall ensure that the length of message-text is in the range [0, {NL_TEXTMAX}] (see the <limits.h> header).

$quote n
This line specifies an optional quote character c, which can be used to surround message-text so that trailing spaces or null (empty) messages are visible in a message source line. By default, or if an empty $quote directive is supplied, no quoting of message-text shall be recognized.

Empty lines in a message text source file shall be ignored. The effects of lines starting with any character other than those defined above are implementation-defined.

Text strings can contain the special characters and escape sequences defined in the following table:
Description | Symbol | Sequence
<newline> | NL(LF) | \n
Horizontal-tab | HT | \t
<vertical-tab> | VT | \v
<backspace> | BS | \b
<carriage-return> | CR | \r
<form-feed> | FF | \f
Backslash | \ | \\
Bit pattern | ddd | \ddd

The escape sequence "\ddd" consists of backslash followed by one, two, or three octal digits, which shall be taken to specify the value of the desired character. If the character following a backslash is not one of those specified, the backslash shall be ignored.

Backslash ( '\' ) followed by a <newline> is also used to continue a string on the following line. Thus, the following two lines describe a single message string:

1 This line continues \
to the next line

which shall be equivalent to:

1 This line continues to the next line

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Message catalogs produced by gencat are binary encoded, meaning that their portability cannot be guaranteed between different types of machine. Thus, just as C programs need to be recompiled for each type of machine, so message catalogs must be recreated via gencat.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iconv() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <nl_types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fold(1p)

FOLD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fold - filter for folding lines

SYNOPSIS

fold [-bs][-w width][file...]

DESCRIPTION

The fold utility is a filter that shall fold lines from its input files, breaking the lines to have a maximum of width column positions (or bytes, if the -b option is specified). Lines shall be broken by the insertion of a <newline> such that each output line (referred to later in this section as a segment) is the maximum width possible that does not exceed the specified number of column positions (or bytes). A line shall not be broken in the middle of a character. The behavior is undefined if width is less than the number of columns any single character in the input would occupy.

If the <carriage-return>s, <backspace>s, or <tab>s are encountered in the input, and the -b option is not specified, they shall be treated specially:

<backspace>
The current count of line width shall be decremented by one, although the count never shall become negative. The fold utility shall not insert a <newline> immediately before or after any <backspace>.
<carriage-return>

The current count of line width shall be set to zero. The fold utility shall not insert a <newline> immediately before or after any <carriage-return>.

<tab>
Each <tab> encountered shall advance the column position pointer to the next tab stop. Tab stops shall be at each column position n such that n modulo 8 equals 1.

OPTIONS

The fold utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-b
Count width in bytes rather than column positions.
-s
If a segment of a line contains a <blank> within the first width column positions (or bytes), break the line after the last such <blank> meeting the width constraints. If there is no <blank> meeting the requirements, the -s option shall have no effect for that output segment of the input line.
-w width
Specify the maximum line length, in column positions (or bytes if -b is specified). The results are unspecified if width is not a positive decimal number. The default value shall be 80.

OPERANDS

The following operand shall be supported:

file
A pathname of a text file to be folded. If no file operands are specified, the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

If the -b option is specified, the input files shall be text files except that the lines are not limited to {LINE_MAX} bytes in length. If the -b option is not specified, the input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of fold:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), and for the determination of the width in column positions each character would occupy on a constant-width font output device.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be a file containing a sequence of characters whose order shall be preserved from the input files, possibly with inserted <newline>s.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All input files were processed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The cut and fold utilities can be used to create text files out of files with arbitrary line lengths. The cut utility should be used when the number of lines (or records) needs to remain constant. The fold utility should be used when the contents of long lines need to be kept contiguous.

The fold utility is frequently used to send text files to printers that truncate, rather than fold, lines wider than the printer is able to print (usually 80 or 132 column positions).

EXAMPLES

An example invocation that submits a file of possibly long lines to the printer (under the assumption that the user knows the line width of the printer to be assigned by lp):

fold -w 132 bigfile | lp

RATIONALE

Although terminal input in canonical processing mode requires the erase character (frequently set to <backspace>) to erase the previous character (not byte or column position), terminal output is not buffered and is extremely difficult, if not impossible, to parse correctly; the interpretation depends entirely on the physical device that actually displays/prints/stores the output. In all known internationalized implementations, the utilities producing output for mixed column-width output assume that a <backspace> backs up one column position and outputs enough <backspace>s to return to the start of the character when <backspace> is used to provide local line motions to support underlining and emboldening operations. Since fold without the -b option is dealing with these same constraints, <backspace> is always treated as backing up one column position rather than backing up one character.

Historical versions of the fold utility assumed 1 byte was one character and occupied one column position when written out. This is no longer always true. Since the most common usage of fold is believed to be folding long lines for output to limited-length output devices, this capability was preserved as the default case. The -b option was added so that applications could fold files with arbitrary length lines into text files that could then be processed by the standard utilities. Note that although the width for the -b option is in bytes, a line is never split in the middle of a character. (It is unspecified what happens if a width is specified that is too small to hold a single character found in the input followed by a <newline>.)

The tab stops are hardcoded to be every eighth column to meet historical practice. No new method of specifying other tab stops was invented.

FUTURE DIRECTIONS

None.

SEE ALSO

cut

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


env(1p)

ENV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

env - set the environment for command invocation

SYNOPSIS

env [-i][name=value]... [utility [argument...]]

DESCRIPTION

The env utility shall obtain the current environment, modify it according to its arguments, then invoke the utility named by the utility operand with the modified environment.

Optional arguments shall be passed to utility.

If no utility operand is specified, the resulting environment shall be written to the standard output, with one name= value pair per line.

OPTIONS

The env utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-i
Invoke utility with exactly the environment specified by the arguments; the inherited environment shall be ignored completely.

OPERANDS

The following operands shall be supported:

name=value
Arguments of the form name= value shall modify the execution environment, and shall be placed into the inherited environment before the utility is invoked.
utility
The name of the utility to be invoked. If the utility operand names any of the special built-in utilities in Special Built-In Utilities , the results are undefined.
argument
A string to pass as an argument for the invoked utility.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of env:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the location of the utility, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables. If PATH is specified as a name= value operand to env, the value given shall be used in the search for utility.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If no utility operand is specified, each name= value pair in the resulting environment shall be written in the form:

"%s=%s\n", <name>, <value>

If the utility operand is specified, the env utility shall not write to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If utility is invoked, the exit status of env shall be the exit status of utility; otherwise, the env utility shall exit with one of the following values:

0
The env utility completed successfully.
1-125
An error occurred in the env utility.
126
The utility specified by utility was found but could not be invoked.
127
The utility specified by utility could not be found.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The command, env, nice, nohup, time, and xargs utilities have been specified to use exit code 127 if an error occurs so that applications can distinguish "failure to find a utility" from "invoked utility exited with an error indication". The value 127 was chosen because it is not commonly used for other meanings; most utilities use small values for "normal error conditions" and the values above 128 can be confused with termination due to receipt of a signal. The value 126 was chosen in a similar manner to indicate that the utility could be found, but not invoked. Some scripts produce meaningful error messages differentiating the 126 and 127 cases. The distinction between exit codes 126 and 127 is based on KornShell practice that uses 127 when all attempts to exec the utility fail with [ENOENT], and uses 126 when any attempt to exec the utility fails for any other reason.

Historical implementations of the env utility use the execvp() or execlp() functions defined in the System Interfaces volume of IEEE Std 1003.1-2001 to invoke the specified utility; this provides better performance and keeps users from having to escape characters with special meaning to the shell. Therefore, shell functions, special built-ins, and built-ins that are only provided by the shell are not found.

EXAMPLES

The following command:

env -i PATH=/mybin mygrep xyz myfile

invokes the command mygrep with a new PATH value as the only entry in its environment. In this case, PATH is used to locate mygrep, which then must reside in /mybin.

RATIONALE

As with all other utilities that invoke other utilities, this volume of IEEE Std 1003.1-2001 only specifies what env does with standard input, standard output, standard error, input files, and output files. If a utility is executed, it is not constrained by the specification of input and output by env.

The -i option was added to allow the functionality of the withdrawn - option in a manner compatible with the Utility Syntax Guidelines.

Some have suggested that env is redundant since the same effect is achieved by:

name=value ... utility [ argument ... ]

The example is equivalent to env when an environment variable is being added to the environment of the command, but not when the environment is being set to the given value. The env utility also writes out the current environment if invoked without arguments. There is sufficient functionality beyond what the example provides to justify inclusion of env.

FUTURE DIRECTIONS

None.

SEE ALSO

Parameters and Variables , Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


chown(1p)

CHOWN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

chown - change the file ownership

SYNOPSIS

chown [-hR] owner[:group] file ...

chown -R [-H | -L | -P ] owner[:group] file ...

DESCRIPTION

The chown utility shall set the user ID of the file named by each file operand to the user ID specified by the owner operand.

For each file operand, or, if the -R option is used, each file encountered while walking the directory trees specified by the file operands, the chown utility shall perform actions equivalent to the chown() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:

1.
The file operand shall be used as the path argument.

2.
The user ID indicated by the owner portion of the first operand shall be used as the owner argument.

3.
If the group portion of the first operand is given, the group ID indicated by it shall be used as the group argument; otherwise, the group ownership shall not be changed.

Unless chown is invoked by a process with appropriate privileges, the set-user-ID and set-group-ID bits of a regular file shall be cleared upon successful completion; the set-user-ID and set-group-ID bits of other file types may be cleared.

OPTIONS

The chown utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-h
If the system supports user IDs for symbolic links, for each file operand that names a file of type symbolic link, chown shall attempt to set the user ID of the symbolic link. If the system supports group IDs for symbolic links, and a group ID was specified, for each file operand that names a file of type symbolic link, chown shall attempt to set the group ID of the symbolic link. If the system does not support user or group IDs for symbolic links, for each file operand that names a file of type symbolic link, chown shall do nothing more with the current file and shall go on to any remaining files.
-H
If the -R option is specified and a symbolic link referencing a file of type directory is specified on the command line, chown shall change the user ID (and group ID, if specified) of the directory referenced by the symbolic link and all files in the file hierarchy below it.
-L
If the -R option is specified and a symbolic link referencing a file of type directory is specified on the command line or encountered during the traversal of a file hierarchy, chown shall change the user ID (and group ID, if specified) of the directory referenced by the symbolic link and all files in the file hierarchy below it.
-P
If the -R option is specified and a symbolic link is specified on the command line or encountered during the traversal of a file hierarchy, chown shall change the owner ID (and group ID, if specified) of the symbolic link if the system supports this operation. The chown utility shall not follow the symbolic link to any other part of the file hierarchy.
-R
Recursively change file user and group IDs. For each file operand that names a directory, chown shall change the user ID (and group ID, if specified) of the directory and all files in the file hierarchy below it. Unless a -H, -L, or -P option is specified, it is unspecified which of these options will be used as the default.

Specifying more than one of the mutually-exclusive options -H, -L, and -P shall not be considered an error. The last option specified shall determine the behavior of the utility.

OPERANDS

The following operands shall be supported:

owner[:group]
A user ID and optional group ID to be assigned to file. The owner portion of this operand shall be a user name from the user database or a numeric user ID. Either specifies a user ID which shall be given to each file named by one of the file operands. If a numeric owner operand exists in the user database as a user name, the user ID number associated with that user name shall be used as the user ID. Similarly, if the group portion of this operand is present, it shall be a group name from the group database or a numeric group ID. Either specifies a group ID which shall be given to each file. If a numeric group operand exists in the group database as a group name, the group ID number associated with that group name shall be used as the group ID.
file
A pathname of a file whose user ID is to be modified.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of chown:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The utility executed successfully and all requested changes were made.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Only the owner of a file or the user with appropriate privileges may change the owner or group of a file.

Some implementations restrict the use of chown to a user with appropriate privileges.

EXAMPLES

None.

RATIONALE

The System V and BSD versions use different exit status codes. Some implementations used the exit status as a count of the number of errors that occurred; this practice is unworkable since it can overflow the range of valid exit status values. These are masked by specifying only 0 and >0 as exit values.

The functionality of chown is described substantially through references to functions in the System Interfaces volume of IEEE Std 1003.1-2001. In this way, there is no duplication of effort required for describing the interactions of permissions, multiple groups, and so on.

The 4.3 BSD method of specifying both owner and group was included in this volume of IEEE Std 1003.1-2001 because:

*
There are cases where the desired end condition could not be achieved using the chgrp and chown (that only changed the user ID) utilities. (If the current owner is not a member of the desired group and the desired owner is not a member of the current group, the chown() function could fail unless both owner and group are changed at the same time.)

*
Even if they could be changed independently, in cases where both are being changed, there is a 100% performance penalty caused by being forced to invoke both utilities.

The BSD syntax user[. group] was changed to user[: group] in this volume of IEEE Std 1003.1-2001 because the period is a valid character in login names (as specified by the Base Definitions volume of IEEE Std 1003.1-2001, login names consist of characters in the portable filename character set). The colon character was chosen as the replacement for the period character because it would never be allowed as a character in a user name or group name on historical implementations.

The -R option is considered by some observers as an undesirable departure from the historical UNIX system tools approach; since a tool, find, already exists to recurse over directories, there seemed to be no good reason to require other tools to have to duplicate that functionality. However, the -R option was deemed an important user convenience, is far more efficient than forking a separate process for each element of the directory hierarchy, and is in widespread historical use.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod , chgrp , the System Interfaces volume of IEEE Std 1003.1-2001, chown()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


more(1p)

MORE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

more - display files on a page-by-page basis

SYNOPSIS

more [-ceisu][-n number][-p command][-t tagstring][file ...]

DESCRIPTION

The more utility shall read files and either write them to the terminal on a page-by-page basis or filter them to standard output. If standard output is not a terminal device, all input files shall be copied to standard output in their entirety, without modification, except as specified for the -s option. If standard output is a terminal device, the files shall be written a number of lines (one screenful) at a time under the control of user commands. See the EXTENDED DESCRIPTION section.

Certain block-mode terminals do not have all the capabilities necessary to support the complete more definition; they are incapable of accepting commands that are not terminated with a <newline>. Implementations that support such terminals shall provide an operating mode to more in which all commands can be terminated with a <newline> on those terminals. This mode:

*
Shall be documented in the system documentation

*
Shall, at invocation, inform the user of the terminal deficiency that requires the <newline> usage and provide instructions on how this warning can be suppressed in future invocations

*
Shall not be required for implementations supporting only fully capable terminals

*
Shall not affect commands already requiring <newline>s

*
Shall not affect users on the capable terminals from using more as described in this volume of IEEE Std 1003.1-2001

OPTIONS

The more utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
If a screen is to be written that has no lines in common with the current screen, or more is writing its first screen, more shall not scroll the screen, but instead shall redraw each line of the screen in turn, from the top of the screen to the bottom. In addition, if more is writing its first screen, the screen shall be cleared. This option may be silently ignored on devices with insufficient terminal capabilities.
-e
By default, more shall exit immediately after writing the last line of the last file in the argument list. If the -e option is specified:
1.
If there is only a single file in the argument list and that file was completely displayed on a single screen, more shall exit immediately after writing the last line of that file.

2.
Otherwise, more shall exit only after reaching end-of-file on the last file in the argument list twice without an intervening operation. See the EXTENDED DESCRIPTION section.

-i
Perform pattern matching in searches without regard to case; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.2, Regular Expression General Requirements.
-n number
Specify the number of lines per screenful. The number argument is a positive decimal integer. The -n option shall override any values obtained from any other source.
-p command
Each time a screen from a new file is displayed or redisplayed (including as a result of more commands; for example, :p), execute the more command(s) in the command arguments in the order specified, as if entered by the user after the first screen has been displayed. No intermediate results shall be displayed (that is, if the command is a movement to a screen different from the normal first screen, only the screen resulting from the command shall be displayed.) If any of the commands fail for any reason, an informational message to this effect shall be written, and no further commands specified using the -p option shall be executed for this file.
-s
Behave as if consecutive empty lines were a single empty line.
-t tagstring
Write the screenful of the file containing the tag named by the tagstring argument. See the ctags utility. The tags feature represented by -t tagstring and the :t command is optional. It shall be provided on any system that also provides a conforming implementation of ctags; otherwise, the use of -t produces undefined results.

The filename resulting from the -t option shall be logically added as a prefix to the list of command line files, as if specified by the user. If the tag named by the tagstring argument is not found, it shall be an error, and more shall take no further action.

If the tag specifies a line number, the first line of the display shall contain the beginning of that line. If the tag specifies a pattern, the first line of the display shall contain the beginning of the matching text from the first line of the file that contains that pattern. If the line does not exist in the file or matching text is not found, an informational message to this effect shall be displayed, and more shall display the default screen as if -t had not been specified.

If both the -t tagstring and -p command options are given, the -t tagstring shall be processed first; that is, the file and starting line for the display shall be as specified by -t, and then the -p more command shall be executed. If the line (matching text) specified by the -t command does not exist (is not found), no -p more command shall be executed for this file at any time.

-u
Treat a <backspace> as a printable control character, displayed as an implementation-defined character sequence (see the EXTENDED DESCRIPTION section), suppressing backspacing and the special handling that produces underlined or standout mode text on some terminal types. Also, do not ignore a <carriage-return> at the end of a line.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If no file operands are specified, the standard input shall be used. If a file is '-' , the standard input shall be read at that point in the sequence.

STDIN

The standard input shall be used only if no file operands are specified, or if a file operand is '-' .

INPUT FILES

The input files being examined shall be text files. If standard output is a terminal, standard error shall be used to read commands from the user. If standard output is a terminal, standard error is not readable, and command input is needed, more may attempt to obtain user commands from the controlling terminal (for example, /dev/tty); otherwise, more shall terminate with an error indicating that it was unable to read user commands. If standard output is not a terminal, no error shall result if standard error cannot be opened for reading.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of more:

COLUMNS
Override the system-selected horizontal display line size. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables for valid values and results when it is unset or null.
EDITOR
Used by the v command to select an editor. See the EXTENDED DESCRIPTION section.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classes within regular expressions.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
LINES
Override the system-selected vertical screen size, used as the number of lines in a screenful. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables for valid values and results when it is unset or null. The -n option shall take precedence over the LINES variable for determining the number of lines in a screenful.
MORE
Determine a string containing options described in the OPTIONS section preceded with hyphens and <blank>-separated as on the command line. Any command line options shall be processed after those in the MORE variable, as if the command line were:

more $MORE options operands

The MORE variable shall take precedence over the TERM and LINES variables for determining the number of lines in a screenful.

TERM
Determine the name of the terminal type. If this variable is unset or null, an unspecified default terminal type is used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be used to write the contents of the input files.

STDERR

The standard error shall be used for diagnostic messages and user commands (see the INPUT FILES section), and, if standard output is a terminal device, to write a prompting string. The prompting string shall appear on the screen line below the last line of the file displayed in the current screenful. The prompt shall contain the name of the file currently being examined and shall contain an end-of-file indication and the name of the next file, if any, when prompting at the end-of-file. If an error or informational message is displayed, it is unspecified whether it is contained in the prompt. If it is not contained in the prompt, it shall be displayed and then the user shall be prompted for a continuation character, at which point another message or the user prompt may be displayed. The prompt is otherwise unspecified. It is unspecified whether informational messages are written for other user commands.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The following section describes the behavior of more when the standard output is a terminal device. If the standard output is not a terminal device, no options other than -s shall have any effect, and all input files shall be copied to standard output otherwise unmodified, at which time more shall exit without further action.

The number of lines available per screen shall be determined by the -n option, if present, or by examining values in the environment (see the ENVIRONMENT VARIABLES section). If neither method yields a number, an unspecified number of lines shall be used.

The maximum number of lines written shall be one less than this number, because the screen line after the last line written shall be used to write a user prompt and user input. If the number of lines in the screen is less than two, the results are undefined. It is unspecified whether user input is permitted to be longer than the remainder of the single line where the prompt has been written.

The number of columns available per line shall be determined by examining values in the environment (see the ENVIRONMENT VARIABLES section), with a default value as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

Lines that are longer than the display shall be folded; the length at which folding occurs is unspecified, but should be appropriate for the output device. Folding may occur between glyphs of single characters that take up multiple display columns.

When standard output is a terminal and -u is not specified, more shall treat <backspace>s and <carriage-return>s specially:

*
A character, followed first by a sequence of n <backspace>s (where n is the same as the number of column positions that the character occupies), then by n underscore characters ( '_' ), shall cause that character to be written as underlined text, if the terminal type supports that. The n underscore characters, followed first by n <backspace>s, then any character with n column positions, shall also cause that character to be written as underlined text, if the terminal type supports that.

*
A sequence of n <backspace>s (where n is the same as the number of column positions that the previous character occupies) that appears between two identical printable characters shall cause the first of those two characters to be written as emboldened text (that is, visually brighter, standout mode, or inverse-video mode), if the terminal type supports that, and the second to be discarded. Immediately subsequent occurrences of <backspace>/ character pairs for that same character shall also be discarded. (For example, the sequence "a\ba\ba\ba" is interpreted as a single emboldened 'a' .)

*
The more utility shall logically discard all other <backspace>s from the line as well as the character which precedes them, if any.

*
A <carriage-return> at the end of a line shall be ignored, rather than being written as a non-printable character, as described in the next paragraph.

It is implementation-defined how other non-printable characters are written. Implementations should use the same format that they use for the ex print command; see the OPTIONS section within the ed utility. It is unspecified whether a multi-column character shall be separated if it crosses a display line boundary; it shall not be discarded. The behavior is unspecified if the number of columns on the display is less than the number of columns any single character in the line being displayed would occupy.

When each new file is displayed (or redisplayed), more shall write the first screen of the file. Once the initial screen has been written, more shall prompt for a user command. If the execution of the user command results in a screen that has lines in common with the current screen, and the device has sufficient terminal capabilities, more shall scroll the screen; otherwise, it is unspecified whether the screen is scrolled or redrawn.

For all files but the last (including standard input if no file was specified, and for the last file as well, if the -e option was not specified), when more has written the last line in the file, more shall prompt for a user command. This prompt shall contain the name of the next file as well as an indication that more has reached end-of-file. If the user command is f, <control>-F, <space>, j, <newline>, d, <control>-D, or s, more shall display the next file. Otherwise, if displaying the last file, more shall exit. Otherwise, more shall execute the user command specified.

Several of the commands described in this section display a previous screen from the input stream. In the case that text is being taken from a non-rewindable stream, such as a pipe, it is implementation-defined how much backwards motion is supported. If a command cannot be executed because of a limitation on backwards motion, an error message to this effect shall be displayed, the current screen shall not change, and the user shall be prompted for another command.

If a command cannot be performed because there are insufficient lines to display, more shall alert the terminal. If a command cannot be performed because there are insufficient lines to display or a / command fails: if the input is the standard input, the last screen in the file may be displayed; otherwise, the current file and screen shall not change, and the user shall be prompted for another command.

The interactive commands in the following sections shall be supported. Some commands can be preceded by a decimal integer, called count in the following descriptions. If not specified with the command, count shall default to 1. In the following descriptions, pattern is a basic regular expression, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions. The term "examine" is historical usage meaning "open the file for viewing''; for example, more foo would be expressed as examining file foo.

In the following descriptions, unless otherwise specified, line is a line in the more display, not a line from the file being examined.

In the following descriptions, the current position refers to two things:

1.
The position of the current line on the screen

2.
The line number (in the file) of the current line on the screen

Usually, the line on the screen corresponding to the current position is the third line on the screen. If this is not possible (there are fewer than three lines to display or this is the first page of the file, or it is the last page of the file), then the current position is either the first or last line on the screen as described later.

Help

Synopsis:

h

Write a summary of these commands and other implementation-defined commands. The behavior shall be as if the more utility were executed with the -e option on a file that contained the summary information. The user shall be prompted as described earlier in this section when end-of-file is reached. If the user command is one of those specified to continue to the next file, more shall return to the file and screen state from which the h command was executed.

Scroll Forward One Screenful

Synopsis:

[count]f
[count]<control>-F

Scroll forward count lines, with a default of one screenful. If count is more than the screen size, only the final screenful shall be written.

Scroll Backward One Screenful

Synopsis:

[count]b
[count]<control>-B

Scroll backward count lines, with a default of one screenful (see the -n option). If count is more than the screen size, only the final screenful shall be written.

Scroll Forward One Line

Synopsis:

[count]<space>
[count]j
[count]<newline>

Scroll forward count lines. The default count for the <space> shall be one screenful; for j and <newline>, one line. The entire count lines shall be written, even if count is more than the screen size.

Scroll Backward One Line

Synopsis:

[count]k

Scroll backward count lines. The entire count lines shall be written, even if count is more than the screen size.

Scroll Forward One Half Screenful

Synopsis:

[count]d
[count]<control>-D

Scroll forward count lines, with a default of one half of the screen size. If count is specified, it shall become the new default for subsequent d, <control>-D, and u commands.

Skip Forward One Line

Synopsis:

[count]s

Display the screenful beginning with the line count lines after the last line on the current screen. If count would cause the current position to be such that less than one screenful would be written, the last screenful in the file shall be written.

Scroll Backward One Half Screenful

Synopsis:

[count]u
[count]<control>-U

Scroll backward count lines, with a default of one half of the screen size. If count is specified, it shall become the new default for subsequent d, <control>-D, u, and <control>-U commands. The entire count lines shall be written, even if count is more than the screen size.

Go to Beginning of File

Synopsis:

[count]g

Display the screenful beginning with line count.

Go to End-of-File

Synopsis:

[count]G

If count is specified, display the screenful beginning with the line count. Otherwise, display the last screenful of the file.

Refresh the Screen

Synopsis:

r
<control>-L

Refresh the screen.

Discard and Refresh

Synopsis:

R

Refresh the screen, discarding any buffered input. If the current file is non-seekable, buffered input shall not be discarded and the R command shall be equivalent to the r command.

Mark Position

Synopsis:

mletter

Mark the current position with the letter named by letter, where letter represents the name of one of the lowercase letters of the portable character set. When a new file is examined, all marks may be lost.

Return to Mark

Synopsis:

'letter

Return to the position that was previously marked with the letter named by letter, making that line the current position.

Return to Previous Position

Synopsis:

''

Return to the position from which the last large movement command was executed (where a "large movement" is defined as any movement of more than a screenful of lines). If no such movements have been made, return to the beginning of the file.

Search Forward for Pattern

Synopsis:

[count]/[!]pattern<newline>

Display the screenful beginning with the countth line containing the pattern. The search shall start after the first line currently displayed. The null regular expression ( '/' followed by a <newline>) shall repeat the search using the previous regular expression, with a default count. If the character '!' is included, the matching lines shall be those that do not contain the pattern. If no match is found for the pattern, a message to that effect shall be displayed.

Search Backward for Pattern

Synopsis:

[count]?[!]pattern<newline>

Display the screenful beginning with the countth previous line containing the pattern. The search shall start on the last line before the first line currently displayed. The null regular expression ( '?' followed by a <newline>) shall repeat the search using the previous regular expression, with a default count. If the character '!' is included, matching lines shall be those that do not contain the pattern. If no match is found for the pattern, a message to that effect shall be displayed.

Repeat Search

Synopsis:

[count]n

Repeat the previous search for countth line containing the last pattern (or not containing the last pattern, if the previous search was "/!" or "?!" ).

Repeat Search in Reverse

Synopsis:

[count]N

Repeat the search in the opposite direction of the previous search for the countth line containing the last pattern (or not containing the last pattern, if the previous search was "/!" or "?!" ).

Examine New File

Synopsis:

:e [filename]<newline>

Examine a new file. If the filename argument is not specified, the current file (see the :n and :p commands below) shall be re-examined. The filename shall be subjected to the process of shell word expansions (see Word Expansions ); if more than a single pathname results, the effects are unspecified. If filename is a number sign ( '#' ), the previously examined file shall be re-examined. If filename is not accessible for any reason (including that it is a non-seekable file), an error message to this effect shall be displayed and the current file and screen shall not change.

Examine Next File

Synopsis:

[count]:n

Examine the next file. If a number count is specified, the countth next file shall be examined. If filename refers to a non-seekable file, the results are unspecified.

Examine Previous File

Synopsis:

[count]:p

Examine the previous file. If a number count is specified, the countth previous file shall be examined. If filename refers to a non-seekable file, the results are unspecified.

Go to Tag

Synopsis:

:t tagstring<newline>

If the file containing the tag named by the tagstring argument is not the current file, examine the file, as if the :e command was executed with that file as the argument. Otherwise, or in addition, display the screenful beginning with the tag, as described for the -t option (see the OPTIONS section). If the ctags utility is not supported by the system, the use of :t produces undefined results.

Invoke Editor

Synopsis:

v

Invoke an editor to edit the current file being examined. If standard input is being examined, the results are unspecified. The name of the editor shall be taken from the environment variable EDITOR , or shall default to vi. If the last pathname component in EDITOR is either vi or ex, the editor shall be invoked with a -c linenumber command line argument, where linenumber is the line number of the file line containing the display line currently displayed as the first line of the screen. It is implementation-defined whether line-setting options are passed to editors other than vi and ex.

When the editor exits, more shall resume with the same file and screen as when the editor was invoked.

Display Position

Synopsis:

=
<control>-G

Write a message for which the information references the first byte of the line after the last line of the file on the screen. This message shall include the name of the file currently being examined, its number relative to the total number of files there are to examine, the line number in the file, the byte number and the total bytes in the file, and what percentage of the file precedes the current position. If more is reading from standard input, or the file is shorter than a single screen, the line number, the byte number, the total bytes, and the percentage need not be written.

Quit

Synopsis:

q
:q
ZZ

Exit more.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If an error is encountered accessing a file when using the :n command, more shall attempt to examine the next file in the argument list, but the final exit status shall be affected. If an error is encountered accessing a file via the :p command, more shall attempt to examine the previous file in the argument list, but the final exit status shall be affected. If an error is encountered accessing a file via the :e command, more shall remain in the current file and the final exit status shall not be affected.

The following sections are informative.

APPLICATION USAGE

When the standard output is not a terminal, only the -s filter-modification option is effective. This is based on historical practice. For example, a typical implementation of man pipes its output through more -s to squeeze excess white space for terminal users. When man is piped to lp, however, it is undesirable for this squeezing to happen.

EXAMPLES

The -p allows arbitrary commands to be executed at the start of each file. Examples are:

more -p G file1 file2

Examine each file starting with its last screenful.

more -p 100 file1 file2

Examine each file starting with line 100 in the current position (usually the third line, so line 98 would be the first line written).

more -p /100 file1 file2

Examine each file starting with the first line containing the string "100" in the current position

RATIONALE

The more utility, available in BSD and BSD-derived systems, was chosen as the prototype for the POSIX file display program since it is more widely available than either the public-domain program less or than pg, a pager provided in System V. The 4.4 BSD more is the model for the features selected; it is almost fully upwards-compatible from the 4.3 BSD version in wide use and has become more amenable for vi users. Several features originally derived from various file editors, found in both less and pg, have been added to this volume of IEEE Std 1003.1-2001 as they have proved extremely popular with users.

There are inconsistencies between more and vi that result from historical practice. For example, the single-character commands h, f, b, and <space> are screen movers in more, but cursor movers in vi. These inconsistencies were maintained because the cursor movements are not applicable to more and the powerful functionality achieved without the use of the control key justifies the differences.

The tags interface has been included in a program that is not a text editor because it promotes another degree of consistent operation with vi. It is conceivable that the paging environment of more would be superior for browsing source code files in some circumstances.

The operating mode referred to for block-mode terminals effectively adds a <newline> to each Synopsis line that currently has none. So, for example, d <newline> would page one screenful. The mode could be triggered by a command line option, environment variable, or some other method. The details are not imposed by this volume of IEEE Std 1003.1-2001 because there are so few systems known to support such terminals. Nevertheless, it was considered that all systems should be able to support more given the exception cited for this small community of terminals because, in comparison to vi, the cursor movements are few and the command set relatively amenable to the optional <newline>s.

Some versions of more provide a shell escaping mechanism similar to the ex ! command. The standard developers did not consider that this was necessary in a paginator, particularly given the wide acceptance of multiple window terminals and job control features. (They chose to retain such features in the editors and mailx because the shell interaction also gives an opportunity to modify the editing buffer, which is not applicable to more.)

The -p (position) option replaces the + command because of the Utility Syntax Guidelines. In early proposals, it took a pattern argument, but historical less provided the more general facility of a command. It would have been desirable to use the same -c as ex and vi, but the letter was already in use.

The text stating "from a non-rewindable stream ... implementations may limit the amount of backwards motion supported" would allow an implementation that permitted no backwards motion beyond text already on the screen. It was not possible to require a minimum amount of backwards motion that would be effective for all conceivable device types. The implementation should allow the user to back up as far as possible, within device and reasonable memory allocation constraints.

Historically, non-printable characters were displayed using the ARPA standard mappings, which are as follows:

1.
Printable characters are left alone.

2.
Control characters less than \177 are represented as followed by the character offset from the '@' character in the ASCII map; for example, \007 is represented as 'G' .

3.
\177 is represented as followed by '?' .

The display of characters having their eighth bit set was less standard. Existing implementations use hex (0x00), octal (\000), and a meta-bit display. (The latter displayed characters with their eighth bit set as the two characters "M-" , followed by the seven-bit display as described previously.) The latter probably has the best claim to historical practice because it was used with the -v option of 4 BSD and 4 BSD-derived versions of the cat utility since 1980.

No specific display format is required by IEEE Std 1003.1-2001. Implementations are encouraged to conform to historic practice in the absence of any strong reason to diverge.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , ctags , ed , ex , vi

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


get(1p)

GET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

get - get a version of an SCCS file (DEVELOPMENT)

SYNOPSIS

get [-begkmnlLpst][-c cutoff][-i list][-r SID][-x list] file...

DESCRIPTION

The get utility shall generate a text file from each named SCCS file according to the specifications given by its options.

The generated text shall normally be written into a file called the g-file whose name is derived from the SCCS filename by simply removing the leading "s." .

OPTIONS

The get utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-r SID
Indicate the SCCS Identification String (SID) of the version (delta) of an SCCS file to be retrieved. The table shows, for the most useful cases, what version of an SCCS file is retrieved (as well as the SID of the version to be eventually created by delta if the -e option is also used), as a function of the SID specified.
-c cutoff
Indicate the cutoff date-time, in the form:

YY[MM[DD[HH[MM[SS]]]]]

For the YY component, values in the range [69,99] shall refer to years 1969 to 1999 inclusive, and values in the range [00,68] shall refer to years 2000 to 2068 inclusive.

Note:
It is expected that in a future version of IEEE Std 1003.1-2001 the default century inferred from a 2-digit year will change. (This would apply to all commands accepting a 2-digit year as input.)

No changes (deltas) to the SCCS file that were created after the specified cutoff date-time shall be included in the generated text file. Units omitted from the date-time default to their maximum possible values; for example, -c 7502 is equivalent to -c 750228235959.

Any number of non-numeric characters may separate the various 2-digit pieces of the cutoff date-time. This feature allows the user to specify a cutoff date in the form: -c "77/2/2 9:22:25".

-e
Indicate that the get is for the purpose of editing or making a change (delta) to the SCCS file via a subsequent use of delta. The -e option used in a get for a particular version (SID) of the SCCS file shall prevent further get commands from editing on the same SID until delta is executed or the j (joint edit) flag is set in the SCCS file. Concurrent use of get -e for different SIDs is always allowed.

If the g-file generated by get with a -e option is accidentally ruined in the process of editing, it may be regenerated by re-executing the get command with the -k option in place of the -e option.

SCCS file protection specified via the ceiling, floor, and authorized user list stored in the SCCS file shall be enforced when the -e option is used.

-b
Use with the -e option to indicate that the new delta should have an SID in a new branch as shown in the table below. This option shall be ignored if the b flag is not present in the file or if the retrieved delta is not a leaf delta. (A leaf delta is one that has no successors on the SCCS file tree.)
Note:
A branch delta may always be created from a non-leaf delta.

-i list
Indicate a list of deltas to be included (forced to be applied) in the creation of the generated file. The list has the following syntax:

<list> ::= <range> | <list> , <range>
<range> ::= SID | SID - SID

SID, the SCCS Identification of a delta, may be in any form shown in the "SID Specified" column of the table in the EXTENDED DESCRIPTION section, except that the result of supplying a partial SID is unspecified. A diagnostic message shall be written if the first SID in the range is not an ancestor of the second SID in the range.

-x list
Indicate a list of deltas to be excluded (forced not to be applied) in the creation of the generated file. See the -i option for the list format.
-k
Suppress replacement of identification keywords (see below) in the retrieved text by their value. The -k option shall be implied by the -e option.
-l
Write a delta summary into an l-file.
-L
Write a delta summary to standard output. All informative output that normally is written to standard output shall be written to standard error instead, unless the -s option is used, in which case it shall be suppressed.
-p
Write the text retrieved from the SCCS file to the standard output. No g-file shall be created. All informative output that normally goes to the standard output shall go to standard error instead, unless the -s option is used, in which case it shall disappear.
-s
Suppress all informative output normally written to standard output. However, fatal error messages (which shall always be written to the standard error) shall remain unaffected.
-m
Precede each text line retrieved from the SCCS file by the SID of the delta that inserted the text line in the SCCS file. The format shall be:

"%s\t%s", <SID>, <text line>
-n
Precede each generated text line with the %M% identification keyword value (see below). The format shall be:

"%s\t%s", <%M% value>, <text line>

When both the -m and -n options are used, the <text line> shall be replaced by the -m option-generated format.

-g
Suppress the actual retrieval of text from the SCCS file. It is primarily used to generate an l-file, or to verify the existence of a particular SID.
-t
Use to access the most recently created (top) delta in a given release (for example, -r 1), or release and level (for example, -r 1.2).

OPERANDS

The following operands shall be supported:

file
A pathname of an existing SCCS file or a directory. If file is a directory, the get utility shall behave as though each file in the directory were specified as a named file, except that non-SCCS files (last component of the pathname does not begin with s.) and unreadable files shall be silently ignored.

If exactly one file operand appears, and it is '-' , the standard input shall be read; each line of the standard input is taken to be the name of an SCCS file to be processed. Non-SCCS files and unreadable files shall be silently ignored.

STDIN

The standard input shall be a text file used only if the file operand is specified as '-' . Each line of the text file shall be interpreted as an SCCS pathname.

INPUT FILES

The SCCS files shall be files of an unspecified format.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of get:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error, and informative messages written to standard output (or standard error, if the -p option is used).
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone in which the times and dates written in the SCCS file are evaluated. If the TZ variable is unset or NULL, an unspecified system default timezone is used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

For each file processed, get shall write to standard output the SID being accessed and the number of lines retrieved from the SCCS file, in the following format:

"%s\n%d lines\n", <SID>, <number of lines>

If the -e option is used, the SID of the delta to be made shall appear after the SID accessed and before the number of lines generated, in the POSIX locale:

"%s\nnew delta %s\n%d lines\n", <SID accessed>,
    <SID to be made>, <number of lines>

If there is more than one named file or if a directory or standard input is named, each pathname shall be written before each of the lines shown in one of the preceding formats:

"\n%s:\n", <pathname>

If the -L option is used, a delta summary shall be written following the format specified below for l-files.

If the -i option is used, included deltas shall be listed following the notation, in the POSIX locale:

"Included:\n"

If the -x option is used, excluded deltas shall be listed following the notation, in the POSIX locale:

"Excluded:\n"

If the -p or -L options are specified, the standard output shall consist of the text retrieved from the SCCS file.

STDERR

The standard error shall be used only for diagnostic messages, except if the -p or -L options are specified, it shall include all informative messages normally sent to standard output.

OUTPUT FILES

Several auxiliary files may be created by get. These files are known generically as the g-file, l-file, p-file, and z-file. The letter before the hyphen is called the tag. An auxiliary filename shall be formed from the SCCS filename: the application shall ensure that the last component of all SCCS filenames is of the form s. module-name; the auxiliary files shall be named by replacing the leading s with the tag. The g-file shall be an exception to this scheme: the g-file is named by removing the s. prefix. For example, for s.xyz.c, the auxiliary filenames would be xyz.c, l.xyz.c, p.xyz.c, and z.xyz.c, respectively.

The g-file, which contains the generated text, shall be created in the current directory (unless the -p option is used). A g-file shall be created in all cases, whether or not any lines of text were generated by the get. It shall be owned by the real user. If the -k option is used or implied, the g-file shall be writable by the owner only (read-only for everyone else); otherwise, it shall be read-only. Only the real user need have write permission in the current directory.

The l-file shall contain a table showing which deltas were applied in generating the retrieved text. The l-file shall be created in the current directory if the -l option is used; it shall be read-only and it is owned by the real user. Only the real user need have write permission in the current directory.

Lines in the l-file shall have the following format:

"%c%c%c %s\t%s %s\n", <code1>, <code2>, <code3>,
    <SID>, <date-time>, <login>

where the entries are:

<code1>
A <space> if the delta was applied; '*' otherwise.
<code2>
A <space> if the delta was applied or was not applied and ignored; '*' if the delta was not applied and was not ignored.
<code3>
A character indicating a special reason why the delta was or was not applied:
I
Included.
X
Excluded.
C
Cut off (by a -c option).

<date-time>
Date and time (using the format of the date utility's %y / %m / %d %T conversion specification format) of creation.
<login>
Login name of person who created delta.

The comments and MR data shall follow on subsequent lines, indented one <tab>. A blank line shall terminate each entry.

The p-file shall be used to pass information resulting from a get with a -e option along to delta. Its contents shall also be used to prevent a subsequent execution of get with a -e option for the same SID until delta is executed or the joint edit flag, j, is set in the SCCS file. The p-file shall be created in the directory containing the SCCS file and the application shall ensure that the effective user has write permission in that directory. It shall be writable by owner only, and owned by the effective user. Each line in the p-file shall have the following format:

"%s %s %s %s%s%s\n", <g-file SID>,
    <SID of new delta>, <login-name of real user>,
    <date-time>, <i-value>, <x-value>

where <i-value> uses the format "" if no -i option was specified, and shall use the format:

" -i%s", <-i option option-argument>

if a -i option was specified and <x-value> uses the format "" if no -x option was specified, and shall use the format:

" -x%s", <-x option option-argument>

if a -x option was specified. There can be an arbitrary number of lines in the p-file at any time; no two lines shall have the same new delta SID.

The z-file shall serve as a lock-out mechanism against simultaneous updates. Its contents shall be the binary process ID of the command (that is, get) that created it. The z-file shall be created in the directory containing the SCCS file for the duration of get. The same protection restrictions as those for the p-file shall apply for the z-file. The z-file shall be created read-only.

EXTENDED DESCRIPTION

Determination of SCCS Identification String |  |  |
SID* | -b Keyletter | Other | SID | SID of Delta
Specified | Used& | Conditions | Retrieved | to be Created
none&& | no | R defaults to mR | mR.mL | mR.(mL+1)
none&& | yes | R defaults to mR | mR.mL | mR.mL.(mB+1).1
R | no | R > mR | mR.mL | R.1***
R | no | R = mR | mR.mL | mR.(mL+1)
R | yes | R > mR | mR.mL | mR.mL.(mB+1).1
R | yes | R = mR | mR.mL | mR.mL.(mB+1).1
R | - | R < mR and R does not exist | hR.mL** | hR.mL.(mB+1).1
R | - | Trunk successor in release > R and R exists | R.mL | R.mL.(mB+1).1
R.L | no | No trunk successor | R.L | R.(L+1)
R.L | yes | No trunk successor | R.L | R.L.(mB+1).1
R.L | - | Trunk successor in release >= R | R.L | R.L.(mB+1).1
R.L.B | no | No branch successor | R.L.B.mS | R.L.B.(mS+1)
R.L.B | yes | No branch successor | R.L.B.mS | R.L.(mB+1).1
R.L.B.S | no | No branch successor | R.L.B.S | R.L.B.(S+1)
R.L.B.S | yes | No branch successor | R.L.B.S | R.L.(mB+1).1
R.L.B.S | - | Branch successor | R.L.B.S | R.L.(mB+1).1
*
R, L, B, and S are the release, level, branch, and sequence components of the SID, respectively; m means maximum. Thus, for example, R.mL means "the maximum level number within release R''; R.L.(mB+1).1 means "the first sequence number on the new branch (that is, maximum branch number plus one) of level L within release R". Note that if the SID specified is of the form R.L, R.L.B, or R.L.B.S, each of the specified components shall exist.
**
hR is the highest existing release that is lower than the specified, nonexistent, release R.
***
This is used to force creation of the first delta in a new release.
&
The -b option is effective only if the b flag is present in the file. An entry of '-' means "irrelevant".
&&
This case applies if the d (default SID) flag is not present in the file. If the d flag is present in the file, then the SID obtained from the d flag is interpreted as if it had been specified on the command line. Thus, one of the other cases in this table applies.

System Date and Time

When a g-file is generated, the creation time of deltas in the SCCS file may be taken into account. If any of these times are apparently in the future, the behavior is unspecified.

Identification Keywords

Identifying information shall be inserted into the text retrieved from the SCCS file by replacing identification keywords with their value wherever they occur. The following keywords may be used in the text stored in an SCCS file:

%M%
Module name: either the value of the m flag in the file, or if absent, the name of the SCCS file with the leading s. removed.
%I%
SCCS identification (SID) (%R%.%L% or %R%.%L%.%B%.%S%) of the retrieved text.
%R%
Release.
%L%
Level.
%B%
Branch.
%S%
Sequence.
%D%
Current date (YY/MM/DD).
%H%
Current date (MM/DD/YY).
%T%
Current time (HH:MM:SS).
%E%
Date newest applied delta was created (YY/MM/DD).
%G%
Date newest applied delta was created (MM/DD/YY).
%U%
Time newest applied delta was created (HH:MM:SS).
%Y%
Module type: value of the t flag in the SCCS file.
%F%
SCCS filename.
%P%
SCCS absolute pathname.
%Q%
The value of the q flag in the file.
%C%
Current line number. This keyword is intended for identifying messages output by the program, such as "this should not have happened" type errors. It is not intended to be used on every line to provide sequence numbers.
%Z%
The four-character string "@(#)" recognizable by what.
%W%
A shorthand notation for constructing what strings:

%W%=%Z%%M%<tab>%I%
%A%
Another shorthand notation for constructing what strings:

%A%=%Z%%Y%%M%%I%%Z%

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Problems can arise if the system date and time have been modified (for example, put forward and then back again, or unsynchronized clocks across a network) and can also arise when different values of the TZ environment variable are used.

Problems of a similar nature can also arise for the operation of the delta utility, which compares the previous file body against the working file as part of its normal operation.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

The -lp option may be withdrawn in a future version.

SEE ALSO

admin , delta , prs , what

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


unalias(1p)

UNALIAS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unalias - remove alias definitions

SYNOPSIS

unalias alias-name...

unalias -a

DESCRIPTION

The unalias utility shall remove the definition for each alias name specified. See Alias Substitution . The aliases shall be removed from the current shell execution environment; see Shell Execution Environment .

OPTIONS

The unalias utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-a
Remove all alias definitions from the current shell execution environment.

OPERANDS

The following operand shall be supported:

alias-name
The name of an alias to be removed.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of unalias:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
One of the alias-name operands specified did not represent a valid alias definition, or an error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since unalias affects the current shell execution environment, it is generally provided as a shell regular built-in.

EXAMPLES

None.

RATIONALE

The unalias description is based on that from historical KornShell implementations. Known differences exist between that and the C shell. The KornShell version was adopted to be consistent with all the other KornShell features in this volume of IEEE Std 1003.1-2001, such as command line editing.

The -a option is the equivalent of the unalias * form of the C shell and is provided to address security concerns about unknown aliases entering the environment of a user (or application) through the allowable implementation-defined predefined alias route or as a result of an ENV file. (Although unalias could be used to simplify the "secure" shell script shown in the command rationale, it does not obviate the need to quote all command names. An initial call to unalias -a would have to be quoted in case there was an alias for unalias.)

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , alias

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tput(1p)

TPUT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tput - change terminal characteristics

SYNOPSIS

tput [-T type] operand...

DESCRIPTION

The tput utility shall display terminal-dependent information. The manner in which this information is retrieved is unspecified. The information displayed shall clear the terminal screen, initialize the user's terminal, or reset the user's terminal, depending on the operand given. The exact consequences of displaying this information are unspecified.

OPTIONS

The tput utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-T type
Indicate the type of terminal. If this option is not supplied and the TERM variable is unset or null, an unspecified default terminal type shall be used. The setting of type shall take precedence over the value in TERM .

OPERANDS

The following strings shall be supported as operands by the implementation in the POSIX locale:

clear
Display the clear-screen sequence.
init
Display the sequence that initializes the user's terminal in an implementation-defined manner.
reset
Display the sequence that resets the user's terminal in an implementation-defined manner.

If a terminal does not support any of the operations described by these operands, this shall not be considered an error condition.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of tput:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TERM
Determine the terminal type. If this variable is unset or null, and if the -T option is not specified, an unspecified default terminal type shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If standard output is a terminal device, it may be used for writing the appropriate sequence to clear the screen or reset or initialize the terminal. If standard output is not a terminal device, undefined results occur.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The requested string was written successfully.
1
Unspecified.
2
Usage error.
3
No information is available about the specified terminal type.
4
The specified operand is invalid.
>4
An error occurred.

CONSEQUENCES OF ERRORS

If one of the operands is not available for the terminal, tput continues processing the remaining operands.

The following sections are informative.

APPLICATION USAGE

The difference between resetting and initializing a terminal is left unspecified, as they vary greatly based on hardware types. In general, resetting is a more severe action.

Some terminals use control characters to perform the stated functions, and on such terminals it might make sense to use tput to store the initialization strings in a file or environment variable for later use. However, because other terminals might rely on system calls to do this work, the standard output cannot be used in a portable manner, such as the following non-portable constructs:

ClearVar=`tput clear`
tput reset | mailx -s "Wake Up" ddg

EXAMPLES

1.
Initialize the terminal according to the type of terminal in the environmental variable TERM . This command can be included in a .profile file.

tput init

2.
Reset a 450 terminal.

tput -T 450 reset

RATIONALE

The list of operands was reduced to a minimum for the following reasons:

*
The only features chosen were those that were likely to be used by human users interacting with a terminal.

*
Specifying the full terminfo set was not considered desirable, but the standard developers did not want to select among operands.

*
This volume of IEEE Std 1003.1-2001 does not attempt to provide applications with sophisticated terminal handling capabilities, as that falls outside of its assigned scope and intersects with the responsibilities of other standards bodies.

The difference between resetting and initializing a terminal is left unspecified as this varies greatly based on hardware types. In general, resetting is a more severe action.

The exit status of 1 is historically reserved for finding out if a Boolean operand is not set. Although the operands were reduced to a minimum, the exit status of 1 should still be reserved for the Boolean operands, for those sites that wish to support them.

FUTURE DIRECTIONS

None.

SEE ALSO

stty , tabs

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


logname(1p)

LOGNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

logname - return the user's login name

SYNOPSIS

logname

DESCRIPTION

The logname utility shall write the user's login name to standard output. The login name shall be the string that would be returned by the getlogin() function defined in the System Interfaces volume of IEEE Std 1003.1-2001. Under the conditions where the getlogin() function would fail, the logname utility shall write a diagnostic message to standard error and exit with a non-zero exit status.

OPTIONS

None.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of logname:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The logname utility output shall be a single line consisting of the user's login name:

"%s\n", <login name>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The logname utility explicitly ignores the LOGNAME environment variable because environment changes could produce erroneous results.

EXAMPLES

None.

RATIONALE

The passwd file is not listed as required because the implementation may have other means of mapping login names.

FUTURE DIRECTIONS

None.

SEE ALSO

id , who , the System Interfaces volume of IEEE Std 1003.1-2001, getlogin()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


trap(1p)

TRAP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

trap - trap signals

SYNOPSIS

trap [action condition ...]

DESCRIPTION

If action is '-' , the shell shall reset each condition to the default value. If action is null ( "" ), the shell shall ignore each specified condition if it arises. Otherwise, the argument action shall be read and executed by the shell when one of the corresponding conditions arises. The action of trap shall override a previous action (either default action or one explicitly set). The value of "$?" after the trap action completes shall be the value it had before trap was invoked.

The condition can be EXIT, 0 (equivalent to EXIT), or a signal specified using a symbolic name, without the SIG prefix, as listed in the tables of signal names in the <signal.h> header defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers; for example, HUP, INT, QUIT, TERM. Implementations may permit names with the SIG prefix or ignore case in signal names as an extension. Setting a trap for SIGKILL or SIGSTOP produces undefined results.

The environment in which the shell executes a trap on EXIT shall be identical to the environment immediately after the last command executed before the trap on EXIT was taken.

Each time trap is invoked, the action argument shall be processed in a manner equivalent to:

eval action

Signals that were ignored on entry to a non-interactive shell cannot be trapped or reset, although no error need be reported when attempting to do so. An interactive shell may reset or catch signals ignored on entry. Traps shall remain in place for a given shell until explicitly changed with another trap command.

When a subshell is entered, traps that are not being ignored are set to the default actions. This does not imply that the trap command cannot be used within the subshell to set new traps.

The trap command with no arguments shall write to standard output a list of commands associated with each condition. The format shall be:

"trap -- %s %s ...\n", <action>, <condition> ...

The shell shall format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same trapping results. For example:

save_traps=$(trap)
...
eval "$save_traps"

XSI-conformant systems also allow numeric signal numbers for the conditions corresponding to the following signal names:
Signal Number | Signal Name
1 | SIGHUP
2 | SIGINT
3 | SIGQUIT
6 | SIGABRT
9 | SIGKILL
14 | SIGALRM
15 | SIGTERM

The trap special built-in shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If the trap name or number is invalid, a non-zero exit status shall be returned; otherwise, zero shall be returned. For both interactive and non-interactive shells, invalid signal names or numbers shall not be considered a syntax error and do not cause the shell to abort.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Write out a list of all traps and actions:

trap

Set a trap so the logout utility in the directory referred to by the HOME environment variable executes when the shell terminates:

trap '$HOME/logout' EXIT

or:

trap '$HOME/logout' 0

Unset traps on INT, QUIT, TERM, and EXIT:

trap - INT QUIT TERM EXIT

RATIONALE

Implementations may permit lowercase signal names as an extension. Implementations may also accept the names with the SIG prefix; no known historical shell does so. The trap and kill utilities in this volume of IEEE Std 1003.1-2001 are now consistent in their omission of the SIG prefix for signal names. Some kill implementations do not allow the prefix, and kill -l lists the signals without prefixes.

Trapping SIGKILL or SIGSTOP is syntactically accepted by some historical implementations, but it has no effect. Portable POSIX applications cannot attempt to trap these signals.

The output format is not historical practice. Since the output of historical trap commands is not portable (because numeric signal values are not portable) and had to change to become so, an opportunity was taken to format the output in a way that a shell script could use to save and then later reuse a trap if it wanted.

The KornShell uses an ERR trap that is triggered whenever set -e would cause an exit. This is allowable as an extension, but was not mandated, as other shells have not used it.

The text about the environment for the EXIT trap invalidates the behavior of some historical versions of interactive shells which, for example, close the standard input before executing a trap on 0. For example, in some historical interactive shell sessions the following trap on 0 would always print "--" :

trap 'read foo; echo "-$foo-"' 0

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nice(1p)

NICE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nice - invoke a utility with an altered nice value

SYNOPSIS

nice [-n increment] utility [argument...]

DESCRIPTION

The nice utility shall invoke a utility, requesting that it be run with a different nice value (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.239, Nice Value). With no options and only if the user has appropriate privileges, the executed utility shall be run with a nice value that is some implementation-defined quantity less than or equal to the nice value of the current process. If the user lacks appropriate privileges to affect the nice value in the requested manner, the nice utility shall not affect the nice value; in this case, a warning message may be written to standard error, but this shall not prevent the invocation of utility or affect the exit status.

OPTIONS

The nice utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option is supported:

-n increment
A positive or negative decimal integer which shall have the same effect on the execution of the utility as if the utility had called the nice() function with the numeric value of the increment option-argument.

OPERANDS

The following operands shall be supported:

utility
The name of a utility that is to be invoked. If the utility operand names any of the special built-in utilities in Special Built-In Utilities , the results are undefined.
argument
Any string to be supplied as an argument when invoking the utility named by the utility operand.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of nice:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the search path used to locate the utility to be invoked. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If utility is invoked, the exit status of nice shall be the exit status of utility; otherwise, the nice utility shall exit with one of the following values:

1-125
An error occurred in the nice utility.
126
The utility specified by utility was found but could not be invoked.
127
The utility specified by utility could not be found.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The only guaranteed portable uses of this utility are:

nice utility

Run utility with the default lower nice value.

nice -n <positive integer> utility

Run utility with a lower nice value.

On some implementations they have no discernible effect on the invoked utility and on some others they are exactly equivalent.

Historical systems have frequently supported the <positive integer> up to 20. Since there is no error penalty associated with guessing a number that is too high, users without access to the system conformance document (to see what limits are actually in place) could use the historical 1 to 20 range or attempt to use very large numbers if the job should be truly low priority.

The nice value of a process can be displayed using the command:

ps -o nice

The command, env, nice, nohup, time, and xargs utilities have been specified to use exit code 127 if an error occurs so that applications can distinguish "failure to find a utility" from "invoked utility exited with an error indication". The value 127 was chosen because it is not commonly used for other meanings; most utilities use small values for "normal error conditions" and the values above 128 can be confused with termination due to receipt of a signal. The value 126 was chosen in a similar manner to indicate that the utility could be found, but not invoked. Some scripts produce meaningful error messages differentiating the 126 and 127 cases. The distinction between exit codes 126 and 127 is based on KornShell practice that uses 127 when all attempts to exec the utility fail with [ENOENT], and uses 126 when any attempt to exec the utility fails for any other reason.

EXAMPLES

None.

RATIONALE

Due to the text about the limits of the nice value being implementation-defined, nice is not actually required to change the nice value of the executed command; the limits could be zero differences from the system default, although the implementor is required to document this fact in the conformance document.

The 4.3 BSD version of nice does not check whether increment is a valid decimal integer. The command nice -x utility, for example, would be treated the same as the command nice --1 utility. If the user does not have appropriate privileges, this results in a "permission denied" error. This is considered a bug.

When a user without appropriate privileges gives a negative increment, System V treats it like the command nice -0 utility, while 4.3 BSD writes a "permission denied" message and does not run the utility. Neither was considered clearly superior, so the behavior was left unspecified.

The C shell has a built-in version of nice that has a different interface from the one described in this volume of IEEE Std 1003.1-2001.

The term "utility" is used, rather than "command", to highlight the fact that shell compound commands, pipelines, and so on, cannot be used. Special built-ins also cannot be used. However, "utility" includes user application programs and shell scripts, not just utilities defined in this volume of IEEE Std 1003.1-2001.

Historical implementations of nice provide a nice value range of 40 or 41 discrete steps, with the default nice value being the midpoint of that range. By default, they lower the nice value of the executed utility by 10.

Some historical documentation states that the increment value must be within a fixed range. This is misleading; the valid increment values on any invocation are determined by the current process nice value, which is not always the default.

The definition of nice value is not intended to suggest that all processes in a system have priorities that are comparable. Scheduling policy extensions such as the realtime priorities in the System Interfaces volume of IEEE Std 1003.1-2001 make the notion of a single underlying priority for all scheduling policies problematic. Some implementations may implement the nice-related features to affect all processes on the system, others to affect just the general time-sharing activities implied by this volume of IEEE Std 1003.1-2001, and others may have no effect at all. Because of the use of "implementation-defined" in nice and renice, a wide range of implementation strategies are possible.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , renice , the System Interfaces volume of IEEE Std 1003.1-2001, nice()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lex(1p)

LEX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lex - generate programs for lexical tasks (DEVELOPMENT)

SYNOPSIS

lex [-t][-n|-v][file ...]

DESCRIPTION

The lex utility shall generate C programs to be used in lexical processing of character input, and that can be used as an interface to yacc. The C programs shall be generated from lex source code and conform to the ISO C standard. Usually, the lex utility shall write the program it generates to the file lex.yy.c; the state of this file is unspecified if lex exits with a non-zero exit status. See the EXTENDED DESCRIPTION section for a complete description of the lex input language.

OPTIONS

The lex utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-n
Suppress the summary of statistics usually written with the -v option. If no table sizes are specified in the lex source code and the -v option is not specified, then -n is implied.
-t
Write the resulting program to standard output instead of lex.yy.c.
-v
Write a summary of lex statistics to the standard output. (See the discussion of lex table sizes in Definitions in lex .) If the -t option is specified and -n is not specified, this report shall be written to standard error. If table sizes are specified in the lex source code, and if the -n option is not specified, the -v option may be enabled.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If more than one such file is specified, all files shall be concatenated to produce a single lex program. If no file operands are specified, or if a file operand is '-' , the standard input shall be used.

STDIN

The standard input shall be used if no file operands are specified, or if a file operand is '-' . See INPUT FILES.

INPUT FILES

The input files shall be text files containing lex source code, as described in the EXTENDED DESCRIPTION section.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of lex:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions. If this variable is not set to the POSIX locale, the results are unspecified.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), and the behavior of character classes within regular expressions. If this variable is not set to the POSIX locale, the results are unspecified.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If the -t option is specified, the text file of C source code output of lex shall be written to standard output.

If the -t option is not specified:

*
Implementation-defined informational, error, and warning messages concerning the contents of lex source code input shall be written to either the standard output or standard error.

*
If the -v option is specified and the -n option is not specified, lex statistics shall also be written to either the standard output or standard error, in an implementation-defined format. These statistics may also be generated if table sizes are specified with a '%' operator in the Definitions section, as long as the -n option is not specified.

STDERR

If the -t option is specified, implementation-defined informational, error, and warning messages concerning the contents of lex source code input shall be written to the standard error.

If the -t option is not specified:

1.
Implementation-defined informational, error, and warning messages concerning the contents of lex source code input shall be written to either the standard output or standard error.

2.
If the -v option is specified and the -n option is not specified, lex statistics shall also be written to either the standard output or standard error, in an implementation-defined format. These statistics may also be generated if table sizes are specified with a '%' operator in the Definitions section, as long as the -n option is not specified.

OUTPUT FILES

A text file containing C source code shall be written to lex.yy.c, or to the standard output if the -t option is present.

EXTENDED DESCRIPTION

Each input file shall contain lex source code, which is a table of regular expressions with corresponding actions in the form of C program fragments.

When lex.yy.c is compiled and linked with the lex library (using the -l l operand with c99), the resulting program shall read character input from the standard input and shall partition it into strings that match the given expressions.

When an expression is matched, these actions shall occur:

*
The input string that was matched shall be left in yytext as a null-terminated string; yytext shall either be an external character array or a pointer to a character string. As explained in Definitions in lex , the type can be explicitly selected using the %array or %pointer declarations, but the default is implementation-defined.

*
The external int yyleng shall be set to the length of the matching string.

*
The expression's corresponding program fragment, or action, shall be executed.

During pattern matching, lex shall search the set of patterns for the single longest possible match. Among rules that match the same number of characters, the rule given first shall be chosen.

The general format of lex source shall be:

Definitions
%%
Rules
%%
UserSubroutines

The first "%%" is required to mark the beginning of the rules (regular expressions and actions); the second "%%" is required only if user subroutines follow.

Any line in the Definitions section beginning with a <blank> shall be assumed to be a C program fragment and shall be copied to the external definition area of the lex.yy.c file. Similarly, anything in the Definitions section included between delimiter lines containing only "%{" and "%}" shall also be copied unchanged to the external definition area of the lex.yy.c file.

Any such input (beginning with a <blank> or within "%{" and "%}" delimiter lines) appearing at the beginning of the Rules section before any rules are specified shall be written to lex.yy.c after the declarations of variables for the yylex() function and before the first line of code in yylex(). Thus, user variables local to yylex() can be declared here, as well as application code to execute upon entry to yylex().

The action taken by lex when encountering any input beginning with a <blank> or within "%{" and "%}" delimiter lines appearing in the Rules section but coming after one or more rules is undefined. The presence of such input may result in an erroneous definition of the yylex() function.

Definitions in lex

Definitions appear before the first "%%" delimiter. Any line in this section not contained between "%{" and "%}" lines and not beginning with a <blank> shall be assumed to define a lex substitution string. The format of these lines shall be:

name substitute

If a name does not meet the requirements for identifiers in the ISO C standard, the result is undefined. The string substitute shall replace the string { name} when it is used in a rule. The name string shall be recognized in this context only when the braces are provided and when it does not appear within a bracket expression or within double-quotes.

In the Definitions section, any line beginning with a '%' (percent sign) character and followed by an alphanumeric word beginning with either 's' or 'S' shall define a set of start conditions. Any line beginning with a '%' followed by a word beginning with either 'x' or 'X' shall define a set of exclusive start conditions. When the generated scanner is in a %s state, patterns with no state specified shall be also active; in a %x state, such patterns shall not be active. The rest of the line, after the first word, shall be considered to be one or more <blank>-separated names of start conditions. Start condition names shall be constructed in the same way as definition names. Start conditions can be used to restrict the matching of regular expressions to one or more states as described in Regular Expressions in lex .

Implementations shall accept either of the following two mutually-exclusive declarations in the Definitions section:

%array
Declare the type of yytext to be a null-terminated character array.
%pointer
Declare the type of yytext to be a pointer to a null-terminated character string.

The default type of yytext is implementation-defined. If an application refers to yytext outside of the scanner source file (that is, via an extern), the application shall include the appropriate %array or %pointer declaration in the scanner source file.

Implementations shall accept declarations in the Definitions section for setting certain internal table sizes. The declarations are shown in the following table.

Table: Table Size Declarations in lex
Declaration | Description | Minimum Value
%p n | Number of positions | 2500
%n n | Number of states | 500
%a n | Number of transitions | 2000
%e n | Number of parse tree nodes | 1000
%k n | Number of packed character classes | 1000
%o n | Size of the output array | 3000

In the table, n represents a positive decimal integer, preceded by one or more <blank>s. The exact meaning of these table size numbers is implementation-defined. The implementation shall document how these numbers affect the lex utility and how they are related to any output that may be generated by the implementation should limitations be encountered during the execution of lex. It shall be possible to determine from this output which of the table size values needs to be modified to permit lex to successfully generate tables for the input language. The values in the column Minimum Value represent the lowest values conforming implementations shall provide.

Rules in lex

The rules in lex source files are a table in which the left column contains regular expressions and the right column contains actions (C program fragments) to be executed when the expressions are recognized.

ERE action
ERE action...

The extended regular expression (ERE) portion of a row shall be separated from action by one or more <blank>s. A regular expression containing <blank>s shall be recognized under one of the following conditions:

*
The entire expression appears within double-quotes.

*
The <blank>s appear within double-quotes or square brackets.

*
Each <blank> is preceded by a backslash character.

User Subroutines in lex

Anything in the user subroutines section shall be copied to lex.yy.c following yylex().

Regular Expressions in lex

The lex utility shall support the set of extended regular expressions (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.4, Extended Regular Expressions), with the following additions and exceptions to the syntax:

"..."
Any string enclosed in double-quotes shall represent the characters within the double-quotes as themselves, except that backslash escapes (which appear in the following table) shall be recognized. Any backslash-escape sequence shall be terminated by the closing quote. For example, "\01" "1" represents a single string: the octal value 1 followed by the character '1' .
<state>r, <state1,state2,...>r

The regular expression r shall be matched only when the program is in one of the start conditions indicated by state, state1, and so on; see Actions in lex . (As an exception to the typographical conventions of the rest of this volume of IEEE Std 1003.1-2001, in this case <state> does not represent a metavariable, but the literal angle-bracket characters surrounding a symbol.) The start condition shall be recognized as such only at the beginning of a regular expression.

r/x
The regular expression r shall be matched only if it is followed by an occurrence of regular expression x ( x is the instance of trailing context, further defined below). The token returned in yytext shall only match r. If the trailing portion of r matches the beginning of x, the result is unspecified. The r expression cannot include further trailing context or the '$' (match-end-of-line) operator; x cannot include the '^' (match-beginning-of-line) operator, nor trailing context, nor the '$' operator. That is, only one occurrence of trailing context is allowed in a lex regular expression, and the '^' operator only can be used at the beginning of such an expression.
{name}
When name is one of the substitution symbols from the Definitions section, the string, including the enclosing braces, shall be replaced by the substitute value. The substitute value shall be treated in the extended regular expression as if it were enclosed in parentheses. No substitution shall occur if { name} occurs within a bracket expression or within double-quotes.

Within an ERE, a backslash character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ). In addition, the escape sequences in the following table shall be recognized.

A literal <newline> cannot occur within an ERE; the escape sequence '\n' can be used to represent a <newline>. A <newline> shall not be matched by a period operator.

Table: Escape Sequences in lex
Escape |  |
Sequence | Description | Meaning
\digits | A backslash character followed by the longest sequence of one, two, or three octal-digit characters (01234567). If all of the digits are 0 (that is, representation of the NUL character), the behavior is undefined. | The character whose encoding is represented by the one, two, or three-digit octal integer. If the size of a byte on the system is greater than nine bits, the valid escape sequence used to represent a byte is implementation-defined. Multi-byte characters require multiple, concatenated escape sequences of this type, including the leading '\' for each byte.
\xdigits | A backslash character followed by the longest sequence of hexadecimal-digit characters (01234567abcdefABCDEF). If all of the digits are 0 (that is, representation of the NUL character), the behavior is undefined. | The character whose encoding is represented by the hexadecimal integer.
\c | A backslash character followed by any character not described in this table or in the table in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ). | The character 'c' , unchanged.
Note:
If a '\x' sequence needs to be immediately followed by a hexadecimal digit character, a sequence such as "\x1" "1" can be used, which represents a character containing the value 1, followed by the character '1' .

The order of precedence given to extended regular expressions for lex differs from that specified in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.4, Extended Regular Expressions. The order of precedence for lex shall be as shown in the following table, from high to low.

Note:
The escaped characters entry is not meant to imply that these are operators, but they are included in the table to show their relationships to the true operators. The start condition, trailing context, and anchoring notations have been omitted from the table because of the placement restrictions described in this section; they can only appear at the beginning or ending of an ERE.

Table: ERE Precedence in lex
Extended Regular Expression Precedence
collation-related bracket symbols [= =] [: :] [. .]
escaped characters \<special character>
bracket expression [ ]
quoting "..."
grouping ( )
definition {name}
single-character RE duplication * + ?
concatenation
interval expression {m,n}
alternation |

The ERE anchoring operators '^' and '$' do not appear in the table. With lex regular expressions, these operators are restricted in their use: the '^' operator can only be used at the beginning of an entire regular expression, and the '$' operator only at the end. The operators apply to the entire regular expression. Thus, for example, the pattern "(^abc)|(def$)" is undefined; it can instead be written as two separate rules, one with the regular expression "^abc" and one with "def$" , which share a common action via the special '|' action (see below). If the pattern were written "^abc|def$" , it would match either "abc" or "def" on a line by itself.

Unlike the general ERE rules, embedded anchoring is not allowed by most historical lex implementations. An example of embedded anchoring would be for patterns such as "(^| )foo( |$)" to match "foo" when it exists as a complete word. This functionality can be obtained using existing lex features:

^foo/[ \n]      |
" foo"/[ \n]    /* Found foo as a separate word. */

Note also that '$' is a form of trailing context (it is equivalent to "/\n" ) and as such cannot be used with regular expressions containing another instance of the operator (see the preceding discussion of trailing context).

The additional regular expressions trailing-context operator '/' can be used as an ordinary character if presented within double-quotes, "/" ; preceded by a backslash, "\/" ; or within a bracket expression, "[/]" . The start-condition '<' and '>' operators shall be special only in a start condition at the beginning of a regular expression; elsewhere in the regular expression they shall be treated as ordinary characters.

Actions in lex

The action to be taken when an ERE is matched can be a C program fragment or the special actions described below; the program fragment can contain one or more C statements, and can also include special actions. The empty C statement ';' shall be a valid action; any string in the lex.yy.c input that matches the pattern portion of such a rule is effectively ignored or skipped. However, the absence of an action shall not be valid, and the action lex takes in such a condition is undefined.

The specification for an action, including C statements and special actions, can extend across several lines if enclosed in braces:

ERE <one or more blanks> { program statement
                           program statement }

The default action when a string in the input to a lex.yy.c program is not matched by any expression shall be to copy the string to the output. Because the default behavior of a program generated by lex is to read the input and copy it to the output, a minimal lex source program that has just "%%" shall generate a C program that simply copies the input to the output unchanged.

Four special actions shall be available:

|   ECHO;   REJECT;   BEGIN
|
The action '|' means that the action for the next rule is the action for this rule. Unlike the other three actions, '|' cannot be enclosed in braces or be semicolon-terminated; the application shall ensure that it is specified alone, with no other actions.
ECHO;
Write the contents of the string yytext on the output.
REJECT;
Usually only a single expression is matched by a given string in the input. REJECT means "continue to the next expression that matches the current input", and shall cause whatever rule was the second choice after the current rule to be executed for the same input. Thus, multiple rules can be matched and executed for one input string or overlapping input strings. For example, given the regular expressions "xyz" and "xy" and the input "xyz" , usually only the regular expression "xyz" would match. The next attempted match would start after z. If the last action in the "xyz" rule is REJECT, both this rule and the "xy" rule would be executed. The REJECT action may be implemented in such a fashion that flow of control does not continue after it, as if it were equivalent to a goto to another part of yylex(). The use of REJECT may result in somewhat larger and slower scanners.
BEGIN
The action:

BEGIN newstate;

switches the state (start condition) to newstate. If the string newstate has not been declared previously as a start condition in the Definitions section, the results are unspecified. The initial state is indicated by the digit '0' or the token INITIAL.

The functions or macros described below are accessible to user code included in the lex input. It is unspecified whether they appear in the C code output of lex, or are accessible only through the -l l operand to c99 (the lex library).

int yylex(void)

Performs lexical analysis on the input; this is the primary function generated by the lex utility. The function shall return zero when the end of input is reached; otherwise, it shall return non-zero values (tokens) determined by the actions that are selected.

int yymore(void)

When called, indicates that when the next input string is recognized, it is to be appended to the current value of yytext rather than replacing it; the value in yyleng shall be adjusted accordingly.

int yyless(int n)

Retains n initial characters in yytext, NUL-terminated, and treats the remaining characters as if they had not been read; the value in yyleng shall be adjusted accordingly.

int input(void)

Returns the next character from the input, or zero on end-of-file. It shall obtain input from the stream pointer yyin, although possibly via an intermediate buffer. Thus, once scanning has begun, the effect of altering the value of yyin is undefined. The character read shall be removed from the input stream of the scanner without any processing by the scanner.

int unput(int c)

Returns the character 'c' to the input; yytext and yyleng are undefined until the next expression is matched. The result of using unput() for more characters than have been input is unspecified.

The following functions shall appear only in the lex library accessible through the -l l operand; they can therefore be redefined by a conforming application:

int yywrap(void)

Called by yylex() at end-of-file; the default yywrap() shall always return 1. If the application requires yylex() to continue processing with another source of input, then the application can include a function yywrap(), which associates another file with the external variable FILE * yyin and shall return a value of zero.

int main(int argc, char *argv[])

Calls yylex() to perform lexical analysis, then exits. The user code can contain main() to perform application-specific operations, calling yylex() as applicable.

Except for input(), unput(), and main(), all external and static names generated by lex shall begin with the prefix yy or YY.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Conforming applications are warned that in the Rules section, an ERE without an action is not acceptable, but need not be detected as erroneous by lex. This may result in compilation or runtime errors.

The purpose of input() is to take characters off the input stream and discard them as far as the lexical analysis is concerned. A common use is to discard the body of a comment once the beginning of a comment is recognized.

The lex utility is not fully internationalized in its treatment of regular expressions in the lex source code or generated lexical analyzer. It would seem desirable to have the lexical analyzer interpret the regular expressions given in the lex source according to the environment specified when the lexical analyzer is executed, but this is not possible with the current lex technology. Furthermore, the very nature of the lexical analyzers produced by lex must be closely tied to the lexical requirements of the input language being described, which is frequently locale-specific anyway. (For example, writing an analyzer that is used for French text is not automatically useful for processing other languages.)

EXAMPLES

The following is an example of a lex program that implements a rudimentary scanner for a Pascal-like syntax:

%{
/* Need this for the call to atof() below. */
#include <math.h>
/* Need this for printf(), fopen(), and stdin below. */
#include <stdio.h>
%}

DIGIT    [0-9]
ID       [a-z][a-z0-9]*

%%

{DIGIT}+ {
    printf("An integer: %s (%d)\n", yytext,
        atoi(yytext));
    }

{DIGIT}+"."{DIGIT}*        {
    printf("A float: %s (%g)\n", yytext,
        atof(yytext));
    }

if|then|begin|end|procedure|function        {
    printf("A keyword: %s\n", yytext);
    }

{ID}    printf("An identifier: %s\n", yytext);

"+"|"-"|"*"|"/"        printf("An operator: %s\n", yytext);

"{"[^}\n]*"}"    /* Eat up one-line comments. */

[ \t\n]+        /* Eat up white space. */

.  printf("Unrecognized character: %s\n", yytext);

%%

int main(int argc, char *argv[])
{
    ++argv, --argc;  /* Skip over program name. */
    if (argc > 0)
        yyin = fopen(argv[0], "r");
    else
        yyin = stdin;

    yylex();
}

RATIONALE

Even though the -c option and references to the C language are retained in this description, lex may be generalized to other languages, as was done at one time for EFL, the Extended FORTRAN Language. Since the lex input specification is essentially language-independent, versions of this utility could be written to produce Ada, Modula-2, or Pascal code, and there are known historical implementations that do so.

The current description of lex bypasses the issue of dealing with internationalized EREs in the lex source code or generated lexical analyzer. If it follows the model used by awk (the source code is assumed to be presented in the POSIX locale, but input and output are in the locale specified by the environment variables), then the tables in the lexical analyzer produced by lex would interpret EREs specified in the lex source in terms of the environment variables specified when lex was executed. The desired effect would be to have the lexical analyzer interpret the EREs given in the lex source according to the environment specified when the lexical analyzer is executed, but this is not possible with the current lex technology.

The description of octal and hexadecimal-digit escape sequences agrees with the ISO C standard use of escape sequences. See the RATIONALE for ed for a discussion of bytes larger than 9 bits being represented by octal values. Hexadecimal values can represent larger bytes and multi-byte characters directly, using as many digits as required.

There is no detailed output format specification. The observed behavior of lex under four different historical implementations was that none of these implementations consistently reported the line numbers for error and warning messages. Furthermore, there was a desire that lex be allowed to output additional diagnostic messages. Leaving message formats unspecified avoids these formatting questions and problems with internationalization.

Although the %x specifier for exclusive start conditions is not historical practice, it is believed to be a minor change to historical implementations and greatly enhances the usability of lex programs since it permits an application to obtain the expected functionality with fewer statements.

The %array and %pointer declarations were added as a compromise between historical systems. The System V-based lex copies the matched text to a yytext array. The flex program, supported in BSD and GNU systems, uses a pointer. In the latter case, significant performance improvements are available for some scanners. Most historical programs should require no change in porting from one system to another because the string being referenced is null-terminated in both cases. (The method used by flex in its case is to null-terminate the token in place by remembering the character that used to come right after the token and replacing it before continuing on to the next scan.) Multi-file programs with external references to yytext outside the scanner source file should continue to operate on their historical systems, but would require one of the new declarations to be considered strictly portable.

The description of EREs avoids unnecessary duplication of ERE details because their meanings within a lex ERE are the same as that for the ERE in this volume of IEEE Std 1003.1-2001.

The reason for the undefined condition associated with text beginning with a <blank> or within "%{" and "%}" delimiter lines appearing in the Rules section is historical practice. Both the BSD and System V lex copy the indented (or enclosed) input in the Rules section (except at the beginning) to unreachable areas of the yylex() function (the code is written directly after a break statement). In some cases, the System V lex generates an error message or a syntax error, depending on the form of indented input.

The intention in breaking the list of functions into those that may appear in lex.yy.c versus those that only appear in libl.a is that only those functions in libl.a can be reliably redefined by a conforming application.

The descriptions of standard output and standard error are somewhat complicated because historical lex implementations chose to issue diagnostic messages to standard output (unless -t was given). IEEE Std 1003.1-2001 allows this behavior, but leaves an opening for the more expected behavior of using standard error for diagnostics. Also, the System V behavior of writing the statistics when any table sizes are given is allowed, while BSD-derived systems can avoid it. The programmer can always precisely obtain the desired results by using either the -t or -n options.

The OPERANDS section does not mention the use of - as a synonym for standard input; not all historical implementations support such usage for any of the file operands.

A description of the translation table was deleted from early proposals because of its relatively low usage in historical applications.

The change to the definition of the input() function that allows buffering of input presents the opportunity for major performance gains in some applications.

The following examples clarify the differences between lex regular expressions and regular expressions appearing elsewhere in this volume of IEEE Std 1003.1-2001. For regular expressions of the form "r/x" , the string matching r is always returned; confusion may arise when the beginning of x matches the trailing portion of r. For example, given the regular expression "a*b/cc" and the input "aaabcc" , yytext would contain the string "aaab" on this match. But given the regular expression "x*/xy" and the input "xxxy" , the token xxx, not xx, is returned by some implementations because xxx matches "x*" .

In the rule "ab*/bc" , the "b*" at the end of r extends r's match into the beginning of the trailing context, so the result is unspecified. If this rule were "ab/bc" , however, the rule matches the text "ab" when it is followed by the text "bc" . In this latter case, the matching of r cannot extend into the beginning of x, so the result is specified.

FUTURE DIRECTIONS

None.

SEE ALSO

c99 , ed , yacc

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


true(1p)

TRUE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

true - return true value

SYNOPSIS

true

DESCRIPTION

The true utility shall return with exit code zero.

OPTIONS

None.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

Not used.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Zero.

CONSEQUENCES OF ERRORS

None.

The following sections are informative.

APPLICATION USAGE

This utility is typically used in shell scripts, as shown in the EXAMPLES section. The special built-in utility : is sometimes more efficient than true.

EXAMPLES

This command is executed forever:

while true
do
    command
done

RATIONALE

The true utility has been retained in this volume of IEEE Std 1003.1-2001, even though the shell special built-in : provides similar functionality, because true is widely used in historical scripts and is less cryptic to novice script readers.

FUTURE DIRECTIONS

None.

SEE ALSO

false , Shell Commands

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sleep(1p)

SLEEP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sleep - suspend execution for an interval

SYNOPSIS

sleep time

DESCRIPTION

The sleep utility shall suspend execution for at least the integral number of seconds specified by the time operand.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

time
A non-negative decimal integer specifying the number of seconds for which to suspend execution.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of sleep:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

If the sleep utility receives a SIGALRM signal, one of the following actions shall be taken:

1.
Terminate normally with a zero exit status.

2.
Effectively ignore the signal.

3.
Provide the default behavior for signals described in the ASYNCHRONOUS EVENTS section of Utility Description Defaults . This could include terminating with a non-zero exit status.

The sleep utility shall take the standard action for all other signals.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The execution was successfully suspended for at least time seconds, or a SIGALRM signal was received. See the ASYNCHRONOUS EVENTS section.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

The sleep utility can be used to execute a command after a certain amount of time, as in:

(sleep 105; command) &

or to execute a command every so often, as in:

while true
do
    command    sleep 37
done

RATIONALE

The exit status is allowed to be zero when sleep is interrupted by the SIGALRM signal because most implementations of this utility rely on the arrival of that signal to notify them that the requested finishing time has been successfully attained. Such implementations thus do not distinguish this situation from the successful completion case. Other implementations are allowed to catch the signal and go back to sleep until the requested time expires or to provide the normal signal termination procedures.

As with all other utilities that take integral operands and do not specify subranges of allowed values, sleep is required by this volume of IEEE Std 1003.1-2001 to deal with time requests of up to 2147483647 seconds. This may mean that some implementations have to make multiple calls to the delay mechanism of the underlying operating system if its argument range is less than this.

FUTURE DIRECTIONS

None.

SEE ALSO

wait , the System Interfaces volume of IEEE Std 1003.1-2001, alarm(), sleep()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


man(1p)

MAN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

man - display system documentation

SYNOPSIS

man [-k] name...

DESCRIPTION

The man utility shall write information about each of the name operands. If name is the name of a standard utility, man at a minimum shall write a message describing the syntax used by the standard utility, its options, and operands. If more information is available, the man utility shall provide it in an implementation-defined manner.

An implementation may provide information for values of name other than the standard utilities. Standard utilities that are listed as optional and that are not supported by the implementation either shall cause a brief message indicating that fact to be displayed or shall cause a full display of information as described previously.

OPTIONS

The man utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-k
Interpret name operands as keywords to be used in searching a utilities summary database that contains a brief purpose entry for each standard utility and write lines from the summary database that match any of the keywords. The keyword search shall produce results that are the equivalent of the output of the following command:

grep -Ei '
name
name...
 summary-database

This assumes that the summary-database is a text file with a single entry per line; this organization is not required and the example using grep -Ei is merely illustrative of the type of search intended. The purpose entry to be included in the database shall consist of a terse description of the purpose of the utility.

OPERANDS

The following operand shall be supported:

name
A keyword or the name of a standard utility. When -k is not specified and name does not represent one of the standard utilities, the results are unspecified.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of man:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and in the summary database). The value of LC_CTYPE need not affect the format of the information written about the name operands.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PAGER
Determine an output filtering command for writing the output to a terminal. Any string acceptable as a command_string operand to the sh -c command shall be valid. When standard output is a terminal device, the reference page output shall be piped through the command. If the PAGER variable is null or not set, the command shall be either more or another paginator utility documented in the system documentation.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The man utility shall write text describing the syntax of the utility name, its options and its operands, or, when -k is specified, lines from the summary database. The format of this text is implementation-defined.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

It is recognized that the man utility is only of minimal usefulness as specified. The opinion of the standard developers was strongly divided as to how much or how little information man should be required to provide. They considered, however, that the provision of some portable way of accessing documentation would aid user portability. The arguments against a fuller specification were:

*
Large quantities of documentation should not be required on a system that does not have excess disk space.

*
The current manual system does not present information in a manner that greatly aids user portability.

*
A "better help system" is currently an area in which vendors feel that they can add value to their POSIX implementations.

The -f option was considered, but due to implementation differences, it was not included in this volume of IEEE Std 1003.1-2001.

The description was changed to be more specific about what has to be displayed for a utility. The standard developers considered it insufficient to allow a display of only the synopsis without giving a short description of what each option and operand does.

The "purpose" entry to be included in the database can be similar to the section title (less the numeric prefix) from this volume of IEEE Std 1003.1-2001 for each utility. These titles are similar to those used in historical systems for this purpose.

See mailx for rationale concerning the default paginator.

The caveat in the LC_CTYPE description was added because it is not a requirement that an implementation provide reference pages for all of its supported locales on each system; changing LC_CTYPE does not necessarily translate the reference page into another language. This is equivalent to the current state of LC_MESSAGES in IEEE Std 1003.1-2001-locale-specific messages are not yet a requirement.

The historical MANPATH variable is not included in POSIX because no attempt is made to specify naming conventions for reference page files, nor even to mandate that they are files at all. On some implementations they could be a true database, a hypertext file, or even fixed strings within the man executable. The standard developers considered the portability of reference pages to be outside their scope of work. However, users should be aware that MANPATH is implemented on a number of historical systems and that it can be used to tailor the search pattern for reference pages from the various categories (utilities, functions, file formats, and so on) when the system administrator reveals the location and conventions for reference pages on the system.

The keyword search can rely on at least the text of the section titles from these utility descriptions, and the implementation may add more keywords. The term "section titles" refers to the strings such as:

man - Display system documentation
ps - Report process status

FUTURE DIRECTIONS

None.

SEE ALSO

more

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


hash(1p)

HASH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

hash - remember or report utility locations

SYNOPSIS

hash [utility...]

hash -r

DESCRIPTION

The hash utility shall affect the way the current shell environment remembers the locations of utilities found as described in Command Search and Execution . Depending on the arguments specified, it shall add utility locations to its list of remembered locations or it shall purge the contents of the list. When no arguments are specified, it shall report on the contents of the list.

Utilities provided as built-ins to the shell shall not be reported by hash.

OPTIONS

The hash utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-r
Forget all previously remembered utility locations.

OPERANDS

The following operand shall be supported:

utility
The name of a utility to be searched for and added to the list of remembered locations. If utility contains one or more slashes, the results are unspecified.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of hash:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the location of utility, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output of hash shall be used when no arguments are specified. Its format is unspecified, but includes the pathname of each utility in the list of remembered locations for the current shell environment. This list shall consist of those utilities named in previous hash invocations that have been invoked, and may contain those invoked and found through the normal command search process.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since hash affects the current shell execution environment, it is always provided as a shell regular built-in. If it is called in a separate utility execution environment, such as one of the following:

nohup hash -r
find . -type f | xargs hash

it does not affect the command search process of the caller's environment.

The hash utility may be implemented as an alias-for example, alias -t -, in which case utilities found through normal command search are not listed by the hash command.

The effects of hash -r can also be achieved portably by resetting the value of PATH ; in the simplest form, this can be:

PATH="$PATH"

The use of hash with utility names is unnecessary for most applications, but may provide a performance improvement on a few implementations; normally, the hashing process is included by default.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Command Search and Execution

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qstat(1p)

QSTAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qstat - show status of batch jobs

SYNOPSIS

qstat [-f] job_identifier ...

qstat -Q [-f] destination ...

qstat -B [-f] server_name ...

DESCRIPTION

The status of a batch job, batch queue, or batch server is obtained by a request to the server. The qstat utility is a user-accessible batch client that requests the status of one or more batch jobs, batch queues, or servers, and writes the status information to standard output.

For each successfully processed batch job_identifier, the qstat utility shall display information about the corresponding batch job.

For each successfully processed destination, the qstat utility shall display information about the corresponding batch queue.

For each successfully processed server name, the qstat utility shall display information about the corresponding server.

The qstat utility shall acquire batch job status information by sending a Job Status Request to a batch server. The qstat utility shall acquire batch queue status information by sending a Queue Status Request to a batch server. The qstat utility shall acquire server status information by sending a Server Status Request to a batch server.

OPTIONS

The qstat utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-f
Specify that a full display is produced.

The minimum contents of a full display are specified in the STDOUT section.

Additional contents and format of a full display are implementation-defined.

-Q
Specify that the operand is a destination.

The qstat utility shall display information about each batch queue at each destination identified as an operand.

-B
Specify that the operand is a server name.

The qstat utility shall display information about each server identified as an operand.

OPERANDS

If the -Q option is presented to the qstat utility, the utility shall accept one or more operands that conform to the syntax for a destination (see Destination ).

If the -B option is presented to the qstat utility, the utility shall accept one or more server_name operands.

If neither the -B nor the -Q option is presented to the qstat utility, the utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qstat:

HOME
Determine the pathname of the user's home directory.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_NUMERIC

Determine the locale for selecting the radix character used when writing floating-point formatted output.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If an operand presented to the qstat utility is a batch job_identifier and the -f option is not specified, the qstat utility shall display the following items on a single line, in the stated order, with white space between each item, for each successfully processed operand:

*
The batch job_identifier

*
The batch job name

*
The Job_Owner attribute

*
The CPU time used by the batch job

*
The batch job state

*
The batch job location

If an operand presented to the qstat utility is a batch job_identifier and the -f option is specified, the qstat utility shall display the following items for each success fully processed operand:

*
The batch job_identifier

*
The batch job name

*
The Job_Owner attribute

*
The execution user ID

*
The CPU time used by the batch job

*
The batch job state

*
The batch job location

*
Additional implementation-defined information, if any, about the batch job or batch queue

If an operand presented to the qstat utility is a destination, the -Q option is specified, and the -f option is not specified, the qstat utility shall display the following items on a single line, in the stated order, with white space between each item, for each successfully processed operand:

*
The batch queue name

*
The maximum number of batch jobs that shall be run in the batch queue concurrently

*
The total number of batch jobs in the batch queue

*
The status of the batch queue

*
For each state, the number of batch jobs in that state in the batch queue and the name of the state

*
The type of batch queue (execution or routing)

If the operands presented to the qstat utility are destinations, the -Q option is specified, and the -f option is specified, the qstat utility shall display the following items for each successfully processed operand:

*
The batch queue name

*
The maximum number of batch jobs that shall be run in the batch queue concurrently

*
The total number of batch jobs in the batch queue

*
The status of the batch queue

*
For each state, the number of batch jobs in that state in the batch queue and the name of the state

*
The type of batch queue (execution or routing)

*
Additional implementation-defined information, if any, about the batch queue

If the operands presented to the qstat utility are batch server names, the -B option is specified, and the -f option is not specified, the qstat utility shall display the following items on a single line, in the stated order, with white space between each item, for each successfully processed operand:

*
The batch server name

*
The maximum number of batch jobs that shall be run in the batch queue concurrently

*
The total number of batch jobs managed by the batch server

*
The status of the batch server

*
For each state, the number of batch jobs in that state and the name of the state

If the operands presented to the qstat utility are server names, the -B option is specified, and the -f option is specified, the qstat utility shall display the following items for each successfully processed operand:

*
The server name

*
The maximum number of batch jobs that shall be run in the batch queue concurrently

*
The total number of batch jobs managed by the server

*
The status of the server

*
For each state, the number of batch jobs in that state and the name of the state

*
Additional implementation-defined information, if any, about the server

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qstat utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qstat utility waits to output the diagnostic message while attempting to locate the batch job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qstat utility allows users to display the status of jobs and list the batch jobs in queues.

The operands of the qstat utility may be either job identifiers, queues (specified as destination identifiers), or batch server names. The -Q and -B options, or absence thereof, indicate the nature of the operands.

The other options of the qstat utility allow the user to control the amount of information displayed and the format in which it is displayed. Should a user wish to display the status of a set of jobs that match a selection criteria, the qselect utility may be used to acquire such a list.

The -f option allows users to request a "full" display in an implementation-defined format.

Historically, the qstat utility has been a part of the NQS and its derivatives, the existing practice on which it is based.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , qselect

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


delta(1p)

DELTA

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

delta - make a delta (change) to an SCCS file (DEVELOPMENT)

SYNOPSIS

delta [-nps][-g list][-m mrlist][-r SID][-y[comment]] file...

DESCRIPTION

The delta utility shall be used to permanently introduce into the named SCCS files changes that were made to the files retrieved by get (called the g-files, or generated files).

OPTIONS

The delta utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the -y option has an optional option-argument. This optional option-argument shall not be presented as a separate argument.

The following options shall be supported:

-r SID
Uniquely identify which delta is to be made to the SCCS file. The use of this option shall be necessary only if two or more outstanding get commands for editing ( get -e) on the same SCCS file were done by the same person (login name). The SID value specified with the -r option can be either the SID specified on the get command line or the SID to be made as reported by the get utility; see get .
-s
Suppress the report to standard output of the activity associated with each file. See the STDOUT section.
-n
Specify retention of the edited g-file (normally removed at completion of delta processing).
-g list
Specify a list (see get for the definition of list) of deltas that shall be ignored when the file is accessed at the change level (SID) created by this delta.
-m mrlist
Specify a modification request (MR) number that the application shall supply as the reason for creating the new delta. This shall be used if the SCCS file has the v flag set; see admin .

If -m is not used and '-' is not specified as a file argument, and the standard input is a terminal, the prompt described in the STDOUT section shall be written to standard output before the standard input is read; if the standard input is not a terminal, no prompt shall be issued.

MRs in a list shall be separated by <blank>s or escaped <newline>s. An unescaped <newline> shall terminate the MR list. The escape character is <backslash>.

If the v flag has a value, it shall be taken to be the name of a program which validates the correctness of the MR numbers. If a non-zero exit status is returned from the MR number validation program, the delta utility shall terminate. (It is assumed that the MR numbers were not all valid.)

-y[comment]
Describe the reason for making the delta. The comment shall be an arbitrary group of lines that would meet the definition of a text file. Implementations shall support comments from zero to 512 bytes and may support longer values. A null string (specified as either -y, -y "" , or in response to a prompt for a comment) shall be considered a valid comment.

If -y is not specified and '-' is not specified as a file argument, and the standard input is a terminal, the prompt described in the STDOUT section shall be written to standard output before the standard input is read; if the standard input is not a terminal, no prompt shall be issued. An unescaped <newline> shall terminate the comment text. The escape character is <backslash>.

The -y option shall be required if the file operand is specified as '-' .

-p
Write (to standard output) the SCCS file differences before and after the delta is applied in diff format; see diff .

OPERANDS

The following operand shall be supported:

file
A pathname of an existing SCCS file or a directory. If file is a directory, the delta utility shall behave as though each file in the directory were specified as a named file, except that non-SCCS files (last component of the pathname does not begin with s.) and unreadable files shall be silently ignored.

If exactly one file operand appears, and it is '-' , the standard input shall be read; each line of the standard input shall be taken to be the name of an SCCS file to be processed. Non-SCCS files and unreadable files shall be silently ignored.

STDIN

The standard input shall be a text file used only in the following cases:

*
To read an mrlist or a comment (see the -m and -y options).

*
A file operand shall be specified as '-' . In this case, the -y option must be used to specify the comment, and if the SCCS file has the v flag set, the -m option must also be used to specify the MR list.

INPUT FILES

Input files shall be text files whose data is to be included in the SCCS files. If the first character of any line of an input file is <SOH> in the POSIX locale, the results are unspecified. If this file contains more than 99999 lines, the number of lines recorded in the header for this file shall be 99999 for this delta.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of delta:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error, and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone in which the time and date are written in the SCCS file. If the TZ variable is unset or NULL, an unspecified system default timezone is used.

ASYNCHRONOUS EVENTS

If SIGINT is caught, temporary files shall be cleaned up and delta shall exit with a non-zero exit code. The standard action shall be taken for all other signals; see Utility Description Defaults .

STDOUT

The standard output shall be used only for the following messages in the POSIX locale:

*
Prompts (see the -m and -y options) in the following formats:

"MRs? "

"comments? "

The MR prompt, if written, shall always precede the comments prompt.

*
A report of each file's activities (unless the -s option is specified) in the following format:

"%s\n%d inserted\n%d deleted\n%d unchanged\n", <New SID>,
    <number of lines inserted>, <number of lines deleted>,
    <number of lines unchanged>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

Any SCCS files updated shall be files of an unspecified format.

EXTENDED DESCRIPTION

System Date and Time

When a delta is added to an SCCS file, the system date and time shall be recorded for the new delta. If a get is performed using an SCCS file with a date recorded apparently in the future, the behavior is unspecified.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Problems can arise if the system date and time have been modified (for example, put forward and then back again, or unsynchronized clocks across a network) and can also arise when different values of the TZ environment variable are used.

Problems of a similar nature can also arise for the operation of the get utility, which records the date and time in the file body.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Utility Description Defaults , admin , diff , get , prs , rmdel

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pax(1p)

PAX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pax - portable archive interchange

SYNOPSIS

pax [-cdnv][-H|-L][-f archive][-s replstr]...[pattern...]

pax -r[-cdiknuv][-H|-L][-f archive][-o options]...[-p string]...
[-s replstr]...[pattern...]

pax -w[-dituvX][-H|-L][-b blocksize][[-a][-f archive][-o options]...
[-s replstr]...[-x format][file...]

pax -r -w[-diklntuvX][-H|-L][-p string]...[-s replstr]...
[file...] directory

DESCRIPTION

The pax utility shall read, write, and write lists of the members of archive files and copy directory hierarchies. A variety of archive formats shall be supported; see the -x format option.

The action to be taken depends on the presence of the -r and -w options. The four combinations of -r and -w are referred to as the four modes of operation: list, read, write, and copy modes, corresponding respectively to the four forms shown in the SYNOPSIS section.

list
In list mode (when neither -r nor -w are specified), pax shall write the names of the members of the archive file read from the standard input, with pathnames matching the specified patterns, to standard output. If a named file is of type directory, the file hierarchy rooted at that file shall be listed as well.
read
In read mode (when -r is specified, but -w is not), pax shall extract the members of the archive file read from the standard input, with pathnames matching the specified patterns. If an extracted file is of type directory, the file hierarchy rooted at that file shall be extracted as well. The extracted files shall be created performing pathname resolution with the directory in which pax was invoked as the current working directory.

If an attempt is made to extract a directory when the directory already exists, this shall not be considered an error. If an attempt is made to extract a FIFO when the FIFO already exists, this shall not be considered an error.

The ownership, access, and modification times, and file mode of the restored files are discussed under the -p option.

write
In write mode (when -w is specified, but -r is not), pax shall write the contents of the file operands to the standard output in an archive format. If no file operands are specified, a list of files to copy, one per line, shall be read from the standard input. A file of type directory shall include all of the files in the file hierarchy rooted at the file.
copy
In copy mode (when both -r and -w are specified), pax shall copy the file operands to the destination directory.

If no file operands are specified, a list of files to copy, one per line, shall be read from the standard input. A file of type directory shall include all of the files in the file hierarchy rooted at the file.

The effect of the copy shall be as if the copied files were written to an archive file and then subsequently extracted, except that there may be hard links between the original and the copied files. If the destination directory is a subdirectory of one of the files to be copied, the results are unspecified. If the destination directory is a file of a type not defined by the System Interfaces volume of IEEE Std 1003.1-2001, the results are implementation-defined; otherwise, it shall be an error for the file named by the directory operand not to exist, not be writable by the user, or not be a file of type directory.

In read or copy modes, if intermediate directories are necessary to extract an archive member, pax shall perform actions equivalent to the mkdir() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:

*
The intermediate directory used as the path argument

*
The value of the bitwise-inclusive OR of S_IRWXU, S_IRWXG, and S_IRWXO as the mode argument

If any specified pattern or file operands are not matched by at least one file or archive member, pax shall write a diagnostic message to standard error for each one that did not match and exit with a non-zero exit status.

The archive formats described in the EXTENDED DESCRIPTION section shall be automatically detected on input. The default output archive format shall be implementation-defined.

A single archive can span multiple files. The pax utility shall determine, in an implementation-defined manner, what file to read or write as the next file.

If the selected archive format supports the specification of linked files, it shall be an error if these files cannot be linked when the archive is extracted. For archive formats that do not store file contents with each name that causes a hard link, if the file that contains the data is not extracted during this pax session, either the data shall be restored from the original file, or a diagnostic message shall be displayed with the name of a file that can be used to extract the data. In traversing directories, pax shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file visited. When it detects an infinite loop, pax shall write a diagnostic message to standard error and shall terminate.

OPTIONS

The pax utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the order of presentation of the -o, -p, and -s options is significant.

The following options shall be supported:

-r
Read an archive file from standard input.
-w
Write files to the standard output in the specified archive format.
-a
Append files to the end of the archive. It is implementation-defined which devices on the system support appending. Additional file formats unspecified by this volume of IEEE Std 1003.1-2001 may impose restrictions on appending.
-b blocksize
Block the output at a positive decimal integer number of bytes per write to the archive file. Devices and archive formats may impose restrictions on blocking. Blocking shall be automatically determined on input. Conforming applications shall not specify a blocksize value larger than 32256. Default blocking when creating archives depends on the archive format. (See the -x option below.)
-c
Match all file or archive members except those specified by the pattern or file operands.
-d
Cause files of type directory being copied or archived or archive members of type directory being extracted or listed to match only the file or archive member itself and not the file hierarchy rooted at the file.
-f archive
Specify the pathname of the input or output archive, overriding the default standard input (in list or read modes) or standard output ( write mode).
-H
If a symbolic link referencing a file of type directory is specified on the command line, pax shall archive the file hierarchy rooted in the file referenced by the link, using the name of the link as the root of the file hierarchy. Otherwise, if a symbolic link referencing a file of any other file type which pax can normally archive is specified on the command line, then pax shall archive the file referenced by the link, using the name of the link. The default behavior shall be to archive the symbolic link itself.
-i
Interactively rename files or archive members. For each archive member matching a pattern operand or file matching a file operand, a prompt shall be written to the file /dev/tty. The prompt shall contain the name of the file or archive member, but the format is otherwise unspecified. A line shall then be read from /dev/tty. If this line is blank, the file or archive member shall be skipped. If this line consists of a single period, the file or archive member shall be processed with no modification to its name. Otherwise, its name shall be replaced with the contents of the line. The pax utility shall immediately exit with a non-zero exit status if end-of-file is encountered when reading a response or if /dev/tty cannot be opened for reading and writing.

The results of extracting a hard link to a file that has been renamed during extraction are unspecified.

-k
Prevent the overwriting of existing files.
-l
(The letter ell.) In copy mode, hard links shall be made between the source and destination file hierarchies whenever possible. If specified in conjunction with -H or -L, when a symbolic link is encountered, the hard link created in the destination file hierarchy shall be to the file referenced by the symbolic link. If specified when neither -H nor -L is specified, when a symbolic link is encountered, the implementation shall create a hard link to the symbolic link in the source file hierarchy or copy the symbolic link to the destination.
-L
If a symbolic link referencing a file of type directory is specified on the command line or encountered during the traversal of a file hierarchy, pax shall archive the file hierarchy rooted in the file referenced by the link, using the name of the link as the root of the file hierarchy. Otherwise, if a symbolic link referencing a file of any other file type which pax can normally archive is specified on the command line or encountered during the traversal of a file hierarchy, pax shall archive the file referenced by the link, using the name of the link. The default behavior shall be to archive the symbolic link itself.
-n
Select the first archive member that matches each pattern operand. No more than one archive member shall be matched for each pattern (although members of type directory shall still match the file hierarchy rooted at that file).
-o options
Provide information to the implementation to modify the algorithm for extracting or writing files. The value of options shall consist of one or more comma-separated keywords of the form:

keyword[[:]=value][,keyword[[:]=value], ...]

Some keywords apply only to certain file formats, as indicated with each description. Use of keywords that are inapplicable to the file format being processed produces undefined results.

Keywords in the options argument shall be a string that would be a valid portable filename as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.276, Portable Filename Character Set.

Note:
Keywords are not expected to be filenames, merely to follow the same character composition rules as portable filenames.

Keywords can be preceded with white space. The value field shall consist of zero or more characters; within value, the application shall precede any literal comma with a backslash, which shall be ignored, but preserves the comma as part of value. A comma as the final character, or a comma followed solely by white space as the final characters, in options shall be ignored. Multiple -o options can be specified; if keywords given to these multiple -o options conflict, the keywords and values appearing later in command line sequence shall take precedence and the earlier shall be silently ignored. The following keyword values of options shall be supported for the file formats as indicated:

delete=pattern

(Applicable only to the -x pax format.) When used in write or copy mode, pax shall omit from extended header records that it produces any keywords matching the string pattern. When used in read or list mode, pax shall ignore any keywords matching the string pattern in the extended header records. In both cases, matching shall be performed using the pattern matching notation described in Patterns Matching a Single Character and Patterns Matching Multiple Characters . For example:

-o delete=security.*

would suppress security-related information. See pax Extended Header for extended header record keyword usage.

exthdr.name=string

(Applicable only to the -x pax format.) This keyword allows user control over the name that is written into the ustar header blocks for the extended header produced under the circumstances described in pax Header Block . The name shall be the contents of string, after the following character substitutions have been made:
string
Includes: Replaced By:
%d The directory name of the file, equivalent to the result of the dirname utility on the translated pathname.
%f The filename of the file, equivalent to the result of the basename utility on the translated pathname.
%p The process ID of the pax process.
%% A '%' character.

Any other '%' characters in string produce undefined results.

If no -o exthdr.name= string is specified, pax shall use the following default value:

%d/PaxHeaders.%p/%f
globexthdr.name=string

(Applicable only to the -x pax format.) When used in write or copy mode with the appropriate options, pax shall create global extended header records with ustar header blocks that will be treated as regular files by previous versions of pax. This keyword allows user control over the name that is written into the ustar header blocks for global extended header records. The name shall be the contents of string, after the following character substitutions have been made:
string
Includes: Replaced By:
%n An integer that represents the sequence number of the global extended header record in the archive, starting at 1.
%p The process ID of the pax process.
%% A '%' character.

Any other '%' characters in string produce undefined results.

If no -o globexthdr.name= string is specified, pax shall use the following default value:

$TMPDIR/GlobalHead.%p.%n

where $ TMPDIR represents the value of the TMPDIR environment variable. If TMPDIR is not set, pax shall use /tmp.

invalid=action

(Applicable only to the -x pax format.) This keyword allows user control over the action pax takes upon encountering values in an extended header record that, in read or copy mode, are invalid in the destination hierarchy or, in list mode, cannot be written in the codeset and current locale of the implementation. The following are invalid values that shall be recognized by pax:

*
In read or copy mode, a filename or link name that contains character encodings invalid in the destination hierarchy. (For example, the name may contain embedded NULs.)

*
In read or copy mode, a filename or link name that is longer than the maximum allowed in the destination hierarchy (for either a pathname component or the entire pathname).

*
In list mode, any character string value (filename, link name, user name, and so on) that cannot be written in the codeset and current locale of the implementation.

The following mutually-exclusive values of the action argument are supported:

bypass
In read or copy mode, pax shall bypass the file, causing no change to the destination hierarchy. In list mode, pax shall write all requested valid values for the file, but its method for writing invalid values is unspecified.
rename
In read or copy mode, pax shall act as if the -i option were in effect for each file with invalid filename or link name values, allowing the user to provide a replacement name interactively. In list mode, pax shall behave identically to the bypass action.
UTF-8
When used in read, copy, or list mode and a filename, link name, owner name, or any other field in an extended header record cannot be translated from the pax UTF-8 codeset format to the codeset and current locale of the implementation, pax shall use the actual UTF-8 encoding for the name.
write
In read or copy mode, pax shall write the file, translating or truncating the name, regardless of whether this may overwrite an existing file with a valid name. In list mode, pax shall behave identically to the bypass action.

If no -o invalid= option is specified, pax shall act as if -o invalid= bypass were specified. Any overwriting of existing files that may be allowed by the -o invalid= actions shall be subject to permission ( -p) and modification time ( -u) restrictions, and shall be suppressed if the -k option is also specified.

linkdata

(Applicable only to the -x pax format.) In write mode, pax shall write the contents of a file to the archive even when that file is merely a hard link to a file whose contents have already been written to the archive.

listopt=format

This keyword specifies the output format of the table of contents produced when the -v option is specified in list mode. See List Mode Format Specifications . To avoid ambiguity, the listopt= format shall be the only or final keyword= value pair in a -o option-argument; all characters in the remainder of the option-argument shall be considered part of the format string. When multiple -o listopt= format options are specified, the format strings shall be considered a single, concatenated string, evaluated in command line order.

times

(Applicable only to the -x pax format.) When used in write or copy mode, pax shall include atime, ctime, and mtime extended header records for each file. See pax Extended Header File Times .

In addition to these keywords, if the -x pax format is specified, any of the keywords and values defined in pax Extended Header , including implementation extensions, can be used in -o option-arguments, in either of two modes:

keyword=value

When used in write or copy mode, these keyword/value pairs shall be included at the beginning of the archive as typeflag g global extended header records. When used in read or list mode, these keyword/value pairs shall act as if they had been at the beginning of the archive as typeflag g global extended header records.

keyword:=value

When used in write or copy mode, these keyword/value pairs shall be included as records at the beginning of a typeflag x extended header for each file. (This shall be equivalent to the equal-sign form except that it creates no typeflag g global extended header records.) When used in read or list mode, these keyword/value pairs shall act as if they were included as records at the end of each extended header; thus, they shall override any global or file-specific extended header record keywords of the same names. For example, in the command:

pax -r -o "
gname:=mygroup,
" <archive

the group name will be forced to a new value for all files read from the archive.

The precedence of -o keywords over various fields in the archive is described in pax Extended Header Keyword Precedence .

-p string
Specify one or more file characteristic options (privileges). The string option-argument shall be a string specifying file characteristics to be retained or discarded on extraction. The string shall consist of the specification characters a , e , m , o , and p . Other implementation-defined characters can be included. Multiple characteristics can be concatenated within the same string and multiple -p options can be specified. The meaning of the specification characters are as follows:
a
Do not preserve file access times.
e
Preserve the user ID, group ID, file mode bits (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.168, File Mode Bits), access time, modification time, and any other implementation-defined file characteristics.
m
Do not preserve file modification times.
o
Preserve the user ID and group ID.
p
Preserve the file mode bits. Other implementation-defined file mode attributes may be preserved.

In the preceding list, "preserve" indicates that an attribute stored in the archive shall be given to the extracted file, subject to the permissions of the invoking process. The access and modification times of the file shall be preserved unless otherwise specified with the -p option or not stored in the archive. All attributes that are not preserved shall be determined as part of the normal file creation action (see File Read, Write, and Creation ).

If neither the e nor the o specification character is specified, or the user ID and group ID are not preserved for any reason, pax shall not set the S_ISUID and S_ISGID bits of the file mode.

If the preservation of any of these items fails for any reason, pax shall write a diagnostic message to standard error. Failure to preserve these items shall affect the final exit status, but shall not cause the extracted file to be deleted.

If file characteristic letters in any of the string option-arguments are duplicated or conflict with each other, the ones given last shall take precedence. For example, if -p eme is specified, file modification times are preserved.

-s replstr
Modify file or archive member names named by pattern or file operands according to the substitution expression replstr, using the syntax of the ed utility. The concepts of "address" and "line" are meaningless in the context of the pax utility, and shall not be supplied. The format shall be:

-s /old/new/[gp]

where as in ed, old is a basic regular expression and new can contain an ampersand, '\n' (where n is a digit) backreferences, or subexpression matching. The old string shall also be permitted to contain <newline>s.

Any non-null character can be used as a delimiter ( '/' shown here). Multiple -s expressions can be specified; the expressions shall be applied in the order specified, terminating with the first successful substitution. The optional trailing 'g' is as defined in the ed utility. The optional trailing 'p' shall cause successful substitutions to be written to standard error. File or archive member names that substitute to the empty string shall be ignored when reading and writing archives.

-t
When reading files from the file system, and if the user has the permissions required by utime() to do so, set the access time of each file read to the access time that it had before being read by pax.
-u
Ignore files that are older (having a less recent file modification time) than a pre-existing file or archive member with the same name. In read mode, an archive member with the same name as a file in the file system shall be extracted if the archive member is newer than the file. In write mode, an archive file member with the same name as a file in the file system shall be superseded if the file is newer than the archive member. If -a is also specified, this is accomplished by appending to the archive; otherwise, it is unspecified whether this is accomplished by actual replacement in the archive or by appending to the archive. In copy mode, the file in the destination hierarchy shall be replaced by the file in the source hierarchy or by a link to the file in the source hierarchy if the file in the source hierarchy is newer.
-v
In list mode, produce a verbose table of contents (see the STDOUT section). Otherwise, write archive member pathnames to standard error (see the STDERR section).
-x format
Specify the output archive format. The pax utility shall support the following formats:
cpio
The cpio interchange format; see the EXTENDED DESCRIPTION section. The default blocksize for this format for character special archive files shall be 5120. Implementations shall support all blocksize values less than or equal to 32256 that are multiples of 512.
pax
The pax interchange format; see the EXTENDED DESCRIPTION section. The default blocksize for this format for character special archive files shall be 5120. Implementations shall support all blocksize values less than or equal to 32256 that are multiples of 512.
ustar
The tar interchange format; see the EXTENDED DESCRIPTION section. The default blocksize for this format for character special archive files shall be 10240. Implementations shall support all blocksize values less than or equal to 32256 that are multiples of 512.

Implementation-defined formats shall specify a default block size as well as any other block sizes supported for character special archive files.

Any attempt to append to an archive file in a format different from the existing archive format shall cause pax to exit immediately with a non-zero exit status.

In copy mode, if no -x format is specified, pax shall behave as if -x pax were specified.

-X
When traversing the file hierarchy specified by a pathname, pax shall not descend into directories that have a different device ID ( st_dev; see the System Interfaces volume of IEEE Std 1003.1-2001, stat()).

The options that operate on the names of files or archive members ( -c, -i, -n, -s, -u, and -v) shall interact as follows. In read mode, the archive members shall be selected based on the user-specified pattern operands as modified by the -c, -n, and -u options. Then, any -s and -i options shall modify, in that order, the names of the selected files. The -v option shall write names resulting from these modifications.

In write mode, the files shall be selected based on the user-specified pathnames as modified by the -n and -u options. Then, any -s and -i options shall modify, in that order, the names of these selected files. The -v option shall write names resulting from these modifications.

If both the -u and -n options are specified, pax shall not consider a file selected unless it is newer than the file to which it is compared.

List Mode Format Specifications

In list mode with the -o listopt= format option, the format argument shall be applied for each selected file. The pax utility shall append a <newline> to the listopt output for each selected file. The format argument shall be used as the format string described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation, with the exceptions 1. through 5. defined in the EXTENDED DESCRIPTION section of printf, plus the following exceptions:

6.
The sequence ( keyword) can occur before a format conversion specifier. The conversion argument is defined by the value of keyword. The implementation shall support the following keywords:
*
Any of the Field Name entries in ustar Header Block and Octet-Oriented cpio Archive Entry . The implementation may support the cpio keywords without the leading c_ in addition to the form required by Values for cpio c_mode Field .

*
Any keyword defined for the extended header in pax Extended Header .

*
Any keyword provided as an implementation-defined extension within the extended header defined in pax Extended Header .

For example, the sequence "%(charset)s" is the string value of the name of the character set in the extended header.

The result of the keyword conversion argument shall be the value from the applicable header field or extended header, without any trailing NULs.

All keyword values used as conversion arguments shall be translated from the UTF-8 encoding to the character set appropriate for the local file system, user database, and so on, as applicable.

7.
An additional conversion specifier character, T , shall be used to specify time formats. The T conversion specifier character can be preceded by the sequence ( keyword= subformat), where subformat is a date format as defined by date operands. The default keyword shall be mtime and the default subformat shall be:

%b %e %H:%M %Y
8.
An additional conversion specifier character, M , shall be used to specify the file mode string as defined in ls Standard Output. If ( keyword) is omitted, the mode keyword shall be used. For example, %.1M writes the single character corresponding to the <entry type> field of the ls -l command.
9.
An additional conversion specifier character, D , shall be used to specify the device for block or special files, if applicable, in an implementation-defined format. If not applicable, and ( keyword) is specified, then this conversion shall be equivalent to %(keyword)u. If not applicable, and ( keyword) is omitted, then this conversion shall be equivalent to <space>.
10.
An additional conversion specifier character, F , shall be used to specify a pathname. The F conversion character can be preceded by a sequence of comma-separated keywords:

(keyword[,keyword] ... )

The values for all the keywords that are non-null shall be concatenated together, each separated by a '/' . The default shall be ( path) if the keyword path is defined; otherwise, the default shall be ( prefix, name).

11.
An additional conversion specifier character, L , shall be used to specify a symbolic line expansion. If the current file is a symbolic link, then %L shall expand to:

"%s -> %s", <value of keyword>, <contents of link>

Otherwise, the %L conversion specification shall be the equivalent of %F .

OPERANDS

The following operands shall be supported:

directory
The destination directory pathname for copy mode.
file
A pathname of a file to be copied or archived.
pattern
A pattern matching one or more pathnames of archive members. A pattern must be given in the name-generating notation of the pattern matching notation in Pattern Matching Notation , including the filename expansion rules in Patterns Used for Filename Expansion . The default, if no pattern is specified, is to select all members in the archive.

STDIN

In write mode, the standard input shall be used only if no file operands are specified. It shall be a text file containing a list of pathnames, one per line, without leading or trailing <blank>s.

In list and read modes, if -f is not specified, the standard input shall be an archive file.

Otherwise, the standard input shall not be used.

INPUT FILES

The input file named by the archive option-argument, or standard input when the archive is read from there, shall be a file formatted according to one of the specifications in the EXTENDED DESCRIPTION section or some other implementation-defined format.

The file /dev/tty shall be used to write prompts and read responses.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of pax:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements used in the pattern matching expressions for the pattern operand, the basic regular expression for the -s option, and the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category, and pattern matching.
LC_MESSAGES
Determine the locale for the processing of affirmative responses that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_TIME
Determine the format and contents of date and time strings when the -v option is specified.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TMPDIR
Determine the pathname that provides part of the default global extended header record file, as described for the -o globexthdr= keyword in the OPTIONS section.
TZ
Determine the timezone used to calculate date and time strings when the -v option is specified. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

In write mode, if -f is not specified, the standard output shall be the archive formatted according to one of the specifications in the EXTENDED DESCRIPTION section, or some other implementation-defined format (see -x format).

In list mode, when the -o listopt= format has been specified, the selected archive members shall be written to standard output using the format described under List Mode Format Specifications . In list mode without the -o listopt= format option, the table of contents of the selected archive members shall be written to standard output using the following format:

"%s\n", <pathname>

If the -v option is specified in list mode, the table of contents of the selected archive members shall be written to standard output using the following formats.

For pathnames representing hard links to previous members of the archive:

"%s == %s\n", <ls -l listing>, <linkname>

For all other pathnames:

"%s\n", <ls -l listing>

where <ls -l listing> shall be the format specified by the ls utility with the -l option. When writing pathnames in this format, it is unspecified what is written for fields for which the underlying archive format does not have the correct information, although the correct number of <blank>-separated fields shall be written.

In list mode, standard output shall not be buffered more than a line at a time.

STDERR

If -v is specified in read, write, or copy modes, pax shall write the pathnames it processes to the standard error output using the following format:

"%s\n", <pathname>

These pathnames shall be written as soon as processing is begun on the file or archive member, and shall be flushed to standard error. The trailing <newline>, which shall not be buffered, is written when the file has been read or written.

If the -s option is specified, and the replacement string has a trailing 'p' , substitutions shall be written to standard error in the following format:

"%s >> %s\n", <original pathname>, <new pathname>

In all operating modes of pax, optional messages of unspecified format concerning the input archive format and volume number, the number of files, blocks, volumes, and media parts as well as other diagnostic messages may be written to standard error.

In all formats, for both standard output and standard error, it is unspecified how non-printable characters in pathnames or link names are written.

When pax is in read mode or list mode, using the -x pax archive format, and a filename, link name, owner name, or any other field in an extended header record cannot be translated from the pax UTF-8 codeset format to the codeset and current locale of the implementation, pax shall write a diagnostic message to standard error, shall process the file as described for the -o invalid= option, and then shall process the next file in the archive.

OUTPUT FILES

In read mode, the extracted output files shall be of the archived file type. In copy mode, the copied output files shall be the type of the file being copied. In either mode, existing files in the destination hierarchy shall be overwritten only when all permission ( -p), modification time ( -u), and invalid-value ( -o invalid=) tests allow it.

In write mode, the output file named by the -f option-argument shall be a file formatted according to one of the specifications in the EXTENDED DESCRIPTION section, or some other implementation-defined format.

EXTENDED DESCRIPTION

pax Interchange Format

A pax archive tape or file produced in the -x pax format shall contain a series of blocks. The physical layout of the archive shall be identical to the ustar format described in ustar Interchange Format . Each file archived shall be represented by the following sequence:

*
An optional header block with extended header records. This header block is of the form described in pax Header Block , with a typeflag value of x or g. The extended header records, described in pax Extended Header , shall be included as the data for this header block.

*
A header block that describes the file. Any fields in the preceding optional extended header shall override the associated fields in this header block for this file.

*
Zero or more blocks that contain the contents of the file.

At the end of the archive file there shall be two 512-byte blocks filled with binary zeros, interpreted as an end-of-archive indicator.

A schematic of an example archive with global extended header records and two actual files is shown in pax Format Archive Example . In the example, the second file in the archive has no extended header preceding it, presumably because it has no need for extended attributes.

Figure: pax Format Archive Example

pax Header Block

The pax header block shall be identical to the ustar header block described in ustar Interchange Format , except that two additional typeflag values are defined:

x
Represents extended header records for the following file in the archive (which shall have its own ustar header block). The format of these extended header records shall be as described in pax Extended Header .
g
Represents global extended header records for the following files in the archive. The format of these extended header records shall be as described in pax Extended Header . Each value shall affect all subsequent files that do not override that value in their own extended header record and until another global extended header record is reached that provides another value for the same field. The typeflag g global headers should not be used with interchange media that could suffer partial data loss in transporting the archive.

For both of these types, the size field shall be the size of the extended header records in octets. The other fields in the header block are not meaningful to this version of the pax utility. However, if this archive is read by a pax utility conforming to the ISO POSIX-2:1993 standard, the header block fields are used to create a regular file that contains the extended header records as data. Therefore, header block field values should be selected to provide reasonable file access to this regular file.

A further difference from the ustar header block is that data blocks for files of typeflag 1 (the digit one) (hard link) may be included, which means that the size field may be greater than zero. Archives created by pax -o linkdata shall include these data blocks with the hard links.

pax Extended Header

A pax extended header contains values that are inappropriate for the ustar header block because of limitations in that format: fields requiring a character encoding other than that described in the ISO/IEC 646:1991 standard, fields representing file attributes not described in the ustar header, and fields whose format or length do not fit the requirements of the ustar header. The values in an extended header add attributes to the following file (or files; see the description of the typeflag g header block) or override values in the following header block(s), as indicated in the following list of keywords.

An extended header shall consist of one or more records, each constructed as follows:

"%d %s=%s\n", <length>, <keyword>, <value>

The extended header records shall be encoded according to the ISO/IEC 10646-1:2000 standard (UTF-8). The <length> field, <blank>, equals sign, and <newline> shown shall be limited to the portable character set, as encoded in UTF-8. The <keyword> and <value> fields can be any UTF-8 characters. The <length> field shall be the decimal length of the extended header record in octets, including the trailing <newline>.

The <keyword> field shall be one of the entries from the following list or a keyword provided as an implementation extension. Keywords consisting entirely of lowercase letters, digits, and periods are reserved for future standardization. A keyword shall not include an equals sign. (In the following list, the notations "file(s)" or "block(s)" is used to acknowledge that a keyword affects the following single file after a typeflag x extended header, but possibly multiple files after typeflag g. Any requirements in the list for pax to include a record when in write or copy mode shall apply only when such a record has not already been provided through the use of the -o option. When used in copy mode, pax shall behave as if an archive had been created with applicable extended header records and then extracted.)

atime
The file access time for the following file(s), equivalent to the value of the st_atime member of the stat structure for a file, as described by the stat() function. The access time shall be restored if the process has the appropriate privilege required to do so. The format of the <value> shall be as described in pax Extended Header File Times .
charset
The name of the character set used to encode the data in the following file(s). The entries in the following table are defined to refer to known standards; additional names may be agreed on between the originator and recipient.
<value> Formal Standard
ISO-IR 646 1990 ISO/IEC 646:1990
ISO-IR 8859 1 1998 ISO/IEC 8859-1:1998
ISO-IR 8859 2 1999 ISO/IEC 8859-2:1999
ISO-IR 8859 3 1999 ISO/IEC 8859-3:1999
ISO-IR 8859 4 1998 ISO/IEC 8859-4:1998
ISO-IR 8859 5 1999 ISO/IEC 8859-5:1999
ISO-IR 8859 6 1999 ISO/IEC 8859-6:1999
ISO-IR 8859 7 1987 ISO/IEC 8859-7:1987
ISO-IR 8859 8 1999 ISO/IEC 8859-8:1999
ISO-IR 8859 9 1999 ISO/IEC 8859-9:1999
ISO-IR 8859 10 1998 ISO/IEC 8859-10:1998
ISO-IR 8859 13 1998 ISO/IEC 8859-13:1998
ISO-IR 8859 14 1998 ISO/IEC 8859-14:1998
ISO-IR 8859 15 1999 ISO/IEC 8859-15:1999
ISO-IR 10646 2000 ISO/IEC 10646:2000
ISO-IR 10646 2000 UTF-8 ISO/IEC 10646, UTF-8 encoding
BINARY None.

The encoding is included in an extended header for information only; when pax is used as described in IEEE Std 1003.1-2001, it shall not translate the file data into any other encoding. The BINARY entry indicates unencoded binary data.

When used in write or copy mode, it is implementation-defined whether pax includes a charset extended header record for a file.

comment
A series of characters used as a comment. All characters in the <value> field shall be ignored by pax.
ctime
The file creation time for the following file(s), equivalent to the value of the st_ctime member of the stat structure for a file, as described by the stat() function. The creation time shall be restored if the process has the appropriate privilege required to do so. The format of the <value> shall be as described in pax Extended Header File Times .
gid
The group ID of the group that owns the file, expressed as a decimal number using digits from the ISO/IEC 646:1991 standard. This record shall override the gid field in the following header block(s). When used in write or copy mode, pax shall include a gid extended header record for each file whose group ID is greater than 2097151 (octal 7777777).
gname
The group of the file(s), formatted as a group name in the group database. This record shall override the gid and gname fields in the following header block(s), and any gid extended header record. When used in read, copy, or list mode, pax shall translate the name from the UTF-8 encoding in the header record to the character set appropriate for the group database on the receiving system. If any of the UTF-8 characters cannot be translated, and if the -o invalid= UTF-8 option is not specified, the results are implementation-defined. When used in write or copy mode, pax shall include a gname extended header record for each file whose group name cannot be represented entirely with the letters and digits of the portable character set.
linkpath
The pathname of a link being created to another file, of any type, previously archived. This record shall override the linkname field in the following ustar header block(s). The following ustar header block shall determine the type of link created. If typeflag of the following header block is 1, it shall be a hard link. If typeflag is 2, it shall be a symbolic link and the linkpath value shall be the contents of the symbolic link. The pax utility shall translate the name of the link (contents of the symbolic link) from the UTF-8 encoding to the character set appropriate for the local file system. When used in write or copy mode, pax shall include a linkpath extended header record for each link whose pathname cannot be represented entirely with the members of the portable character set other than NUL.
mtime
The file modification time of the following file(s), equivalent to the value of the st_mtime member of the stat structure for a file, as described in the stat() function. This record shall override the mtime field in the following header block(s). The modification time shall be restored if the process has the appropriate privilege required to do so. The format of the <value> shall be as described in pax Extended Header File Times .
path
The pathname of the following file(s). This record shall override the name and prefix fields in the following header block(s). The pax utility shall translate the pathname of the file from the UTF-8 encoding to the character set appropriate for the local file system.

When used in write or copy mode, pax shall include a path extended header record for each file whose pathname cannot be represented entirely with the members of the portable character set other than NUL.

realtime.any
The keywords prefixed by "realtime." are reserved for future standardization.
security.any
The keywords prefixed by "security." are reserved for future standardization.
size
The size of the file in octets, expressed as a decimal number using digits from the ISO/IEC 646:1991 standard. This record shall override the size field in the following header block(s). When used in write or copy mode, pax shall include a size extended header record for each file with a size value greater than 8589934591 (octal 77777777777).
uid
The user ID of the file owner, expressed as a decimal number using digits from the ISO/IEC 646:1991 standard. This record shall override the uid field in the following header block(s). When used in write or copy mode, pax shall include a uid extended header record for each file whose owner ID is greater than 2097151 (octal 7777777).
uname
The owner of the following file(s), formatted as a user name in the user database. This record shall override the uid and uname fields in the following header block(s), and any uid extended header record. When used in read, copy, or list mode, pax shall translate the name from the UTF-8 encoding in the header record to the character set appropriate for the user database on the receiving system. If any of the UTF-8 characters cannot be translated, and if the -o invalid= UTF-8 option is not specified, the results are implementation-defined. When used in write or copy mode, pax shall include a uname extended header record for each file whose user name cannot be represented entirely with the letters and digits of the portable character set.

If the <value> field is zero length, it shall delete any header block field, previously entered extended header value, or global extended header value of the same name.

If a keyword in an extended header record (or in a -o option-argument) overrides or deletes a corresponding field in the ustar header block, pax shall ignore the contents of that header block field.

Unlike the ustar header block fields, NULs shall not delimit <value>s; all characters within the <value> field shall be considered data for the field. None of the length limitations of the ustar header block fields in ustar Header Block shall apply to the extended header records.

pax Extended Header Keyword Precedence

This section describes the precedence in which the various header records and fields and command line options are selected to apply to a file in the archive. When pax is used in read or list modes, it shall determine a file attribute in the following sequence:

1.
If -o delete= keyword-prefix is used, the affected attributes shall be determined from step 7., if applicable, or ignored otherwise.

2.
If -o keyword:= is used, the affected attributes shall be ignored.

3.
If -o keyword := value is used, the affected attribute shall be assigned the value.

4.
If there is a typeflag x extended header record, the affected attribute shall be assigned the <value>. When extended header records conflict, the last one given in the header shall take precedence.

5.
If -o keyword = value is used, the affected attribute shall be assigned the value.

6.
If there is a typeflag g global extended header record, the affected attribute shall be assigned the <value>. When global extended header records conflict, the last one given in the global header shall take precedence.

7.
Otherwise, the attribute shall be determined from the ustar header block.

pax Extended Header File Times

The pax utility shall write an mtime record for each file in write or copy modes if the file's modification time cannot be represented exactly in the ustar header logical record described in ustar Interchange Format . This can occur if the time is out of ustar range, or if the file system of the underlying implementation supports non-integer time granularities and the time is not an integer. All of these time records shall be formatted as a decimal representation of the time in seconds since the Epoch. If a period ( '.' ) decimal point character is present, the digits to the right of the point shall represent the units of a subsecond timing granularity, where the first digit is tenths of a second and each subsequent digit is a tenth of the previous digit. In read or copy mode, the pax utility shall truncate the time of a file to the greatest value that is not greater than the input header file time. In write or copy mode, the pax utility shall output a time exactly if it can be represented exactly as a decimal number, and otherwise shall generate only enough digits so that the same time shall be recovered if the file is extracted on a system whose underlying implementation supports the same time granularity.

ustar Interchange Format

A ustar archive tape or file shall contain a series of logical records. Each logical record shall be a fixed-size logical record of 512 octets (see below). Although this format may be thought of as being stored on 9-track industry-standard 12.7 mm (0.5 in) magnetic tape, other types of transportable media are not excluded. Each file archived shall be represented by a header logical record that describes the file, followed by zero or more logical records that give the contents of the file. At the end of the archive file there shall be two 512-octet logical records filled with binary zeros, interpreted as an end-of-archive indicator.

The logical records may be grouped for physical I/O operations, as described under the -b blocksize and -x ustar options. Each group of logical records may be written with a single operation equivalent to the write() function. On magnetic tape, the result of this write shall be a single tape physical block. The last physical block shall always be the full size, so logical records after the two zero logical records may contain undefined data.

The header logical record shall be structured as shown in the following table. All lengths and offsets are in decimal.

Table: ustar Header Block
Field Name | Octet Offset | Length (in Octets)
name | 0 | 100
mode | 100 | 8
uid | 108 | 8
gid | 116 | 8
size | 124 | 12
mtime | 136 | 12
chksum | 148 | 8
typeflag | 156 | 1
linkname | 157 | 100
magic | 257 | 6
version | 263 | 2
uname | 265 | 32
gname | 297 | 32
devmajor | 329 | 8
devminor | 337 | 8
prefix | 345 | 155

All characters in the header logical record shall be represented in the coded character set of the ISO/IEC 646:1991 standard. For maximum portability between implementations, names should be selected from characters represented by the portable filename character set as octets with the most significant bit zero. If an implementation supports the use of characters outside of slash and the portable filename character set in names for files, users, and groups, one or more implementation-defined encodings of these characters shall be provided for interchange purposes.

However, the pax utility shall never create filenames on the local system that cannot be accessed via the procedures described in IEEE Std 1003.1-2001. If a filename is found on the medium that would create an invalid filename, it is implementation-defined whether the data from the file is stored on the file hierarchy and under what name it is stored. The pax utility may choose to ignore these files as long as it produces an error indicating that the file is being ignored.

Each field within the header logical record is contiguous; that is, there is no padding used. Each character on the archive medium shall be stored contiguously.

The fields magic, uname, and gname are character strings each terminated by a NUL character. The fields name, linkname, and prefix are NUL-terminated character strings except when all characters in the array contain non-NUL characters including the last character. The version field is two octets containing the characters "00" (zero-zero). The typeflag contains a single character. All other fields are leading zero-filled octal numbers using digits from the ISO/IEC 646:1991 standard IRV. Each numeric field is terminated by one or more <space> or NUL characters.

The name and the prefix fields shall produce the pathname of the file. A new pathname shall be formed, if prefix is not an empty string (its first character is not NUL), by concatenating prefix (up to the first NUL character), a slash character, and name; otherwise, name is used alone. In either case, name is terminated at the first NUL character. If prefix begins with a NUL character, it shall be ignored. In this manner, pathnames of at most 256 characters can be supported. If a pathname does not fit in the space provided, pax shall notify the user of the error, and shall not store any part of the file-header or data-on the medium.

The linkname field, described below, shall not use the prefix to produce a pathname. As such, a linkname is limited to 100 characters. If the name does not fit in the space provided, pax shall notify the user of the error, and shall not attempt to store the link on the medium.

The mode field provides 12 bits encoded in the ISO/IEC 646:1991 standard octal digit representation. The encoded bits shall represent the following values:

Table: ustar mode Field
Bit Value | IEEE Std 1003.1-2001 Bit | Description
04000 | S_ISUID | Set UID on execution.
02000 | S_ISGID | Set GID on execution.
01000 | <reserved> | Reserved for future standardization.
00400 | S_IRUSR | Read permission for file owner class.
00200 | S_IWUSR | Write permission for file owner class.
00100 | S_IXUSR | Execute/search permission for file owner class.
00040 | S_IRGRP | Read permission for file group class.
00020 | S_IWGRP | Write permission for file group class.
00010 | S_IXGRP | Execute/search permission for file group class.
00004 | S_IROTH | Read permission for file other class.
00002 | S_IWOTH | Write permission for file other class.
00001 | S_IXOTH | Execute/search permission for file other class.

When appropriate privilege is required to set one of these mode bits, and the user restoring the files from the archive does not have the appropriate privilege, the mode bits for which the user does not have appropriate privilege shall be ignored. Some of the mode bits in the archive format are not mentioned elsewhere in this volume of IEEE Std 1003.1-2001. If the implementation does not support those bits, they may be ignored.

The uid and gid fields are the user and group ID of the owner and group of the file, respectively.

The size field is the size of the file in octets. If the typeflag field is set to specify a file to be of type 1 (a link) or 2 (a symbolic link), the size field shall be specified as zero. If the typeflag field is set to specify a file of type 5 (directory), the size field shall be interpreted as described under the definition of that record type. No data logical records are stored for types 1, 2, or 5. If the typeflag field is set to 3 (character special file), 4 (block special file), or 6 (FIFO), the meaning of the size field is unspecified by this volume of IEEE Std 1003.1-2001, and no data logical records shall be stored on the medium. Additionally, for type 6, the size field shall be ignored when reading. If the typeflag field is set to any other value, the number of logical records written following the header shall be ( size+511)/512, ignoring any fraction in the result of the division.

The mtime field shall be the modification time of the file at the time it was archived. It is the ISO/IEC 646:1991 standard representation of the octal value of the modification time obtained from the stat() function.

The chksum field shall be the ISO/IEC 646:1991 standard IRV representation of the octal value of the simple sum of all octets in the header logical record. Each octet in the header shall be treated as an unsigned value. These values shall be added to an unsigned integer, initialized to zero, the precision of which is not less than 17 bits. When calculating the checksum, the chksum field is treated as if it were all spaces.

The typeflag field specifies the type of file archived. If a particular implementation does not recognize the type, or the user does not have appropriate privilege to create that type, the file shall be extracted as if it were a regular file if the file type is defined to have a meaning for the size field that could cause data logical records to be written on the medium (see the previous description for size). If conversion to a regular file occurs, the pax utility shall produce an error indicating that the conversion took place. All of the typeflag fields shall be coded in the ISO/IEC 646:1991 standard IRV:

0
Represents a regular file. For backwards-compatibility, a typeflag value of binary zero ( '\0' ) should be recognized as meaning a regular file when extracting files from the archive. Archives written with this version of the archive file format create regular files with a typeflag value of the ISO/IEC 646:1991 standard IRV '0' .
1
Represents a file linked to another file, of any type, previously archived. Such files are identified by each file having the same device and file serial number. The linked-to name is specified in the linkname field with a NUL-character terminator if it is less than 100 octets in length.
2
Represents a symbolic link. The contents of the symbolic link shall be stored in the linkname field.
3,4
Represent character special files and block special files respectively. In this case the devmajor and devminor fields shall contain information defining the device, the format of which is unspecified by this volume of IEEE Std 1003.1-2001. Implementations may map the device specifications to their own local specification or may ignore the entry.
5
Specifies a directory or subdirectory. On systems where disk allocation is performed on a directory basis, the size field shall contain the maximum number of octets (which may be rounded to the nearest disk block allocation unit) that the directory may hold. A size field of zero indicates no such limiting. Systems that do not support limiting in this manner should ignore the size field.
6
Specifies a FIFO special file. Note that the archiving of a FIFO file archives the existence of this file and not its contents.
7
Reserved to represent a file to which an implementation has associated some high-performance attribute. Implementations without such extensions should treat this file as a regular file (type 0).
A-Z
The letters 'A' to 'Z' , inclusive, are reserved for custom implementations. All other values are reserved for future versions of IEEE Std 1003.1-2001.

Attempts to archive a socket using ustar interchange format shall produce a diagnostic message. Handling of other file types is implementation-defined.

The magic field is the specification that this archive was output in this archive format. If this field contains ustar (the five characters from the ISO/IEC 646:1991 standard IRV shown followed by NUL), the uname and gname fields shall contain the ISO/IEC 646:1991 standard IRV representation of the owner and group of the file, respectively (truncated to fit, if necessary). When the file is restored by a privileged, protection-preserving version of the utility, the user and group databases shall be scanned for these names. If found, the user and group IDs contained within these files shall be used rather than the values contained within the uid and gid fields.

cpio Interchange Format

The octet-oriented cpio archive format shall be a series of entries, each comprising a header that describes the file, the name of the file, and then the contents of the file.

An archive may be recorded as a series of fixed-size blocks of octets. This blocking shall be used only to make physical I/O more efficient. The last group of blocks shall always be at the full size.

For the octet-oriented cpio archive format, the individual entry information shall be in the order indicated and described by the following table; see also the <cpio.h> header.

Table: Octet-Oriented cpio Archive Entry
Header Field Name | Length (in Octets) | Interpreted as
c_magic | 6 | Octal number
c_dev | 6 | Octal number
c_ino | 6 | Octal number
c_mode | 6 | Octal number
c_uid | 6 | Octal number
c_gid | 6 | Octal number
c_nlink | 6 | Octal number
c_rdev | 6 | Octal number
c_mtime | 11 | Octal number
c_namesize | 6 | Octal number
c_filesize | 11 | Octal number
Filename Field Name | Length | Interpreted as
c_name | c_namesize | Pathname string
File Data Field Name | Length | Interpreted as
c_filedata | c_filesize | Data

cpio Header

For each file in the archive, a header as defined previously shall be written. The information in the header fields is written as streams of the ISO/IEC 646:1991 standard characters interpreted as octal numbers. The octal numbers shall be extended to the necessary length by appending the ISO/IEC 646:1991 standard IRV zeros at the most-significant-digit end of the number; the result is written to the most-significant digit of the stream of octets first. The fields shall be interpreted as follows:

c_magic
Identify the archive as being a transportable archive by containing the identifying value "070707" .
c_dev, c_ino
Contains values that uniquely identify the file within the archive (that is, no files contain the same pair of c_dev and c_ino values unless they are links to the same file). The values shall be determined in an unspecified manner.
c_mode
Contains the file type and access permissions as defined in the following table.

Table: Values for cpio c_mode Field
File Permissions Name Value Indicates
C_IRUSR 000400 Read by owner
C_IWUSR 000200 Write by owner
C_IXUSR 000100 Execute by owner
C_IRGRP 000040 Read by group
C_IWGRP 000020 Write by group
C_IXGRP 000010 Execute by group
C_IROTH 000004 Read by others
C_IWOTH 000002 Write by others
C_IXOTH 000001 Execute by others
C_ISUID 004000 Set uid
C_ISGID 002000 Set gid
C_ISVTX 001000 Reserved
File Type Name Value Indicates
C_ISDIR 040000 Directory
C_ISFIFO 010000 FIFO
C_ISREG 0100000 Regular file
C_ISLNK 0120000 Symbolic link
C_ISBLK 060000 Block special file
C_ISCHR 020000 Character special file
C_ISSOCK 0140000 Socket
C_ISCTG 0110000 Reserved

Directories, FIFOs, symbolic links, and regular files shall be supported on a system conforming to this volume of IEEE Std 1003.1-2001; additional values defined previously are reserved for compatibility with existing systems. Additional file types may be supported; however, such files should not be written to archives intended to be transported to other systems.

c_uid
Contains the user ID of the owner.
c_gid
Contains the group ID of the group.
c_nlink
Contains the number of links referencing the file at the time the archive was created.
c_rdev
Contains implementation-defined information for character or block special files.
c_mtime
Contains the latest time of modification of the file at the time the archive was created.
c_namesize
Contains the length of the pathname, including the terminating NUL character.
c_filesize
Contains the length of the file in octets. This shall be the length of the data section following the header structure.

cpio Filename

The c_name field shall contain the pathname of the file. The length of this field in octets is the value of c_namesize.

If a filename is found on the medium that would create an invalid pathname, it is implementation-defined whether the data from the file is stored on the file hierarchy and under what name it is stored.

All characters shall be represented in the ISO/IEC 646:1991 standard IRV. For maximum portability between implementations, names should be selected from characters represented by the portable filename character set as octets with the most significant bit zero. If an implementation supports the use of characters outside the portable filename character set in names for files, users, and groups, one or more implementation-defined encodings of these characters shall be provided for interchange purposes. However, the pax utility shall never create filenames on the local system that cannot be accessed via the procedures described previously in this volume of IEEE Std 1003.1-2001. If a filename is found on the medium that would create an invalid filename, it is implementation-defined whether the data from the file is stored on the local file system and under what name it is stored. The pax utility may choose to ignore these files as long as it produces an error indicating that the file is being ignored.

cpio File Data

Following c_name, there shall be c_filesize octets of data. Interpretation of such data occurs in a manner dependent on the file. If c_filesize is zero, no data shall be contained in c_filedata.

When restoring from an archive:

*
If the user does not have the appropriate privilege to create a file of the specified type, pax shall ignore the entry and write an error message to standard error.

*
Only regular files have data to be restored. Presuming a regular file meets any selection criteria that might be imposed on the format-reading utility by the user, such data shall be restored.

*
If a user does not have appropriate privilege to set a particular mode flag, the flag shall be ignored. Some of the mode flags in the archive format are not mentioned elsewhere in this volume of IEEE Std 1003.1-2001. If the implementation does not support those flags, they may be ignored.

cpio Special Entries

FIFO special files, directories, and the trailer shall be recorded with c_filesize equal to zero. For other special files, c_filesize is unspecified by this volume of IEEE Std 1003.1-2001. The header for the next file entry in the archive shall be written directly after the last octet of the file entry preceding it. A header denoting the filename TRAILER!!! shall indicate the end of the archive; the contents of octets in the last block of the archive following such a header are undefined.

EXIT STATUS

The following exit values shall be returned:

0
All files were processed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If pax cannot create a file or a link when reading an archive or cannot find a file when writing an archive, or cannot preserve the user ID, group ID, or file mode when the -p option is specified, a diagnostic message shall be written to standard error and a non-zero exit status shall be returned, but processing shall continue. In the case where pax cannot create a link to a file, pax shall not, by default, create a second copy of the file.

If the extraction of a file from an archive is prematurely terminated by a signal or error, pax may have only partially extracted the file or (if the -n option was not specified) may have extracted a file of the same name as that specified by the user, but which is not the file the user wanted. Additionally, the file modes of extracted directories may have additional bits from the S_IRWXU mask set as well as incorrect modification and access times.

The following sections are informative.

APPLICATION USAGE

The -p (privileges) option was invented to reconcile differences between historical tar and cpio implementations. In particular, the two utilities use -m in diametrically opposed ways. The -p option also provides a consistent means of extending the ways in which future file attributes can be addressed, such as for enhanced security systems or high-performance files. Although it may seem complex, there are really two modes that are most commonly used:

-p e
``Preserve everything". This would be used by the historical superuser, someone with all the appropriate privileges, to preserve all aspects of the files as they are recorded in the archive. The e flag is the sum of o and p, and other implementation-defined attributes.
-p p
``Preserve" the file mode bits. This would be used by the user with regular privileges who wished to preserve aspects of the file other than the ownership. The file times are preserved by default, but two other flags are offered to disable these and use the time of extraction.

The one pathname per line format of standard input precludes pathnames containing <newline>s. Although such pathnames violate the portable filename guidelines, they may exist and their presence may inhibit usage of pax within shell scripts. This problem is inherited from historical archive programs. The problem can be avoided by listing filename arguments on the command line instead of on standard input.

It is almost certain that appropriate privileges are required for pax to accomplish parts of this volume of IEEE Std 1003.1-2001. Specifically, creating files of type block special or character special, restoring file access times unless the files are owned by the user (the -t option), or preserving file owner, group, and mode (the -p option) all probably require appropriate privileges.

In read mode, implementations are permitted to overwrite files when the archive has multiple members with the same name. This may fail if permissions on the first version of the file do not permit it to be overwritten.

The cpio and ustar formats can only support files up to 8589934592 bytes (8 * 2^30) in size.

EXAMPLES

The following command:

pax -w -f /dev/rmt/1m .

copies the contents of the current directory to tape drive 1, medium density (assuming historical System V device naming procedures-the historical BSD device name would be /dev/rmt9).

The following commands:

mkdir newdirpax -rw olddir newdir

copy the olddir directory hierarchy to newdir.

pax -r -s ',^//*usr//*,,' -f a.pax

reads the archive a.pax, with all files rooted in /usr in the archive extracted relative to the current directory.

Using the option:

-o listopt="%M %(atime)T %(size)D %(name)s"

overrides the default output description in Standard Output and instead writes:

-rw-rw--- Jan 12 15:53 1492 /usr/foo/bar

Using the options:

-o listopt='%L\t%(size)D\n%.7' \
-o listopt='(name)s\n%(ctime)T\n%T'

overrides the default output description in Standard Output and instead writes:

/usr/foo/bar -> /tmp   1492
/usr/fo
Jan 12 1991
Jan 31 15:53

RATIONALE

The pax utility was new for the ISO POSIX-2:1993 standard. It represents a peaceful compromise between advocates of the historical tar and cpio utilities.

A fundamental difference between cpio and tar was in the way directories were treated. The cpio utility did not treat directories differently from other files, and to select a directory and its contents required that each file in the hierarchy be explicitly specified. For tar, a directory matched every file in the file hierarchy it rooted.

The pax utility offers both interfaces; by default, directories map into the file hierarchy they root. The -d option causes pax to skip any file not explicitly referenced, as cpio historically did. The tar - style behavior was chosen as the default because it was believed that this was the more common usage and because tar is the more commonly available interface, as it was historically provided on both System V and BSD implementations.

The data interchange format specification in this volume of IEEE Std 1003.1-2001 requires that processes with "appropriate privileges" shall always restore the ownership and permissions of extracted files exactly as archived. If viewed from the historic equivalence between superuser and "appropriate privileges", there are two problems with this requirement. First, users running as superusers may unknowingly set dangerous permissions on extracted files. Second, it is needlessly limiting, in that superusers cannot extract files and own them as superuser unless the archive was created by the superuser. (It should be noted that restoration of ownerships and permissions for the superuser, by default, is historical practice in cpio, but not in tar.) In order to avoid these two problems, the pax specification has an additional "privilege" mechanism, the -p option. Only a pax invocation with the privileges needed, and which has the -p option set using the e specification character, has the "appropriate privilege" to restore full ownership and permission information.

Note also that this volume of IEEE Std 1003.1-2001 requires that the file ownership and access permissions shall be set, on extraction, in the same fashion as the creat() function when provided with the mode stored in the archive. This means that the file creation mask of the user is applied to the file permissions.

Users should note that directories may be created by pax while extracting files with permissions that are different from those that existed at the time the archive was created. When extracting sensitive information into a directory hierarchy that no longer exists, users are encouraged to set their file creation mask appropriately to protect these files during extraction.

The table of contents output is written to standard output to facilitate pipeline processing.

An early proposal had hard links displaying for all pathnames. This was removed because it complicates the output of the case where -v is not specified and does not match historical cpio usage. The hard-link information is available in the -v display.

The description of the -l option allows implementations to make hard links to symbolic links. IEEE Std 1003.1-2001 does not specify any way to create a hard link to a symbolic link, but many implementations provide this capability as an extension. If there are hard links to symbolic links when an archive is created, the implementation is required to archive the hard link in the archive (unless -H or -L is specified). When in read mode and in copy mode, implementations supporting hard links to symbolic links should use them when appropriate.

The archive formats inherited from the POSIX.1-1990 standard have certain restrictions that have been brought along from historical usage. For example, there are restrictions on the length of pathnames stored in the archive. When pax is used in copy( -rw) mode (copying directory hierarchies), the ability to use extensions from the -x pax format overcomes these restrictions.

The default blocksize value of 5120 bytes for cpio was selected because it is one of the standard block-size values for cpio, set when the -B option is specified. (The other default block-size value for cpio is 512 bytes, and this was considered to be too small.) The default block value of 10240 bytes for tar was selected because that is the standard block-size value for BSD tar. The maximum block size of 32256 bytes (2**15-512 bytes) is the largest multiple of 512 bytes that fits into a signed 16-bit tape controller transfer register. There are known limitations in some historical systems that would prevent larger blocks from being accepted. Historical values were chosen to improve compatibility with historical scripts using dd or similar utilities to manipulate archives. Also, default block sizes for any file type other than character special file has been deleted from this volume of IEEE Std 1003.1-2001 as unimportant and not likely to affect the structure of the resulting archive.

Implementations are permitted to modify the block-size value based on the archive format or the device to which the archive is being written. This is to provide implementations with the opportunity to take advantage of special types of devices, and it should not be used without a great deal of consideration as it almost certainly decreases archive portability.

The intended use of the -n option was to permit extraction of one or more files from the archive without processing the entire archive. This was viewed by the standard developers as offering significant performance advantages over historical implementations. The -n option in early proposals had three effects; the first was to cause special characters in patterns to not be treated specially. The second was to cause only the first file that matched a pattern to be extracted. The third was to cause pax to write a diagnostic message to standard error when no file was found matching a specified pattern. Only the second behavior is retained by this volume of IEEE Std 1003.1-2001, for many reasons. First, it is in general not acceptable for a single option to have multiple effects. Second, the ability to make pattern matching characters act as normal characters is useful for parts of pax other than file extraction. Third, a finer degree of control over the special characters is useful because users may wish to normalize only a single special character in a single filename. Fourth, given a more general escape mechanism, the previous behavior of the -n option can be easily obtained using the -s option or a sed script. Finally, writing a diagnostic message when a pattern specified by the user is unmatched by any file is useful behavior in all cases.

In this version, the -n was removed from the copy mode synopsis of pax; it is inapplicable because there are no pattern operands specified in this mode.

There is another method than pax for copying subtrees in IEEE Std 1003.1-2001 described as part of the cp utility. Both methods are historical practice: cp provides a simpler, more intuitive interface, while pax offers a finer granularity of control. Each provides additional functionality to the other; in particular, pax maintains the hard-link structure of the hierarchy while cp does not. It is the intention of the standard developers that the results be similar (using appropriate option combinations in both utilities). The results are not required to be identical; there seemed insufficient gain to applications to balance the difficulty of implementations having to guarantee that the results would be exactly identical.

A single archive may span more than one file. It is suggested that implementations provide informative messages to the user on standard error whenever the archive file is changed.

The -d option (do not create intermediate directories not listed in the archive) found in early proposals was originally provided as a complement to the historic -d option of cpio. It has been deleted.

The -s option in early proposals specified a subset of the substitution command from the ed utility. As there was no reason for only a subset to be supported, the -s option is now compatible with the current ed specification. Since the delimiter can be any non-null character, the following usage with single spaces is valid:

pax -s " foo bar " ...

The -t description is worded so as to note that this may cause the access time update caused by some other activity (which occurs while the file is being read) to be overwritten.

The default behavior of pax with regard to file modification times is the same as historical implementations of tar. It is not the historical behavior of cpio.

Because the -i option uses /dev/tty, utilities without a controlling terminal are not able to use this option.

The -y option, found in early proposals, has been deleted because a line containing a single period for the -i option has equivalent functionality. The special lines for the -i option (a single period and the empty line) are historical practice in cpio.

In early drafts, a -e charmap option was included to increase portability of files between systems using different coded character sets. This option was omitted because it was apparent that consensus could not be formed for it. In this version, the use of UTF-8 should be an adequate substitute.

The -k option was added to address international concerns about the dangers involved in the character set transformations of -e (if the target character set were different from the source, the filenames might be transformed into names matching existing files) and also was made more general to protect files transferred between file systems with different {NAME_MAX} values (truncating a filename on a smaller system might also inadvertently overwrite existing files). As stated, it prevents any overwriting, even if the target file is older than the source. This version adds more granularity of options to solve this problem by introducing the -o invalid= option-specifically the UTF-8 action. (Note that an existing file that is named with a UTF-8 encoding is still subject to overwriting in this case. The -k option closes that loophole.)

Some of the file characteristics referenced in this volume of IEEE Std 1003.1-2001 might not be supported by some archive formats. For example, neither the tar nor cpio formats contain the file access time. For this reason, the e specification character has been provided, intended to cause all file characteristics specified in the archive to be retained.

It is required that extracted directories, by default, have their access and modification times and permissions set to the values specified in the archive. This has obvious problems in that the directories are almost certainly modified after being extracted and that directory permissions may not permit file creation. One possible solution is to create directories with the mode specified in the archive, as modified by the umask of the user, with sufficient permissions to allow file creation. After all files have been extracted, pax would then reset the access and modification times and permissions as necessary.

The list-mode formatting description borrows heavily from the one defined by the printf utility. However, since there is no separate operand list to get conversion arguments, the format was extended to allow specifying the name of the conversion argument as part of the conversion specification.

The T conversion specifier allows time fields to be displayed in any of the date formats. Unlike the ls utility, pax does not adjust the format when the date is less than six months in the past. This makes parsing the output more predictable.

The D conversion specifier handles the ability to display the major/minor or file size, as with ls, by using %-8(size)D.

The L conversion specifier handles the ls display for symbolic links.

Conversion specifiers were added to generate existing known types used for ls.

pax Interchange Format

The new POSIX data interchange format was developed primarily to satisfy international concerns that the ustar and cpio formats did not provide for file, user, and group names encoded in characters outside a subset of the ISO/IEC 646:1991 standard. The standard developers realized that this new POSIX data interchange format should be very extensible because there were other requirements they foresaw in the near future:

*
Support international character encodings and locale information

*
Support security information (ACLs, and so on)

*
Support future file types, such as realtime or contiguous files

*
Include data areas for implementation use

*
Support systems with words larger than 32 bits and timers with subsecond granularity

The following were not goals for this format because these are better handled by separate utilities or are inappropriate for a portable format:

*
Encryption

*
Compression

*
Data translation between locales and codesets

*
inode storage

The format chosen to support the goals is an extension of the ustar format. Of the two formats previously available, only the ustar format was selected for extensions because:

*
It was easier to extend in an upwards-compatible way. It offered version flags and header block type fields with room for future standardization. The cpio format, while possessing a more flexible file naming methodology, could not be extended without breaking some theoretical implementation or using a dummy filename that could be a legitimate filename.

*
Industry experience since the original " tar wars" fought in developing the ISO POSIX-1 standard has clearly been in favor of the ustar format, which is generally the default output format selected for pax implementations on new systems.

The new format was designed with one additional goal in mind: reasonable behavior when an older tar or pax utility happened to read an archive. Since the POSIX.1-1990 standard mandated that a "format-reading utility" had to treat unrecognized typeflag values as regular files, this allowed the format to include all the extended information in a pseudo-regular file that preceded each real file. An option is given that allows the archive creator to set up reasonable names for these files on the older systems. Also, the normative text suggests that reasonable file access values be used for this ustar header block. Making these header files inaccessible for convenient reading and deleting would not be reasonable. File permissions of 600 or 700 are suggested.

The ustar typeflag field was used to accommodate the additional functionality of the new format rather than magic or version because the POSIX.1-1990 standard (and, by reference, the previous version of pax), mandated the behavior of the format-reading utility when it encountered an unknown typeflag, but was silent about the other two fields.

Early proposals of the first revision to IEEE Std 1003.1-2001 contained a proposed archive format that was based on compatibility with the standard for tape files (ISO 1001, similar to the format used historically on many mainframes and minicomputers). This format was overly complex and required considerable overhead in volume and header records. Furthermore, the standard developers felt that it would not be acceptable to the community of POSIX developers, so it was later changed to be a format more closely related to historical practice on POSIX systems.

The prefix and name split of pathnames in ustar was replaced by the single path extended header record for simplicity.

The concept of a global extended header ( typeflag g) was controversial. If this were applied to an archive being recorded on magnetic tape, a few unreadable blocks at the beginning of the tape could be a serious problem; a utility attempting to extract as many files as possible from a damaged archive could lose a large percentage of file header information in this case. However, if the archive were on a reliable medium, such as a CD-ROM, the global extended header offers considerable potential size reductions by eliminating redundant information. Thus, the text warns against using the global method for unreliable media and provides a method for implanting global information in the extended header for each file, rather than in the typeflag g records.

No facility for data translation or filtering on a per-file basis is included because the standard developers could not invent an interface that would allow this in an efficient manner. If a filter, such as encryption or compression, is to be applied to all the files, it is more efficient to apply the filter to the entire archive as a single file. The standard developers considered interfaces that would invoke a shell script for each file going into or out of the archive, but the system overhead in this approach was considered to be too high.

One such approach would be to have filter= records that give a pathname for an executable. When the program is invoked, the file and archive would be open for standard input/output and all the header fields would be available as environment variables or command-line arguments. The standard developers did discuss such schemes, but they were omitted from IEEE Std 1003.1-2001 due to concerns about excessive overhead. Also, the program itself would need to be in the archive if it were to be used portably.

There is currently no portable means of identifying the character set(s) used for a file in the file system. Therefore, pax has not been given a mechanism to generate charset records automatically. The only portable means of doing this is for the user to write the archive using the -o charset= string command line option. This assumes that all of the files in the archive use the same encoding. The "implementation-defined" text is included to allow for a system that can identify the encodings used for each of its files.

The table of standards that accompanies the charset record description is acknowledged to be very limited. Only a limited number of character set standards is reasonable for maximal interchange. Any character set is, of course, possible by prior agreement. It was suggested that EBCDIC be listed, but it was omitted because it is not defined by a formal standard. Formal standards, and then only those with reasonably large followings, can be included here, simply as a matter of practicality. The <value>s represent names of officially registered character sets in the format required by the ISO 2375:1985 standard.

The normal comma or <blank>-separated list rules are not followed in the case of keyword options to allow ease of argument parsing for getopts.

Further information on character encodings is in pax Archive Character Set Encoding/Decoding .

The standard developers have reserved keyword name space for vendor extensions. It is suggested that the format to be used is:

VENDOR.keyword

where VENDOR is the name of the vendor or organization in all uppercase letters. It is further suggested that the keyword following the period be named differently than any of the standard keywords so that it could be used for future standardization, if appropriate, by omitting the VENDOR prefix.

The <length> field in the extended header record was included to make it simpler to step through the records, even if a record contains an unknown format (to a particular pax) with complex interactions of special characters. It also provides a minor integrity checkpoint within the records to aid a program attempting to recover files from a damaged archive.

There are no extended header versions of the devmajor and devminor fields because the unspecified format ustar header field should be sufficient. If they are not, vendor-specific extended keywords (such as VENDOR.devmajor) should be used.

Device and i-number labeling of files was not adopted from cpio; files are interchanged strictly on a symbolic name basis, as in ustar.

Just as with the ustar format descriptions, the new format makes no special arrangements for multi-volume archives. Each of the pax archive types is assumed to be inside a single POSIX file and splitting that file over multiple volumes (diskettes, tape cartridges, and so on), processing their labels, and mounting each in the proper sequence are considered to be implementation details that cannot be described portably.

The pax format is intended for interchange, not only for backup on a single (family of) systems. It is not as densely packed as might be possible for backup:

*
It contains information as coded characters that could be coded in binary.

*
It identifies extended records with name fields that could be omitted in favor of a fixed-field layout.

*
It translates names into a portable character set and identifies locale-related information, both of which are probably unnecessary for backup.

The requirements on restoring from an archive are slightly different from the historical wording, allowing for non-monolithic privilege to bring forward as much as possible. In particular, attributes such as "high performance file" might be broadly but not universally granted while set-user-ID or chown() might be much more restricted. There is no implication in IEEE Std 1003.1-2001 that the security information be honored after it is restored to the file hierarchy, in spite of what might be improperly inferred by the silence on that topic. That is a topic for another standard.

Links are recorded in the fashion described here because a link can be to any file type. It is desirable in general to be able to restore part of an archive selectively and restore all of those files completely. If the data is not associated with each link, it is not possible to do this. However, the data associated with a file can be large, and when selective restoration is not needed, this can be a significant burden. The archive is structured so that files that have no associated data can always be restored by the name of any link name of any link, and the user may choose whether data is recorded with each instance of a file that contains data. The format permits mixing of both types of links in a single archive; this can be done for special needs, and pax is expected to interpret such archives on input properly, despite the fact that there is no pax option that would force this mixed case on output. (When -o linkdata is used, the output must contain the duplicate data, but the implementation is free to include it or omit it when -o linkdata is not used.)

The time values are included as extended header records for those implementations needing more than the eleven octal digits allowed by the ustar format. Portable file timestamps cannot be negative. If pax encounters a file with a negative timestamp in copy or write mode, it can reject the file, substitute a non-negative timestamp, or generate a non-portable timestamp with a leading '-' . Even though some implementations can support finer file-time granularities than seconds, the normative text requires support only for seconds since the Epoch because the ISO POSIX-1 standard states them that way. The ustar format includes only mtime; the new format adds atime and ctime for symmetry. The atime access time restored to the file system will be affected by the -p a and -p e options. The ctime creation time (actually inode modification time) is described with "appropriate privilege" so that it can be ignored when writing to the file system. POSIX does not provide a portable means to change file creation time. Nothing is intended to prevent a non-portable implementation of pax from restoring the value.

The gid, size, and uid extended header records were included to allow expansion beyond the sizes specified in the regular tar header. New file system architectures are emerging that will exhaust the 12-digit size field. There are probably not many systems requiring more than 8 digits for user and group IDs, but the extended header values were included for completeness, allowing overrides for all of the decimal values in the tar header.

The standard developers intended to describe the effective results of pax with regard to file ownerships and permissions; implementations are not restricted in timing or sequencing the restoration of such, provided the results are as specified.

Much of the text describing the extended headers refers to use in " write or copy modes". The copy mode references are due to the normative text: "The effect of the copy shall be as if the copied files were written to an archive file and then subsequently extracted ...". There is certainly no way to test whether pax is actually generating the extended headers in copy mode, but the effects must be as if it had.

pax Archive Character Set Encoding/Decoding

There is a need to exchange archives of files between systems of different native codesets. Filenames, group names, and user names must be preserved to the fullest extent possible when an archive is read on the receiving platform. Translation of the contents of files is not within the scope of the pax utility.

There will also be the need to represent characters that are not available on the receiving platform. These unsupported characters cannot be automatically folded to the local set of characters due to the chance of collisions. This could result in overwriting previous extracted files from the archive or pre-existing files on the system.

For these reasons, the codeset used to represent characters within the extended header records of the pax archive must be sufficiently rich to handle all commonly used character sets. The fields requiring translation include, at a minimum, filenames, user names, group names, and link pathnames. Implementations may wish to have localized extended keywords that use non-portable characters.

The standard developers considered the following options:

*
The archive creator specifies the well-defined name of the source codeset. The receiver must then recognize the codeset name and perform the appropriate translations to the destination codeset.

*
The archive creator includes within the archive the character mapping table for the source codeset used to encode extended header records. The receiver must then read the character mapping table and perform the appropriate translations to the destination codeset.

*
The archive creator translates the extended header records in the source codeset into a canonical form. The receiver must then perform the appropriate translations to the destination codeset.

The approach that incorporates the name of the source codeset poses the problem of codeset name registration, and makes the archive useless to pax archive decoders that do not recognize that codeset.

Because parts of an archive may be corrupted, the standard developers felt that including the character map of the source codeset was too fragile. The loss of this one key component could result in making the entire archive useless. (The difference between this and the global extended header decision was that the latter has a workaround-duplicating extended header records on unreliable media-but this would be too burdensome for large character set maps.)

Both of the above approaches also put an undue burden on the pax archive receiver to handle the cross-product of all source and destination codesets.

To simplify the translation from the source codeset to the canonical form and from the canonical form to the destination codeset, the standard developers decided that the internal representation should be a stateless encoding. A stateless encoding is one where each codepoint has the same meaning, without regard to the decoder being in a specific state. An example of a stateful encoding would be the Japanese Shift-JIS; an example of a stateless encoding would be the ISO/IEC 646:1991 standard (equivalent to 7-bit ASCII).

For these reasons, the standard developers decided to adopt a canonical format for the representation of file information strings. The obvious, well-endorsed candidate is the ISO/IEC 10646-1:2000 standard (based in part on Unicode), which can be used to represent the characters of virtually all standardized character sets. The standard developers initially agreed upon using UCS2 (16-bit Unicode) as the internal representation. This repertoire of characters provides a sufficiently rich set to represent all commonly-used codesets.

However, the standard developers found that the 16-bit Unicode representation had some problems. It forced the issue of standardizing byte ordering. The 2-byte length of each character made the extended header records twice as long for the case of strings coded entirely from historical 7-bit ASCII. For these reasons, the standard developers chose the UTF-8 defined in the ISO/IEC 10646-1:2000 standard. This multi-byte representation encodes UCS2 or UCS4 characters reliably and deterministically, eliminating the need for a canonical byte ordering. In addition, NUL octets and other characters possibly confusing to POSIX file systems do not appear, except to represent themselves. It was realized that certain national codesets take up more space after the encoding, due to their placement within the UCS range; it was felt that the usefulness of the encoding of the names outweighs the disadvantage of size increase for file, user, and group names.

The encoding of UTF-8 is as follows:

UCS4 Hex Encoding  UTF-8 Binary Encoding

00000000-0000007F  0xxxxxxx
00000080-000007FF  110xxxxx 10xxxxxx
00000800-0000FFFF  1110xxxx 10xxxxxx 10xxxxxx
00010000-001FFFFF  11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
00200000-03FFFFFF  111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
04000000-7FFFFFFF  1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

where each 'x' represents a bit value from the character being translated.

ustar Interchange Format

The description of the ustar format reflects numerous enhancements over pre-1988 versions of the historical tar utility. The goal of these changes was not only to provide the functional enhancements desired, but also to retain compatibility between new and old versions. This compatibility has been retained. Archives written using the old archive format are compatible with the new format.

Implementors should be aware that the previous file format did not include a mechanism to archive directory type files. For this reason, the convention of using a filename ending with slash was adopted to specify a directory on the archive.

The total size of the name and prefix fields have been set to meet the minimum requirements for {PATH_MAX}. If a pathname will fit within the name field, it is recommended that the pathname be stored there without the use of the prefix field. Although the name field is known to be too small to contain {PATH_MAX} characters, the value was not changed in this version of the archive file format to retain backwards-compatibility, and instead the prefix was introduced. Also, because of the earlier version of the format, there is no way to remove the restriction on the linkname field being limited in size to just that of the name field.

The size field is required to be meaningful in all implementation extensions, although it could be zero. This is required so that the data blocks can always be properly counted.

It is suggested that if device special files need to be represented that cannot be represented in the standard format, that one of the extension types ( A- Z) be used, and that the additional information for the special file be represented as data and be reflected in the size field.

Attempting to restore a special file type, where it is converted to ordinary data and conflicts with an existing filename, need not be specially detected by the utility. If run as an ordinary user, pax should not be able to overwrite the entries in, for example, /dev in any case (whether the file is converted to another type or not). If run as a privileged user, it should be able to do so, and it would be considered a bug if it did not. The same is true of ordinary data files and similarly named special files; it is impossible to anticipate the needs of the user (who could really intend to overwrite the file), so the behavior should be predictable (and thus regular) and rely on the protection system as required.

The value 7 in the typeflag field is intended to define how contiguous files can be stored in a ustar archive. IEEE Std 1003.1-2001 does not require the contiguous file extension, but does define a standard way of archiving such files so that all conforming systems can interpret these file types in a meaningful and consistent manner. On a system that does not support extended file types, the pax utility should do the best it can with the file and go on to the next.

The file protection modes are those conventionally used by the ls utility. This is extended beyond the usage in the ISO POSIX-2 standard to support the "shared text" or "sticky" bit. It is intended that the conformance document should not document anything beyond the existence of and support of such a mode. Further extensions are expected to these bits, particularly with overloading the set-user-ID and set-group-ID flags.

cpio Interchange Format

The reference to appropriate privilege in the cpio format refers to an error on standard output; the ustar format does not make comparable statements.

The model for this format was the historical System V cpio -c data interchange format. This model documents the portable version of the cpio format and not the binary version. It has the flexibility to transfer data of any type described within IEEE Std 1003.1-2001, yet is extensible to transfer data types specific to extensions beyond IEEE Std 1003.1-2001 (for example, contiguous files). Because it describes existing practice, there is no question of maintaining upwards-compatibility.

cpio Header

There has been some concern that the size of the c_ino field of the header is too small to handle those systems that have very large inode numbers. However, the c_ino field in the header is used strictly as a hard-link resolution mechanism for archives. It is not necessarily the same value as the inode number of the file in the location from which that file is extracted.

The name c_magic is based on historical usage.

cpio Filename

For most historical implementations of the cpio utility, {PATH_MAX} octets can be used to describe the pathname without the addition of any other header fields (the NUL character would be included in this count). {PATH_MAX} is the minimum value for pathname size, documented as 256 bytes. However, an implementation may use c_namesize to determine the exact length of the pathname. With the current description of the <cpio.h> header, this pathname size can be as large as a number that is described in six octal digits.

Two values are documented under the c_mode field values to provide for extensibility for known file types:

0110 000
Reserved for contiguous files. The implementation may treat the rest of the information for this archive like a regular file. If this file type is undefined, the implementation may create the file as a regular file.

This provides for extensibility of the cpio format while allowing for the ability to read old archives. Files of an unknown type may be read as "regular files" on some implementations. On a system that does not support extended file types, the pax utility should do the best it can with the file and go on to the next.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , cp , ed , getopts , ls , printf() , the Base Definitions volume of IEEE Std 1003.1-2001, <cpio.h>, the System Interfaces volume of IEEE Std 1003.1-2001, chown(), creat(), mkdir(), mkfifo(), stat(), utime(), write()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


head(1p)

HEAD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

head - copy the first part of files

SYNOPSIS

head [-n number][file...]

DESCRIPTION

The head utility shall copy its input files to the standard output, ending the output for each file at a designated point.

Copying shall end at the point in each input file indicated by the -n number option. The option-argument number shall be counted in units of lines.

OPTIONS

The head utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-n number
The first number lines of each input file shall be copied to standard output. The application shall ensure that the number option-argument is a positive decimal integer.

When a file contains less than number lines, it shall be copied to standard output in its entirety. This shall not be an error.

If no options are specified, head shall act as if -n 10 had been specified.

OPERANDS

The following operand shall be supported:

file
A pathname of an input file. If no file operands are specified, the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

Input files shall be text files, but the line length is not restricted to {LINE_MAX} bytes.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of head:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall contain designated portions of the input files.

If multiple file operands are specified, head shall precede the output for each with the header:

"\n==> %s <==\n", <pathname>

except that the first header written shall not include the initial <newline>.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The obsolescent - number form is withdrawn in this version. Applications should use the -n number option.

EXAMPLES

To write the first ten lines of all files (except those with a leading period) in the directory:

head *

RATIONALE

Although it is possible to simulate head with sed 10q for a single file, the standard developers decided that the popularity of head on historical BSD systems warranted its inclusion alongside tail.

This standard version of head follows the Utility Syntax Guidelines. The -n option was added to this new interface so that head and tail would be more logically related.

There is no -c option (as there is in tail) because it is not historical practice and because other utilities in this volume of IEEE Std 1003.1-2001 provide similar functionality.

FUTURE DIRECTIONS

None.

SEE ALSO

sed , tail

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fort77(1p)

FORT77

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fort77 - FORTRAN compiler (FORTRAN)

SYNOPSIS

fort77 [-c][-g][-L directory]... [-O optlevel][-o outfile][-s][-w]
operand...

DESCRIPTION

The fort77 utility is the interface to the FORTRAN compilation system; it shall accept the full FORTRAN-77 language defined by the ANSI X3.9-1978 standard. The system conceptually consists of a compiler and link editor. The files referenced by operands are compiled and linked to produce an executable file. It is unspecified whether the linking occurs entirely within the operation of fort77; some implementations may produce objects that are not fully resolved until the file is executed.

If the -c option is present, for all pathname operands of the form file .f, the files:

$(basename pathname.f).o

shall be created or overwritten as the result of successful compilation. If the -c option is not specified, it is unspecified whether such .o files are created or deleted for the file .f operands.

If there are no options that prevent link editing (such as -c) and all operands compile and link without error, the resulting executable file shall be written into the file named by the -o option (if present) or to the file a.out. The executable file shall be created as specified in the System Interfaces volume of IEEE Std 1003.1-2001, except that the file permissions shall be set to:

S_IRWXO | S_IRWXG | S_IRWXU

and that the bits specified by the umask of the process shall be cleared.

OPTIONS

The fort77 utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that:

*
The -l library operands have the format of options, but their position within a list of operands affects the order in which libraries are searched.

*
The order of specifying the multiple -L options is significant.

*
Conforming applications shall specify each option separately; that is, grouping option letters (for example, -cg) need not be recognized by all implementations.

The following options shall be supported:

-c
Suppress the link-edit phase of the compilation, and do not remove any object files that are produced.
-g
Produce symbolic information in the object or executable files; the nature of this information is unspecified, and may be modified by implementation-defined interactions with other options.
-s
Produce object or executable files, or both, from which symbolic and other information not required for proper execution using the exec family of functions defined in the System Interfaces volume of IEEE Std 1003.1-2001 has been removed (stripped). If both -g and -s options are present, the action taken is unspecified.
-o outfile
Use the pathname outfile, instead of the default a.out, for the executable file produced. If the -o option is present with -c, the result is unspecified.
-L directory
Change the algorithm of searching for the libraries named in -l operands to look in the directory named by the directory pathname before looking in the usual places. Directories named in -L options shall be searched in the specified order. At least ten instances of this option shall be supported in a single fort77 command invocation. If a directory specified by a -L option contains a file named libf.a, the results are unspecified.
-O optlevel
Specify the level of code optimization. If the optlevel option-argument is the digit '0' , all special code optimizations shall be disabled. If it is the digit '1' , the nature of the optimization is unspecified. If the -O option is omitted, the nature of the system's default optimization is unspecified. It is unspecified whether code generated in the presence of the -O 0 option is the same as that generated when -O is omitted. Other optlevel values may be supported.
-w
Suppress warnings.

Multiple instances of -L options can be specified.

OPERANDS

An operand is either in the form of a pathname or the form -l library. At least one operand of the pathname form shall be specified. The following operands shall be supported:

file.f
The pathname of a FORTRAN source file to be compiled and optionally passed to the link editor. The filename operand shall be of this form if the -c option is used.
file.a
A library of object files typically produced by ar, and passed directly to the link editor. Implementations may recognize implementation-defined suffixes other than .a as denoting object file libraries.
file.o
An object file produced by fort77 -c and passed directly to the link editor. Implementations may recognize implementation-defined suffixes other than .o as denoting object files.

The processing of other files is implementation-defined.

-l library
(The letter ell.) Search the library named:

liblibrary.a

A library is searched when its name is encountered, so the placement of a -l operand is significant. Several standard libraries can be specified in this manner, as described in the EXTENDED DESCRIPTION section. Implementations may recognize implementation-defined suffixes other than .a as denoting libraries.

STDIN

Not used.

INPUT FILES

The input file shall be one of the following: a text file containing FORTRAN source code; an object file in the format produced by fort77 -c; or a library of object files, in the format produced by archiving zero or more object files, using ar. Implementations may supply additional utilities that produce files in these formats. Additional input files are implementation-defined.

A <tab> encountered within the first six characters on a line of source code shall cause the compiler to interpret the following character as if it were the seventh character on the line (that is, in column 7).

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of fort77:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TMPDIR
Determine the pathname that should override the default directory for temporary files, if any.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages. If more than one file operand ending in .f (or possibly other unspecified suffixes) is given, for each such file:

"%s:\n", <file>

may be written to allow identification of the diagnostic message with the appropriate input file.

This utility may produce warning messages about certain conditions that do not warrant returning an error (non-zero) exit value.

OUTPUT FILES

Object files, listing files, and executable files shall be produced in unspecified formats.

EXTENDED DESCRIPTION

Standard Libraries

The fort77 utility shall recognize the following -l operand for the standard library:

-l f
This library contains all functions referenced in the ANSI X3.9-1978 standard. This operand shall not be required to be present to cause a search of this library.

In the absence of options that inhibit invocation of the link editor, such as -c, the fort77 utility shall cause the equivalent of a -l f operand to be passed to the link editor as the last -l operand, causing it to be searched after all other object files and libraries are loaded.

It is unspecified whether the library libf.a exists as a regular file. The implementation may accept as -l operands names of objects that do not exist as regular files.

External Symbols

The FORTRAN compiler and link editor shall support the significance of external symbols up to a length of at least 31 bytes; case folding is permitted. The action taken upon encountering symbols exceeding the implementation-defined maximum symbol length is unspecified.

The compiler and link editor shall support a minimum of 511 external symbols per source or object file, and a minimum of 4095 external symbols total. A diagnostic message is written to standard output if the implementation-defined limit is exceeded; other actions are unspecified.

EXIT STATUS

The following exit values shall be returned:

0
Successful compilation or link edit.
>0
An error occurred.

CONSEQUENCES OF ERRORS

When fort77 encounters a compilation error, it shall write a diagnostic to standard error and continue to compile other source code operands. It shall return a non-zero exit status, but it is implementation-defined whether an object module is created. If the link edit is unsuccessful, a diagnostic message shall be written to standard error, and fort77 shall exit with a non-zero status.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

The following usage example compiles xyz.f and creates the executable file foo:

fort77 -o foo xyz.f

The following example compiles xyz.f and creates the object file xyz.o:

fort77 -c xyz.f

The following example compiles xyz.f and creates the executable file a.out:

fort77 xyz.f

The following example compiles xyz.f, links it with b.o, and creates the executable a.out:

fort77 xyz.f b.o

RATIONALE

The name of this utility was chosen as fort77 to parallel the renaming of the C compiler. The name f77 was not chosen to avoid problems with historical implementations. The ANSI X3.9-1978 standard was selected as a normative reference because the ISO/IEC version of FORTRAN-77 has been superseded by the ISO/IEC 1539:1990 standard (Fortran-90).

The file inclusion and symbol definition #define mechanisms used by the c99 utility were not included in this volume of IEEE Std 1003.1-2001-even though they are commonly implemented-since there is no requirement that the FORTRAN compiler use the C preprocessor.

The -onetrip option was not included in this volume of IEEE Std 1003.1-2001, even though many historical compilers support it, because it is derived from FORTRAN-66; it is an anachronism that should not be perpetuated.

Some implementations produce compilation listings. This aspect of FORTRAN has been left unspecified because there was controversy concerning the various methods proposed for implementing it: a -V option overlapped with historical vendor practice and a naming convention of creating files with .l suffixes collided with historical lex file naming practice.

There is no -I option in this version of this volume of IEEE Std 1003.1-2001 to specify a directory for file inclusion. An INCLUDE directive has been a part of the Fortran-90 discussions, but an interface supporting that standard is not in the current scope.

It is noted that many FORTRAN compilers produce an object module even when compilation errors occur; during a subsequent compilation, the compiler may patch the object module rather than recompiling all the code. Consequently, it is left to the implementor whether or not an object file is created.

A reference to MIL-STD-1753 was removed from an early proposal in response to a request from the POSIX FORTRAN-binding standard developers. It was not the intention of the standard developers to require certification of the FORTRAN compiler, and IEEE Std 1003.9-1992 does not specify the military standard or any special preprocessing requirements. Furthermore, use of that document would have been inappropriate for an international standard.

The specification of optimization has been subject to changes through early proposals. At one time, -O and -N were Booleans: optimize and do not optimize (with an unspecified default). Some historical practice led this to be changed to:

-O 0
No optimization.
-O 1
Some level of optimization.
-O n
Other, unspecified levels of optimization.

It is not always clear whether "good code generation" is the same thing as optimization. Simple optimizations of local actions do not usually affect the semantics of a program. The -O 0 option has been included to accommodate the very particular nature of scientific calculations in a highly optimized environment; compilers make errors. Some degree of optimization is expected, even if it is not documented here, and the ability to shut it off completely could be important when porting an application. An implementation may treat -O 0 as "do less than normal" if it wishes, but this is only meaningful if any of the operations it performs can affect the semantics of a program. It is highly dependent on the implementation whether doing less than normal is logical. It is not the intent of the -O 0 option to ask for inefficient code generation, but rather to assure that any semantically visible optimization is suppressed.

The specification of standard library access is consistent with the C compiler specification. Implementations are not required to have /usr/lib/libf.a, as many historical implementations do, but if not they are required to recognize f as a token.

External symbol size limits are in normative text; conforming applications need to know these limits. However, the minimum maximum symbol length should be taken as a constraint on a conforming application, not on an implementation, and consequently the action taken for a symbol exceeding the limit is unspecified. The minimum size for the external symbol table was added for similar reasons.

The CONSEQUENCES OF ERRORS section clearly specifies the behavior of the compiler when compilation or link-edit errors occur. The behavior of several historical implementations was examined, and the choice was made to be silent on the status of the executable, or a.out, file in the face of compiler or linker errors. If a linker writes the executable file, then links it on disk with lseek()s and write()s, the partially linked executable file can be left on disk and its execute bits turned off if the link edit fails. However, if the linker links the image in memory before writing the file to disk, it need not touch the executable file (if it already exists) because the link edit fails. Since both approaches are historical practice, a conforming application shall rely on the exit status of fort77, rather than on the existence or mode of the executable file.

The -g and -s options are not specified as mutually-exclusive. Historically these two options have been mutually-exclusive, but because both are so loosely specified, it seemed appropriate to leave their interaction unspecified.

The requirement that conforming applications specify compiler options separately is to reserve the multi-character option name space for vendor-specific compiler options, which are known to exist in many historical implementations. Implementations are not required to recognize, for example, -gc as if it were -g -c; nor are they forbidden from doing so. The SYNOPSIS shows all of the options separately to highlight this requirement on applications.

Echoing filenames to standard error is considered a diagnostic message because it would otherwise be difficult to associate an error message with the erring file. They are described with "may" to allow implementations to use other methods of identifying files and to parallel the description in c99.

FUTURE DIRECTIONS

A compilation system based on the ISO/IEC 1539:1990 standard (Fortran-90) may be considered for a future version; it may have a different utility name from fort77.

SEE ALSO

ar , asa , c99 , umask() , the System Interfaces volume of IEEE Std 1003.1-2001, exec

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


prs(1p)

PRS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

prs - print an SCCS file (DEVELOPMENT)

SYNOPSIS

prs [-a][-d dataspec][-r[SID]] file...

prs [ -e| -l] -c cutoff [-d dataspec] file...

prs [ -e| -l] -r[SID][-d dataspec]file...

DESCRIPTION

The prs utility shall write to standard output parts or all of an SCCS file in a user-supplied format.

OPTIONS

The prs utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the -r option has an optional option-argument. This optional option-argument cannot be presented as a separate argument. The following options shall be supported:

-d dataspec
Specify the output data specification. The dataspec shall be a string consisting of SCCS file data keywords (see Data Keywords ) interspersed with optional user-supplied text.
-r[SID]
Specify the SCCS identification string (SID) of a delta for which information is desired. If no SID option-argument is specified, the SID of the most recently created delta shall be assumed.
-e
Request information for all deltas created earlier than and including the delta designated via the -r option or the date-time given by the -c option.
-l
Request information for all deltas created later than and including the delta designated via the -r option or the date-time given by the -c option.
-c cutoff
Indicate the cutoff date-time, in the form:

YY[MM[DD[HH[MM[SS]]]]]

For the YY component, values in the range [69,99] shall refer to years 1969 to 1999 inclusive, and values in the range [00,68] shall refer to years 2000 to 2068 inclusive.

Note:
It is expected that in a future version of IEEE Std 1003.1-2001 the default century inferred from a 2-digit year will change. (This would apply to all commands accepting a 2-digit year as input.)

No changes (deltas) to the SCCS file that were created after the specified cutoff date-time shall be included in the output. Units omitted from the date-time default to their maximum possible values; for example, -c 7502 is equivalent to -c 750228235959.

-a
Request writing of information for both removed-that is, delta type= R (see rmdel )- and existing-that is, delta type= D,- deltas. If the -a option is not specified, information for existing deltas only shall be provided.

OPERANDS

The following operand shall be supported:

file
A pathname of an existing SCCS file or a directory. If file is a directory, the prs utility shall behave as though each file in the directory were specified as a named file, except that non-SCCS files (last component of the pathname does not begin with s.) and unreadable files shall be silently ignored.

If exactly one file operand appears, and it is '-' , the standard input shall be read; each line of the standard input shall be taken to be the name of an SCCS file to be processed. Non-SCCS files and unreadable files shall be silently ignored.

STDIN

The standard input shall be a text file used only when the file operand is specified as '-' . Each line of the text file shall be interpreted as an SCCS pathname.

INPUT FILES

Any SCCS files displayed are files of an unspecified format.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of prs:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be a text file whose format is dependent on the data keywords specified with the -d option.

Data Keywords

Data keywords specify which parts of an SCCS file shall be retrieved and output. All parts of an SCCS file have an associated data keyword. A data keyword may appear in a dataspec multiple times.

The information written by prs shall consist of:

1.
The user-supplied text

2.
Appropriate values (extracted from the SCCS file) substituted for the recognized data keywords in the order of appearance in the dataspec

The format of a data keyword value shall either be simple ( 'S' ), in which keyword substitution is direct, or multi-line ( 'M' ).

User-supplied text shall be any text other than recognized data keywords. A <tab> shall be specified by '\t' and <newline> by '\n' . When the -r option is not specified, the default dataspec shall be:

:PN::\n\n

and the following dataspec shall be used for each selected delta:

:Dt:\t:DL:\nMRs:\n:MR:COMMENTS:\n:C:

SCCS File Data Keywords |  |  |
Keyword | Data Item | File Section | Value | Format
:Dt: | Delta information | Delta Table | See below* | S
:DL: | Delta line statistics | " | :Li:/:Ld:/:Lu: | S
:Li: | Lines inserted by Delta | " | nnnnn*** | S
:Ld: | Lines deleted by Delta | " | nnnnn*** | S
:Lu: | Lines unchanged by Delta | " | nnnnn*** | S
:DT: | Delta type | " | D or R | S
:I: | SCCS ID string (SID) | " | See below** | S
:R: | Release number | " | nnnn | S
:L: | Level number | " | nnnn | S
:B: | Branch number | " | nnnn | S
:S: | Sequence number | " | nnnn | S
:D: | Date delta created | " | :Dy:/:Dm:/:Dd: | S
:Dy: | Year delta created | " | nn | S
:Dm: | Month delta created | " | nn | S
:Dd: | Day delta created | " | nn | S
:T: | Time delta created | " | :Th:::Tm:::Ts: | S
:Th: | Hour delta created | " | nn | S
:Tm: | Minutes delta created | " | nn | S
:Ts: | Seconds delta created | " | nn | S
:P: | Programmer who created Delta | " | logname | S
:DS: | Delta sequence number | " | nnnn | S
:DP: | Predecessor Delta sequence | " | nnnn | S
 | number |  |  |
:DI: | Sequence number of deltas | " | :Dn:/:Dx:/:Dg: | S
 | included, excluded, or ignored |  |  |
:Dn: | Deltas included (sequence #) | " | :DS: :DS: ... | S
:Dx: | Deltas excluded (sequence #) | " | :DS: :DS: ... | S
:Dg: | Deltas ignored (sequence #) | " | :DS: :DS: ... | S
:MR: | MR numbers for delta | " | text | M
:C: | Comments for delta | " | text | M
:UN: | User names | User Names | text | M
:FL: | Flag list | Flags | text | M
:Y: | Module type flag | " | text | S
:MF: | MR validation flag | " | yes or no | S
:MP: | MR validation program name | " | text | S
:KF: | Keyword error, warning flag | " | yes or no | S
:KV: | Keyword validation string | " | text | S
:BF: | Branch flag | " | yes or no | S
:J: | Joint edit flag | " | yes or no | S
:LK: | Locked releases | " | :R: ... | S
:Q: | User-defined keyword | " | text | S
:M: | Module name | " | text | S
:FB: | Floor boundary | " | :R: | S
:CB: | Ceiling boundary | " | :R: | S
:Ds: | Default SID | " | :I: | S
:ND: | Null delta flag | " | yes or no | S
:FD: | File descriptive text | Comments | text | M
:BD: | Body | Body | text | M
:GB: | Gotten body | " | text | M
:W: | A form of what string | N/A | :Z::M:\t:I: | S
:A: | A form of what string | N/A | :Z::Y: :M: :I::Z: | S
:Z: | what string delimiter | N/A | @(#) | S
:F: | SCCS filename | N/A | text | S
:PN: | SCCS file pathname | N/A | text | S
*
:Dt:= :DT: :I: :D: :T: :P: :DS: :DP:
**
:R:.:L:.:B:.:S: if the delta is a branch delta ( :BF:== yes)
:R:.:L: if the delta is not a branch delta ( :BF:== no)
***
The line statistics are capped at 99999. For example, if 100000 lines were unchanged in a certain revision, :Lu: shall produce the value 99999.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

1.
The following example:

prs -d "User Names for :F: are:\n:UN:" s.file

might write to standard output:

User Names for s.file are:
xyz
131
abc

2.
The following example:

prs -d "Delta for pgm :M:: :I: - :D: By :P:" -r s.file

might write to standard output:

Delta for pgm main.c: 3.7 - 77/12/01 By cas

3.
As a special case:

prs s.file

might write to standard output:

s.file:
<blank line>
D 1.1 77/12/01 00:00:00 cas 1 000000/00000/00000
MRs:
bl78-12345
bl79-54321
COMMENTS:
this is the comment line for s.file initial delta
<blank line>

for each delta table entry of the D type. The only option allowed to be used with this special case is the -a option.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

admin , delta , get , what

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pwd(1p)

PWD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pwd - return working directory name

SYNOPSIS

pwd [-L | -P ]

DESCRIPTION

The pwd utility shall write to standard output an absolute pathname of the current working directory, which does not contain the filenames dot or dot-dot.

OPTIONS

The pwd utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-L
If the PWD environment variable contains an absolute pathname of the current directory that does not contain the filenames dot or dot-dot, pwd shall write this pathname to standard output. Otherwise, the -L option shall behave as the -P option.
-P
The absolute pathname written shall not contain filenames that, in the context of the pathname, refer to files of type symbolic link.

If both -L and -P are specified, the last one shall apply. If neither -L nor -P is specified, the pwd utility shall behave as if -L had been specified.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of pwd:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PWD
If the -P option is in effect, this variable shall be set to an absolute pathname of the current working directory that does not contain any components that specify symbolic links, does not contain any components that are dot, and does not contain any components that are dot-dot. If an application sets or unsets the value of PWD , the behavior of pwd is unspecified.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The pwd utility output is an absolute pathname of the current working directory:

"%s\n", <directory pathname>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If an error is detected, output shall not be written to standard output, a diagnostic message shall be written to standard error, and the exit status is not zero.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

Some implementations have historically provided pwd as a shell special built-in command.

In most utilities, if an error occurs, partial output may be written to standard output. This does not happen in historical implementations of pwd. Because pwd is frequently used in historical shell scripts without checking the exit status, it is important that the historical behavior is required here; therefore, the CONSEQUENCES OF ERRORS section specifically disallows any partial output being written to standard output.

FUTURE DIRECTIONS

None.

SEE ALSO

cd , the System Interfaces volume of IEEE Std 1003.1-2001, getcwd()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uniq(1p)

UNIQ

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uniq - report or filter out repeated lines in a file

SYNOPSIS

uniq [-c|-d|-u][-f fields][-s char][input_file [output_file]]

DESCRIPTION

The uniq utility shall read an input file comparing adjacent lines, and write one copy of each input line on the output. The second and succeeding copies of repeated adjacent input lines shall not be written.

Repeated lines in the input shall not be detected if they are not adjacent.

OPTIONS

The uniq utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Precede each output line with a count of the number of times the line occurred in the input.
-d
Suppress the writing of lines that are not repeated in the input.
-f fields
Ignore the first fields fields on each input line when doing comparisons, where fields is a positive decimal integer. A field is the maximal string matched by the basic regular expression:

[[:blank:]]*[^[:blank:]]*

If the fields option-argument specifies more fields than appear on an input line, a null string shall be used for comparison.

-s chars
Ignore the first chars characters when doing comparisons, where chars shall be a positive decimal integer. If specified in conjunction with the -f option, the first chars characters after the first fields fields shall be ignored. If the chars option-argument specifies more characters than remain on an input line, a null string shall be used for comparison.
-u
Suppress the writing of lines that are repeated in the input.

OPERANDS

The following operands shall be supported:

input_file
A pathname of the input file. If the input_file operand is not specified, or if the input_file is '-' , the standard input shall be used.
output_file
A pathname of the output file. If the output_file operand is not specified, the standard output shall be used. The results are unspecified if the file named by output_file is the file named by input_file.

STDIN

The standard input shall be used only if no input_file operand is specified or if input_file is '-' . See the INPUT FILES section.

INPUT FILES

The input file shall be a text file.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uniq:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for ordering rules.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and which characters constitute a <blank> in the current locale.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be used only if no output_file operand is specified. See the OUTPUT FILES section.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

If the -c option is specified, the output file shall be empty or each line shall be of the form:

"%d %s", <number of duplicates>, <line>

otherwise, the output file shall be empty or each line shall be of the form:

"%s", <line>

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The utility executed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The sort utility can be used to cause repeated lines to be adjacent in the input file.

EXAMPLES

The following input file data (but flushed left) was used for a test series on uniq:

#01 foo0 bar0 foo1 bar1
#02 bar0 foo1 bar1 foo1
#03 foo0 bar0 foo1 bar1
#04
#05 foo0 bar0 foo1 bar1
#06 foo0 bar0 foo1 bar1
#07 bar0 foo1 bar1 foo0

What follows is a series of test invocations of the uniq utility that use a mixture of uniq options against the input file data. These tests verify the meaning of adjacent. The uniq utility views the input data as a sequence of strings delimited by '\n' . Accordingly, for the fieldsth member of the sequence, uniq interprets unique or repeated adjacent lines strictly relative to the fields+1th member.

1.
This first example tests the line counting option, comparing each line of the input file data starting from the second field:

uniq -c -f 1 uniq_0I.t
    1 #01 foo0 bar0 foo1 bar1
    1 #02 bar0 foo1 bar1 foo0
    1 #03 foo0 bar0 foo1 bar1
    1 #04
    2 #05 foo0 bar0 foo1 bar1
    1 #07 bar0 foo1 bar1 foo0

The number '2' , prefixing the fifth line of output, signifies that the uniq utility detected a pair of repeated lines. Given the input data, this can only be true when uniq is run using the -f 1 option (which shall cause uniq to ignore the first field on each input line).

2.
The second example tests the option to suppress unique lines, comparing each line of the input file data starting from the second field:

uniq -d -f 1 uniq_0I.t
#05 foo0 bar0 foo1 bar1

3.
This test suppresses repeated lines, comparing each line of the input file data starting from the second field:

uniq -u -f 1 uniq_0I.t
#01 foo0 bar0 foo1 bar1
#02 bar0 foo1 bar1 foo1
#03 foo0 bar0 foo1 bar1
#04
#07 bar0 foo1 bar1 foo0

4.
This suppresses unique lines, comparing each line of the input file data starting from the third character:

uniq -d -s 2 uniq_0I.t

In the last example, the uniq utility found no input matching the above criteria.

RATIONALE

Some historical implementations have limited lines to be 1080 bytes in length, which does not meet the implied {LINE_MAX} limit.

FUTURE DIRECTIONS

None.

SEE ALSO

comm , sort

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


grep(1p)

GREP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

grep - search a file for a pattern

SYNOPSIS

grep [-E| -F][-c| -l| -q][-insvx] -e pattern_list...
[-f pattern_file]...[file...]

grep [-E| -F][-c| -l| -q][-insvx][-e pattern_list]...
-f pattern_file...[file...]

grep [-E| -F][-c| -l| -q][-insvx] pattern_list[file...]

DESCRIPTION

The grep utility shall search the input files, selecting lines matching one or more patterns; the types of patterns are controlled by the options specified. The patterns are specified by the -e option, -f option, or the pattern_list operand. The pattern_list's value shall consist of one or more patterns separated by <newline>s; the pattern_file's contents shall consist of one or more patterns terminated by <newline>. By default, an input line shall be selected if any pattern, treated as an entire basic regular expression (BRE) as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions, matches any part of the line excluding the terminating <newline>; a null BRE shall match every line. By default, each selected input line shall be written to the standard output.

Regular expression matching shall be based on text lines. Since a <newline> separates or terminates patterns (see the -e and -f options below), regular expressions cannot contain a <newline>. Similarly, since patterns are matched against individual lines (excluding the terminating <newline>s) of the input, there is no way for a pattern to match a <newline> found in the input.

OPTIONS

The grep utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-E
Match using extended regular expressions. Treat each pattern specified as an ERE, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.4, Extended Regular Expressions. If any entire ERE pattern matches some part of an input line excluding the terminating <newline>, the line shall be matched. A null ERE shall match every line.
-F
Match using fixed strings. Treat each pattern specified as a string instead of a regular expression. If an input line contains any of the patterns as a contiguous sequence of bytes, the line shall be matched. A null string shall match every line.
-c
Write only a count of selected lines to standard output.
-e pattern_list

Specify one or more patterns to be used during the search for input. The application shall ensure that patterns in pattern_list are separated by a <newline>. A null pattern can be specified by two adjacent <newline>s in pattern_list. Unless the -E or -F option is also specified, each pattern shall be treated as a BRE, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions. Multiple -e and -f options shall be accepted by the grep utility. All of the specified patterns shall be used when matching lines, but the order of evaluation is unspecified.

-f pattern_file

Read one or more patterns from the file named by the pathname pattern_file. Patterns in pattern_file shall be terminated by a <newline>. A null pattern can be specified by an empty line in pattern_file. Unless the -E or -F option is also specified, each pattern shall be treated as a BRE, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions.

-i
Perform pattern matching in searches without regard to case; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.2, Regular Expression General Requirements.
-l
(The letter ell.) Write only the names of files containing selected lines to standard output. Pathnames shall be written once per file searched. If the standard input is searched, a pathname of "(standard input)" shall be written, in the POSIX locale. In other locales, "standard input" may be replaced by something more appropriate in those locales.
-n
Precede each output line by its relative line number in the file, each file starting at line 1. The line number counter shall be reset for each file processed.
-q
Quiet. Nothing shall be written to the standard output, regardless of matching lines. Exit with zero status if an input line is selected.
-s
Suppress the error messages ordinarily written for nonexistent or unreadable files. Other error messages shall not be suppressed.
-v
Select lines not matching any of the specified patterns. If the -v option is not specified, selected lines shall be those that match any of the specified patterns.
-x
Consider only input lines that use all characters in the line excluding the terminating <newline> to match an entire fixed string or regular expression to be matching lines.

OPERANDS

The following operands shall be supported:

pattern_list
Specify one or more patterns to be used during the search for input. This operand shall be treated as if it were specified as -e pattern_list.
file
A pathname of a file to be searched for the patterns. If no file operands are specified, the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

The input files shall be text files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of grep:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classes within regular expressions.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If the -l option is in effect, and the -q option is not, the following shall be written for each file containing at least one selected input line:

"%s\n", <file>

Otherwise, if more than one file argument appears, and -q is not specified, the grep utility shall prefix each output line by:

"%s:", <file>

The remainder of each output line shall depend on the other options specified:

*
If the -c option is in effect, the remainder of each output line shall contain:

"%d\n", <count>

*
Otherwise, if -c is not in effect and the -n option is in effect, the following shall be written to standard output:

"%d:", <line number>

*
Finally, the following shall be written to standard output:

"%s", <selected-line contents>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
One or more lines were selected.
1
No lines were selected.
>1
An error occurred.

CONSEQUENCES OF ERRORS

If the -q option is specified, the exit status shall be zero if an input line is selected, even if an error was detected. Otherwise, default actions shall be performed.

The following sections are informative.

APPLICATION USAGE

Care should be taken when using characters in pattern_list that may also be meaningful to the command interpreter. It is safest to enclose the entire pattern_list argument in single quotes:

'...'

The -e pattern_list option has the same effect as the pattern_list operand, but is useful when pattern_list begins with the hyphen delimiter. It is also useful when it is more convenient to provide multiple patterns as separate arguments.

Multiple -e and -f options are accepted and grep uses all of the patterns it is given while matching input text lines. (Note that the order of evaluation is not specified. If an implementation finds a null string as a pattern, it is allowed to use that pattern first, matching every line, and effectively ignore any other patterns.)

The -q option provides a means of easily determining whether or not a pattern (or string) exists in a group of files. When searching several files, it provides a performance improvement (because it can quit as soon as it finds the first match) and requires less care by the user in choosing the set of files to supply as arguments (because it exits zero if it finds a match even if grep detected an access or read error on earlier file operands).

EXAMPLES

1.
To find all uses of the word "Posix" (in any case) in file text.mm and write with line numbers:

grep -i -n posix text.mm

2.
To find all empty lines in the standard input:

grep ^$

or:

grep -v .

3.
Both of the following commands print all lines containing strings "abc" or "def" or both:

grep -E 'abc|def'

grep -F 'abc
def'

4.
Both of the following commands print all lines matching exactly "abc" or "def" :

grep -E '^abc$|^def$'

grep -F -x 'abc
def'

RATIONALE

This grep has been enhanced in an upwards-compatible way to provide the exact functionality of the historical egrep and fgrep commands as well. It was the clear intention of the standard developers to consolidate the three greps into a single command.

The old egrep and fgrep commands are likely to be supported for many years to come as implementation extensions, allowing historical applications to operate unmodified.

Historical implementations usually silently ignored all but one of multiply-specified -e and -f options, but were not consistent as to which specification was actually used.

The -b option was omitted from the OPTIONS section because block numbers are implementation-defined.

The System V restriction on using - to mean standard input was omitted.

A definition of action taken when given a null BRE or ERE is specified. This is an error condition in some historical implementations.

The -l option previously indicated that its use was undefined when no files were explicitly named. This behavior was historical and placed an unnecessary restriction on future implementations. It has been removed.

The historical BSD grep -s option practice is easily duplicated by redirecting standard output to /dev/null. The -s option required here is from System V.

The -x option, historically available only with fgrep, is available here for all of the non-obsolescent versions.

FUTURE DIRECTIONS

None.

SEE ALSO

sed

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


type(1p)

TYPE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

type - write a description of command type

SYNOPSIS

type name...

DESCRIPTION

The type utility shall indicate how each argument would be interpreted if used as a command name.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

name
A name to be interpreted.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of type:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the location of name, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output of type contains information about each operand in an unspecified format. The information provided typically identifies the operand as a shell built-in, function, alias, or keyword, and where applicable, may display the operand's pathname.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since type must be aware of the contents of the current shell execution environment (such as the lists of commands, functions, and built-ins processed by hash), it is always provided as a shell regular built-in. If it is called in a separate utility execution environment, such as one of the following:

nohup type writer
find . -type f | xargs type
it might not produce accurate results.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

command , hash

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sed(1p)

SED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sed - stream editor

SYNOPSIS

sed [-n] script[file...]

sed [-n][-e script]...[-f script_file]...[file...]

DESCRIPTION

The sed utility is a stream editor that shall read one or more text files, make editing changes according to a script of editing commands, and write the results to standard output. The script shall be obtained from either the script operand string or a combination of the option-arguments from the -e script and -f script_file options.

OPTIONS

The sed utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the order of presentation of the -e and -f options is significant.

The following options shall be supported:

-e script
Add the editing commands specified by the script option-argument to the end of the script of editing commands. The script option-argument shall have the same properties as the script operand, described in the OPERANDS section.
-f script_file
Add the editing commands in the file script_file to the end of the script.
-n
Suppress the default output (in which each line, after it is examined for editing, is written to standard output). Only lines explicitly selected for output are written.

Multiple -e and -f options may be specified. All commands shall be added to the script in the order specified, regardless of their origin.

OPERANDS

The following operands shall be supported:

file
A pathname of a file whose contents are read and edited. If multiple file operands are specified, the named files shall be read in the order specified and the concatenation shall be edited. If no file operands are specified, the standard input shall be used.
script
A string to be used as the script of editing commands. The application shall not present a script that violates the restrictions of a text file except that the final character need not be a <newline>.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

The input files shall be text files. The script_files named by the -f option shall consist of editing commands.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of sed:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), and the behavior of character classes within regular expressions.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The input files shall be written to standard output, with the editing commands specified in the script applied. If the -n option is specified, only those input lines selected by the script shall be written to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output files shall be text files whose formats are dependent on the editing commands given.

EXTENDED DESCRIPTION

The script shall consist of editing commands of the following form:

[address[,address]]function

where function represents a single-character command verb from the list in Editing Commands in sed , followed by any applicable arguments.

The command can be preceded by <blank>s and/or semicolons. The function can be preceded by <blank>s. These optional characters shall have no effect.

In default operation, sed cyclically shall append a line of input, less its terminating <newline>, into the pattern space. Normally the pattern space will be empty, unless a D command terminated the last cycle. The sed utility shall then apply in sequence all commands whose addresses select that pattern space, and at the end of the script copy the pattern space to standard output (except when -n is specified) and delete the pattern space. Whenever the pattern space is written to standard output or a named file, sed shall immediately follow it with a <newline>.

Some of the editing commands use a hold space to save all or part of the pattern space for subsequent retrieval. The pattern and hold spaces shall each be able to hold at least 8192 bytes.

Addresses in sed

An address is either a decimal number that counts input lines cumulatively across files, a '$' character that addresses the last line of input, or a context address (which consists of a BRE, as described in Regular Expressions in sed , preceded and followed by a delimiter, usually a slash).

An editing command with no addresses shall select every pattern space.

An editing command with one address shall select each pattern space that matches the address.

An editing command with two addresses shall select the inclusive range from the first pattern space that matches the first address through the next pattern space that matches the second. (If the second address is a number less than or equal to the line number first selected, only one line shall be selected.) Starting at the first line following the selected range, sed shall look again for the first address. Thereafter, the process shall be repeated. Omitting either or both of the address components in the following form produces undefined results:

[address[,address]]

Regular Expressions in sed

The sed utility shall support the BREs described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions, with the following additions:

*
In a context address, the construction "\cBREc" , where c is any character other than backslash or <newline>, shall be identical to "/BRE/" . If the character designated by c appears following a backslash, then it shall be considered to be that literal character, which shall not terminate the BRE. For example, in the context address "\xabc\xdefx" , the second x stands for itself, so that the BRE is "abcxdef" .

*
The escape sequence '\n' shall match a <newline> embedded in the pattern space. A literal <newline> shall not be used in the BRE of a context address or in the substitute function.

*
If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.

Editing Commands in sed

In the following list of editing commands, the maximum number of permissible addresses for each function is indicated by [ 0addr], [ 1addr], or [ 2addr], representing zero, one, or two addresses.

The argument text shall consist of one or more lines. Each embedded <newline> in the text shall be preceded by a backslash. Other backslashes in text shall be removed, and the following character shall be treated literally.

The r and w command verbs, and the w flag to the s command, take an optional rfile (or wfile) parameter, separated from the command verb letter or flag by one or more <blank>s; implementations may allow zero separation as an extension.

The argument rfile or the argument wfile shall terminate the editing command. Each wfile shall be created before processing begins. Implementations shall support at least ten wfile arguments in the script; the actual number (greater than or equal to 10) that is supported by the implementation is unspecified. The use of the wfile parameter shall cause that file to be initially created, if it does not exist, or shall replace the contents of an existing file.

The b, r, s, t, w, y, and : command verbs shall accept additional arguments. The following synopses indicate which arguments shall be separated from the command verbs by a single <space>.

The a and r commands schedule text for later output. The text specified for the a command, and the contents of the file specified for the r command, shall be written to standard output just before the next attempt to fetch a line of input when executing the N or n commands, or when reaching the end of the script. If written when reaching the end of the script, and the -n option was not specified, the text shall be written after copying the pattern space to standard output. The contents of the file specified for the r command shall be as of the time the output is written, not the time the r command is applied. The text shall be output in the order in which the a and r commands were applied to the input.

Command verbs other than {, a, b, c, i, r, t, w, :, and # can be followed by a semicolon, optional <blank>s, and another command verb. However, when the s command verb is used with the w flag, following it with another command in this manner produces undefined results.

A function can be preceded by one or more '!' characters, in which case the function shall be applied if the addresses do not select the pattern space. Zero or more <blank>s shall be accepted before the first '!' character. It is unspecified whether <blank>s can follow a '!' character, and conforming applications shall not follow a '!' character with <blank>s.

[2addr] {function
function
...
}
Execute a list of sed functions only when the pattern space is selected. The list of sed functions shall be surrounded by braces and separated by <newline>s, and conform to the following rules. The braces can be preceded or followed by <blank>s. The functions can be preceded by <blank>s, but shall not be followed by <blank>s. The <right-brace> shall be preceded by a <newline> and can be preceded or followed by <blank>s.
[1addr]a\
text
Write text to standard output as described previously.
[2addr]b [label]

Branch to the : function bearing the label. If label is not specified, branch to the end of the script. The implementation shall support labels recognized as unique up to at least 8 characters; the actual length (greater than or equal to 8) that shall be supported by the implementation is unspecified. It is unspecified whether exceeding a label length causes an error or a silent truncation.

[2addr]c\
text
Delete the pattern space. With a 0 or 1 address or at the end of a 2-address range, place text on the output and start the next cycle.
[2addr]d
Delete the pattern space and start the next cycle.
[2addr]D
Delete the initial segment of the pattern space through the first <newline> and start the next cycle.
[2addr]g
Replace the contents of the pattern space by the contents of the hold space.
[2addr]G
Append to the pattern space a <newline> followed by the contents of the hold space.
[2addr]h
Replace the contents of the hold space with the contents of the pattern space.
[2addr]H
Append to the hold space a <newline> followed by the contents of the pattern space.
[1addr]i\
text
Write text to standard output.
[2addr]l
(The letter ell.) Write the pattern space to standard output in a visually unambiguous form. The characters listed in the Base Definitions volume of IEEE Std 1003.1-2001, Table 5-1, Escape Sequences and Associated Actions ( '\\' , '\a' , '\b' , '\f' , '\r' , '\t' , '\v' ) shall be written as the corresponding escape sequence; the '\n' in that table is not applicable. Non-printable characters not in that table shall be written as one three-digit octal number (with a preceding backslash) for each byte in the character (most significant byte first). If the size of a byte on the system is greater than 9 bits, the format used for non-printable characters is implementation-defined.

Long lines shall be folded, with the point of folding indicated by writing a backslash followed by a <newline>; the length at which folding occurs is unspecified, but should be appropriate for the output device. The end of each line shall be marked with a '$' .

[2addr]n
Write the pattern space to standard output if the default output has not been suppressed, and replace the pattern space with the next line of input, less its terminating <newline>.

If no next line of input is available, the n command verb shall branch to the end of the script and quit without starting a new cycle.

[2addr]N
Append the next line of input, less its terminating <newline>, to the pattern space, using an embedded <newline> to separate the appended material from the original material. Note that the current line number changes.

If no next line of input is available, the N command verb shall branch to the end of the script and quit without starting a new cycle or copying the pattern space to standard output.

[2addr]p
Write the pattern space to standard output.
[2addr]P
Write the pattern space, up to the first <newline>, to standard output.
[1addr]q
Branch to the end of the script and quit without starting a new cycle.
[1addr]r rfile
Copy the contents of rfile to standard output as described previously. If rfile does not exist or cannot be read, it shall be treated as if it were an empty file, causing no error condition.
[2addr]s/BRE/replacement/flags

Substitute the replacement string for instances of the BRE in the pattern space. Any character other than backslash or <newline> can be used instead of a slash to delimit the BRE and the replacement. Within the BRE and the replacement, the BRE delimiter itself can be used as a literal character if it is preceded by a backslash.

The replacement string shall be scanned from beginning to end. An ampersand ( '&' ) appearing in the replacement shall be replaced by the string matching the BRE. The special meaning of '&' in this context can be suppressed by preceding it by a backslash. The characters "\n", where n is a digit, shall be replaced by the text matched by the corresponding backreference expression. The special meaning of "\n" where n is a digit in this context, can be suppressed by preceding it by a backslash. For each other backslash ( '\' ) encountered, the following character shall lose its special meaning (if any). The meaning of a '\' immediately followed by any character other than '&' , '\' , a digit, or the delimiter character used for this command, is unspecified.

A line can be split by substituting a <newline> into it. The application shall escape the <newline> in the replacement by preceding it by a backslash. A substitution shall be considered to have been performed even if the replacement string is identical to the string that it replaces. Any backslash used to alter the default meaning of a subsequent character shall be discarded from the BRE or the replacement before evaluating the BRE or using the replacement.

The value of flags shall be zero or more of:

n
Substitute for the nth occurrence only of the BRE found within the pattern space.
g
Globally substitute for all non-overlapping instances of the BRE rather than just the first one. If both g and n are specified, the results are unspecified.
p
Write the pattern space to standard output if a replacement was made.
w wfile
Write. Append the pattern space to wfile if a replacement was made. A conforming application shall precede the wfile argument with one or more <blank>s. If the w flag is not the last flag value given in a concatenation of multiple flag values, the results are undefined.

[2addr]t [label]

Test. Branch to the : command verb bearing the label if any substitutions have been made since the most recent reading of an input line or execution of a t. If label is not specified, branch to the end of the script.

[2addr]w wfile

Append (write) the pattern space to wfile.

[2addr]x
Exchange the contents of the pattern and hold spaces.
[2addr]y/string1/string2/

Replace all occurrences of characters in string1 with the corresponding characters in string2. If a backslash followed by an 'n' appear in string1 or string2, the two characters shall be handled as a single <newline>. If the number of characters in string1 and string2 are not equal, or if any of the characters in string1 appear more than once, the results are undefined. Any character other than backslash or <newline> can be used instead of slash to delimit the strings. If the delimiter is not n, within string1 and string2, the delimiter itself can be used as a literal character if it is preceded by a backslash. If a backslash character is immediately followed by a backslash character in string1 or string2, the two backslash characters shall be counted as a single literal backslash character. The meaning of a backslash followed by any character that is not 'n' , a backslash, or the delimiter character is undefined.

[0addr]:label
Do nothing. This command bears a label to which the b and t commands branch.
[1addr]=
Write the following to standard output:

"%d\n", <current line number>
[0addr]
Ignore this empty command.
[0addr]#
Ignore the '#' and the remainder of the line (treat them as a comment), with the single exception that if the first two characters in the script are "#n" , the default output shall be suppressed; this shall be the equivalent of specifying -n on the command line.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Regular expressions match entire strings, not just individual lines, but a <newline> is matched by '\n' in a sed RE; a <newline> is not allowed by the general definition of regular expression in IEEE Std 1003.1-2001. Also note that '\n' cannot be used to match a <newline> at the end of an arbitrary input line; <newline>s appear in the pattern space as a result of the N editing command.

EXAMPLES

This sed script simulates the BSD cat -s command, squeezing excess blank lines from standard input.

sed -n '
# Write non-empty lines.
/./ {
    p
    d
    }
# Write a single empty line, then look for more empty lines.
/^$/    p
# Get next line, discard the held <newline> (empty line),
# and look for more empty lines.
:Empty
/^$/    {
    N
    s/.//
    b Empty
    }
# Write the non-empty line before going back to search
# for the first in a set of empty lines.
    p

RATIONALE

This volume of IEEE Std 1003.1-2001 requires implementations to support at least ten distinct wfiles, matching historical practice on many implementations. Implementations are encouraged to support more, but conforming applications should not exceed this limit.

The exit status codes specified here are different from those in System V. System V returns 2 for garbled sed commands, but returns zero with its usage message or if the input file could not be opened. The standard developers considered this to be a bug.

The manner in which the l command writes non-printable characters was changed to avoid the historical backspace-overstrike method, and other requirements to achieve unambiguous output were added. See the RATIONALE for ed for details of the format chosen, which is the same as that chosen for sed.

This volume of IEEE Std 1003.1-2001 requires implementations to provide pattern and hold spaces of at least 8192 bytes, larger than the 4000 bytes spaces used by some historical implementations, but less than the 20480 bytes limit used in an early proposal. Implementations are encouraged to allocate dynamically larger pattern and hold spaces as needed.

The requirements for acceptance of <blank>s and <space>s in command lines has been made more explicit than in early proposals to describe clearly the historical practice and to remove confusion about the phrase "protect initial blanks [sic] and tabs from the stripping that is done on every script line" that appears in much of the historical documentation of the sed utility description of text. (Not all implementations are known to have stripped <blank>s from text lines, although they all have allowed leading <blank>s preceding the address on a command line.)

The treatment of '#' comments differs from the SVID which only allows a comment as the first line of the script, but matches BSD-derived implementations. The comment character is treated as a command, and it has the same properties in terms of being accepted with leading <blank>s; the BSD implementation has historically supported this.

Early proposals required that a script_file have at least one non-comment line. Some historical implementations have behaved in unexpected ways if this were not the case. The standard developers considered that this was incorrect behavior and that application developers should not have to avoid this feature. A correct implementation of this volume of IEEE Std 1003.1-2001 shall permit script_files that consist only of comment lines.

Early proposals indicated that if -e and -f options were intermixed, all -e options were processed before any -f options. This has been changed to process them in the order presented because it matches historical practice and is more intuitive.

The treatment of the p flag to the s command differs between System V and BSD-based systems when the default output is suppressed. In the two examples:

echo a | sed    's/a/A/p'
echo a | sed -n 's/a/A/p'

this volume of IEEE Std 1003.1-2001, BSD, System V documentation, and the SVID indicate that the first example should write two lines with A, whereas the second should write one. Some System V systems write the A only once in both examples because the p flag is ignored if the -n option is not specified.

This is a case of a diametrical difference between systems that could not be reconciled through the compromise of declaring the behavior to be unspecified. The SVID/BSD/System V documentation behavior was adopted for this volume of IEEE Std 1003.1-2001 because:

*
No known documentation for any historic system describes the interaction between the p flag and the -n option.

*
The selected behavior is more correct as there is no technical justification for any interaction between the p flag and the -n option. A relationship between -n and the p flag might imply that they are only used together, but this ignores valid scripts that interrupt the cyclical nature of the processing through the use of the D, d, q, or branching commands. Such scripts rely on the p suffix to write the pattern space because they do not make use of the default output at the "bottom" of the script.

*
Because the -n option makes the p flag unnecessary, any interaction would only be useful if sed scripts were written to run both with and without the -n option. This is believed to be unlikely. It is even more unlikely that programmers have coded the p flag expecting it to be unnecessary. Because the interaction was not documented, the likelihood of a programmer discovering the interaction and depending on it is further decreased.

*
Finally, scripts that break under the specified behavior produce too much output instead of too little, which is easier to diagnose and correct.

The form of the substitute command that uses the n suffix was limited to the first 512 matches in an early proposal. This limit has been removed because there is no reason an editor processing lines of {LINE_MAX} length should have this restriction. The command s/a/A/2047 should be able to substitute the 2047th occurrence of a on a line.

The b, t, and : commands are documented to ignore leading white space, but no mention is made of trailing white space. Historical implementations of sed assigned different locations to the labels 'x' and "x " . This is not useful, and leads to subtle programming errors, but it is historical practice, and changing it could theoretically break working scripts. Implementors are encouraged to provide warning messages about labels that are never used or jumps to labels that do not exist.

Historically, the sed ! and } editing commands did not permit multiple commands on a single line using a semicolon as a command delimiter. Implementations are permitted, but not required, to support this extension.

FUTURE DIRECTIONS

None.

SEE ALSO

awk , ed , grep

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


set(1p)

SET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

set - set or unset options and positional parameters

SYNOPSIS

set [-abCefmnuvx][-h][-o option][argument...]

set [+abCefmnuvx][+h][+o option][argument...]

set -- [argument...]

set -o

set +o

DESCRIPTION

If no options or arguments are specified, set shall write the names and values of all shell variables in the collation sequence of the current locale. Each name shall start on a separate line, using the format:

"%s=%s\n", <name>, <value>

The value string shall be written with appropriate quoting; see the description of shell quoting in Quoting . The output shall be suitable for reinput to the shell, setting or resetting, as far as possible, the variables that are currently set; read-only variables cannot be reset.

When options are specified, they shall set or unset attributes of the shell, as described below. When arguments are specified, they cause positional parameters to be set or unset, as described below. Setting or unsetting attributes and positional parameters are not necessarily related actions, but they can be combined in a single invocation of set.

The set special built-in shall support the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines except that options can be specified with either a leading hyphen (meaning enable the option) or plus sign (meaning disable it) unless otherwise specified.

Implementations shall support the options in the following list in both their hyphen and plus-sign forms. These options can also be specified as options to sh.

-a
When this option is on, the export attribute shall be set for each variable to which an assignment is performed; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.21, Variable Assignment. If the assignment precedes a utility name in a command, the export attribute shall not persist in the current execution environment after the utility completes, with the exception that preceding one of the special built-in utilities causes the export attribute to persist after the built-in has completed. If the assignment does not precede a utility name in the command, or if the assignment is a result of the operation of the getopts or read utilities, the export attribute shall persist until the variable is unset.
-b
This option shall be supported if the implementation supports the User Portability Utilities option. It shall cause the shell to notify the user asynchronously of background job completions. The following message is written to standard error:

"[%d]%c %s%s\n", <job-number>, <current>, <status>, <job-name>

where the fields shall be as follows:

<current>
The character '+' identifies the job that would be used as a default for the fg or bg utilities; this job can also be specified using the job_id "%+" or "%%" . The character '-' identifies the job that would become the default if the current default job were to exit; this job can also be specified using the job_id "%-" . For other jobs, this field is a <space>. At most one job can be identified with '+' and at most one job can be identified with '-' . If there is any suspended job, then the current job shall be a suspended job. If there are at least two suspended jobs, then the previous job also shall be a suspended job.
<job-number>
A number that can be used to identify the process group to the wait, fg, bg, and kill utilities. Using these utilities, the job can be identified by prefixing the job number with '%' .
<status>
Unspecified.
<job-name>
Unspecified.

When the shell notifies the user a job has been completed, it may remove the job's process ID from the list of those known in the current shell execution environment; see Asynchronous Lists . Asynchronous notification shall not be enabled by default.

-C
(Uppercase C.) Prevent existing files from being overwritten by the shell's '>' redirection operator (see Redirecting Output ); the ">|" redirection operator shall override this noclobber option for an individual file.
-e
When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.
-f
The shell shall disable pathname expansion.
-h
Locate and remember utilities invoked by functions as those functions are defined (the utilities are normally located when the function is executed).
-m
This option shall be supported if the implementation supports the User Portability Utilities option. All jobs shall be run in their own process groups. Immediately before the shell issues a prompt after completion of the background job, a message reporting the exit status of the background job shall be written to standard error. If a foreground job stops, the shell shall write a message to standard error to that effect, formatted as described by the jobs utility. In addition, if a job changes status other than exiting (for example, if it stops for input or output or is stopped by a SIGSTOP signal), the shell shall write a similar message immediately prior to writing the next prompt. This option is enabled by default for interactive shells.
-n
The shell shall read commands but does not execute them; this can be used to check for shell script syntax errors. An interactive shell may ignore this option.
-o
Write the current settings of the options to standard output in an unspecified format.
+o
Write the current option settings to standard output in a format that is suitable for reinput to the shell as commands that achieve the same options settings.
-o option

This option is supported if the system supports the User Portability Utilities option. It shall set various options, many of which shall be equivalent to the single option letters. The following values of option shall be supported:

allexport
Equivalent to -a.
errexit
Equivalent to -e.
ignoreeof
Prevent an interactive shell from exiting on end-of-file. This setting prevents accidental logouts when <control>-D is entered. A user shall explicitly exit to leave the interactive shell.
monitor
Equivalent to -m. This option is supported if the system supports the User Portability Utilities option.
noclobber
Equivalent to -C (uppercase C).
noglob
Equivalent to -f.
noexec
Equivalent to -n.
nolog
Prevent the entry of function definitions into the command history; see Command History List .
notify
Equivalent to -b.
nounset
Equivalent to -u.
verbose
Equivalent to -v.
vi
Allow shell command line editing using the built-in vi editor. Enabling vi mode shall disable any other command line editing mode provided as an implementation extension.

It need not be possible to set vi mode on for certain block-mode terminals.

xtrace
Equivalent to -x.

-u
The shell shall write a message to standard error when it tries to expand a variable that is not set and immediately exit. An interactive shell shall not exit.
-v
The shell shall write its input to standard error as it is read.
-x
The shell shall write to standard error a trace for each command after it expands the command and before it executes it. It is unspecified whether the command that turns tracing off is traced.

The default for all these options shall be off (unset) unless stated otherwise in the description of the option or unless the shell was invoked with them on; see sh.

The remaining arguments shall be assigned in order to the positional parameters. The special parameter '#' shall be set to reflect the number of positional parameters. All positional parameters shall be unset before any new values are assigned.

The special argument "--" immediately following the set command name can be used to delimit the arguments if the first argument begins with '+' or '-' , or to prevent inadvertent listing of all shell variables when there are no arguments. The command set -- without argument shall unset all positional parameters and set the special parameter '#' to zero.

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Zero.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Write out all variables and their values:

set

Set $1, $2, and $3 and set "$#" to 3:

set c a b

Turn on the -x and -v options:

set -xv

Unset all positional parameters:

set --

Set $1 to the value of x, even if it begins with '-' or '+' :

set -- "$x"

Set the positional parameters to the expansion of x, even if x expands with a leading '-' or '+' :

set -- $x

RATIONALE

The set -- form is listed specifically in the SYNOPSIS even though this usage is implied by the Utility Syntax Guidelines. The explanation of this feature removes any ambiguity about whether the set -- form might be misinterpreted as being equivalent to set without any options or arguments. The functionality of this form has been adopted from the KornShell. In System V, set -- only unsets parameters if there is at least one argument; the only way to unset all parameters is to use shift. Using the KornShell version should not affect System V scripts because there should be no reason to issue it without arguments deliberately; if it were issued as, for example:

set -- "$@"

and there were in fact no arguments resulting from "$@" , unsetting the parameters would have no result.

The set + form in early proposals was omitted as being an unnecessary duplication of set alone and not widespread historical practice.

The noclobber option was changed to allow set -C as well as the set -o noclobber option. The single-letter version was added so that the historical "$-" paradigm would not be broken; see Special Parameters .

The -h flag is related to command name hashing and is only required on XSI-conformant systems.

The following set flags were omitted intentionally with the following rationale:

-k
The -k flag was originally added by the author of the Bourne shell to make it easier for users of pre-release versions of the shell. In early versions of the Bourne shell the construct set name= value had to be used to assign values to shell variables. The problem with -k is that the behavior affects parsing, virtually precluding writing any compilers. To explain the behavior of -k, it is necessary to describe the parsing algorithm, which is implementation-defined. For example:

set -k; echo name=value

and:

set -k
echo name=value

behave differently. The interaction with functions is even more complex. What is more, the -k flag is never needed, since the command line could have been reordered.

-t
The -t flag is hard to specify and almost never used. The only known use could be done with here-documents. Moreover, the behavior with ksh and sh differs. The reference page says that it exits after reading and executing one command. What is one command? If the input is date; date, sh executes both date commands while ksh does only the first.

Consideration was given to rewriting set to simplify its confusing syntax. A specific suggestion was that the unset utility should be used to unset options instead of using the non- getopt() -able + option syntax. However, the conclusion was reached that the historical practice of using + option was satisfactory and that there was no compelling reason to modify such widespread historical practice.

The -o option was adopted from the KornShell to address user needs. In addition to its generally friendly interface, -o is needed to provide the vi command line editing mode, for which historical practice yields no single-letter option name. (Although it might have been possible to invent such a letter, it was recognized that other editing modes would be developed and -o provides ample name space for describing such extensions.)

Historical implementations are inconsistent in the format used for -o option status reporting. The +o format without an option-argument was added to allow portable access to the options that can be saved and then later restored using, for instance, a dot script.

Historically, sh did trace the command set +x, but ksh did not.

The ignoreeof setting prevents accidental logouts when the end-of-file character (typically <control>-D) is entered. A user shall explicitly exit to leave the interactive shell.

The set -m option was added to apply only to the UPE because it applies primarily to interactive use, not shell script applications.

The ability to do asynchronous notification became available in the 1988 version of the KornShell. To have it occur, the user had to issue the command:

trap "jobs -n" CLD

The C shell provides two different levels of an asynchronous notification capability. The environment variable notify is analogous to what is done in set -b or set -o notify. When set, it notifies the user immediately of background job completions. When unset, this capability is turned off.

The other notification ability comes through the built-in utility notify. The syntax is:

notify [%job ... ]

By issuing notify with no operands, it causes the C shell to notify the user asynchronously when the state of the current job changes. If given operands, notify asynchronously informs the user of changes in the states of the specified jobs.

To add asynchronous notification to the POSIX shell, neither the KornShell extensions to trap, nor the C shell notify environment variable seemed appropriate ( notify is not a proper POSIX environment variable name).

The set -b option was selected as a compromise.

The notify built-in was considered to have more functionality than was required for simple asynchronous notification.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tee(1p)

TEE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tee - duplicate standard input

SYNOPSIS

tee [-ai][file...]

DESCRIPTION

The tee utility shall copy standard input to standard output, making a copy in zero or more files. The tee utility shall not buffer output.

If the -a option is not specified, output files shall be written (see File Read, Write, and Creation .

OPTIONS

The tee utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Append the output to the files.
-i
Ignore the SIGINT signal.

OPERANDS

The following operands shall be supported:

file
A pathname of an output file. Processing of at least 13 file operands shall be supported.

STDIN

The standard input can be of any type.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of tee:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default, except that if the -i option was specified, SIGINT shall be ignored.

STDOUT

The standard output shall be a copy of the standard input.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

If any file operands are specified, the standard input shall be copied to each named file.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The standard input was successfully copied to all output files.
>0
An error occurred.

CONSEQUENCES OF ERRORS

If a write to any successfully opened file operand fails, writes to other successfully opened file operands and standard output shall continue, but the exit status shall be non-zero. Otherwise, the default actions specified in Utility Description Defaults apply.

The following sections are informative.

APPLICATION USAGE

The tee utility is usually used in a pipeline, to make a copy of the output of some utility.

The file operand is technically optional, but tee is no more useful than cat when none is specified.

EXAMPLES

Save an unsorted intermediate form of the data in a pipeline:

... | tee unsorted | sort > sorted

RATIONALE

The buffering requirement means that tee is not allowed to use ISO C standard fully buffered or line-buffered writes. It does not mean that tee has to do 1-byte reads followed by 1-byte writes.

It should be noted that early versions of BSD ignore any invalid options and accept a single '-' as an alternative to -i. They also print a message if unable to open a file:

"tee: cannot access %s\n", <pathname>

Historical implementations ignore write errors. This is explicitly not permitted by this volume of IEEE Std 1003.1-2001.

Some historical implementations use O_APPEND when providing append mode; others use the lseek() function to seek to the end-of-file after opening the file without O_APPEND. This volume of IEEE Std 1003.1-2001 requires functionality equivalent to using O_APPEND; see File Read, Write, and Creation .

FUTURE DIRECTIONS

None.

SEE ALSO

Introduction , cat , the System Interfaces volume of IEEE Std 1003.1-2001, lseek()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


locale(1p)

LOCALE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

locale - get locale-specific information

SYNOPSIS

locale [-a| -m]

locale [-ck] name...

DESCRIPTION

The locale utility shall write information about the current locale environment, or all public locales, to the standard output. For the purposes of this section, a public locale is one provided by the implementation that is accessible to the application.

When locale is invoked without any arguments, it shall summarize the current locale environment for each locale category as determined by the settings of the environment variables defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

When invoked with operands, it shall write values that have been assigned to the keywords in the locale categories, as follows:

*
Specifying a keyword name shall select the named keyword and the category containing that keyword.

*
Specifying a category name shall select the named category and all keywords in that category.

OPTIONS

The locale utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Write information about all available public locales. The available locales shall include POSIX, representing the POSIX locale. The manner in which the implementation determines what other locales are available is implementation-defined.
-c
Write the names of selected locale categories; see the STDOUT section. The -c option increases readability when more than one category is selected (for example, via more than one keyword name or via a category name). It is valid both with and without the -k option.
-k
Write the names and values of selected keywords. The implementation may omit values for some keywords; see the OPERANDS section.
-m
Write names of available charmaps; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set.

OPERANDS

The following operand shall be supported:

name
The name of a locale category as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, the name of a keyword in a locale category, or the reserved name charmap. The named category or keyword shall be selected for output. If a single name represents both a locale category name and a keyword name in the current locale, the results are unspecified. Otherwise, both category and keyword names can be specified as name operands, in any sequence. It is implementation-defined whether any keyword values are written for the categories LC_CTYPE and LC_COLLATE .

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of locale:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

The application shall ensure that the LANG , LC_* , and NLSPATH environment variables specify the current locale environment to be written out; they shall be used if the -a option is not specified.

ASYNCHRONOUS EVENTS

Default.

STDOUT

If locale is invoked without any options or operands, the names and values of the LANG and LC_* environment variables described in this volume of IEEE Std 1003.1-2001 shall be written to the standard output, one variable per line, with LANG first, and each line using the following format. Only those variables set in the environment and not overridden by LC_ALL shall be written using this format:

"%s=%s\n", <variable_name>, <value>

The names of those LC_* variables associated with locale categories defined in this volume of IEEE Std 1003.1-2001 that are not set in the environment or are overridden by LC_ALL shall be written in the following format:

"%s=\"%s\"\n", <variable_name>, <implied value>

The <implied value> shall be the name of the locale that has been selected for that category by the implementation, based on the values in LANG and LC_ALL , as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

The <value> and <implied value> shown above shall be properly quoted for possible later reentry to the shell. The <value> shall not be quoted using double-quotes (so that it can be distinguished by the user from the <implied value> case, which always requires double-quotes).

The LC_ALL variable shall be written last, using the first format shown above. If it is not set, it shall be written as:

"LC_ALL=\n"

If any arguments are specified:

1.
If the -a option is specified, the names of all the public locales shall be written, each in the following format:

"%s\n", <locale name>

2.
If the -c option is specified, the names of all selected categories shall be written, each in the following format:

"%s\n", <category name>

If keywords are also selected for writing (see following items), the category name output shall precede the keyword output for that category.

If the -c option is not specified, the names of the categories shall not be written; only the keywords, as selected by the <name> operand, shall be written.

3.
If the -k option is specified, the names and values of selected keywords shall be written. If a value is non-numeric, it shall be written in the following format:

"%s=\"%s\"\n", <keyword name>, <keyword value>

If the keyword was charmap, the name of the charmap (if any) that was specified via the localedef -f option when the locale was created shall be written, with the word charmap as <keyword name>.

If a value is numeric, it shall be written in one of the following formats:

"%s=%d\n", <keyword name>, <keyword value>

"%s=%c%o\n", <keyword name>, <escape character>, <keyword value>

"%s=%cx%x\n", <keyword name>, <escape character>, <keyword value>

where the <escape character> is that identified by the escape_char keyword in the current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3, Locale Definition.

Compound keyword values (list entries) shall be separated in the output by semicolons. When included in keyword values, the semicolon, the double-quote, the backslash, and any control character shall be preceded (escaped) with the escape character.

4.
If the -k option is not specified, selected keyword values shall be written, each in the following format:

"%s\n", <keyword value>

If the keyword was charmap, the name of the charmap (if any) that was specified via the localedef -f option when the locale was created shall be written.

5.
If the -m option is specified, then a list of all available charmaps shall be written, each in the format:

"%s\n", <charmap>

where <charmap> is in a format suitable for use as the option-argument to the localedef -f option.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All the requested information was found and output successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

If the LANG environment variable is not set or set to an empty value, or one of the LC_* environment variables is set to an unrecognized value, the actual locales assumed (if any) are implementation-defined as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

Implementations are not required to write out the actual values for keywords in the categories LC_CTYPE and LC_COLLATE ; however, they must write out the categories (allowing an application to determine, for example, which character classes are available).

EXAMPLES

In the following examples, the assumption is that locale environment variables are set as follows:

LANG=locale_x
LC_COLLATE=locale_y

The command locale would result in the following output:

LANG=locale_x
LC_CTYPE="locale_x"
LC_COLLATE=locale_y
LC_TIME="locale_x"
LC_NUMERIC="locale_x"
LC_MONETARY="locale_x"
LC_MESSAGES="locale_x"
LC_ALL=

The order of presentation of the categories is not specified by this volume of IEEE Std 1003.1-2001.

The command:

LC_ALL=POSIX locale -ck decimal_point

would produce:

LC_NUMERIC
decimal_point="."

The following command shows an application of locale to determine whether a user-supplied response is affirmative:

if printf "%s\n" "$response" | grep -Eq "$(locale yesexpr)"
then
    affirmative processing goes here
else
    non-affirmative processing goes here
fi

RATIONALE

The output for categories LC_CTYPE and LC_COLLATE has been made implementation-defined because there is a questionable value in having a shell script receive an entire array of characters. It is also difficult to return a logical collation description, short of returning a complete localedef source.

The -m option was included to allow applications to query for the existence of charmaps. The output is a list of the charmaps (implementation-supplied and user-supplied, if any) on the system.

The -c option was included for readability when more than one category is selected (for example, via more than one keyword name or via a category name). It is valid both with and without the -k option.

The charmap keyword, which returns the name of the charmap (if any) that was used when the current locale was created, was included to allow applications needing the information to retrieve it.

FUTURE DIRECTIONS

None.

SEE ALSO

localedef , the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3, Locale Definition

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


admin(1p)

ADMIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

admin - create and administer SCCS files (DEVELOPMENT)

SYNOPSIS

admin -i[name][-n][-a login][-d flag][-e login][-f flag][-m mrlist]
[-r rel][-t[name][-y[comment]] newfile

admin -n[-a login][-d flag][-e login][-f flag][-m mrlist][-t[name]]
[-y[comment]] newfile ...

admin [-a login][-d flag][-m mrlist][-r rel][-t[name]] file ...

admin -h file ...

admin -z file ...

DESCRIPTION

The admin utility shall create new SCCS files or change parameters of existing ones. If a named file does not exist, it shall be created, and its parameters shall be initialized according to the specified options. Parameters not initialized by an option shall be assigned a default value. If a named file does exist, parameters corresponding to specified options shall be changed, and other parameters shall be left as is.

All SCCS filenames supplied by the application shall be of the form s.filename. New SCCS files shall be given read-only permission mode. Write permission in the parent directory is required to create a file. All writing done by admin shall be to a temporary x-file, named x.filename (see get ) created with read-only mode if admin is creating a new SCCS file, or created with the same mode as that of the SCCS file if the file already exists. After successful execution of admin, the SCCS file shall be removed (if it exists), and the x-file shall be renamed with the name of the SCCS file. This ensures that changes are made to the SCCS file only if no errors occur.

The admin utility shall also use a transient lock file (named z.filename), which is used to prevent simultaneous updates to the SCCS file; see get .

OPTIONS

The admin utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the -i, -t, and -y options have optional option-arguments. These optional option-arguments shall not be presented as separate arguments. The following options are supported:

-n
Create a new SCCS file. When -n is used without -i, the SCCS file shall be created with control information but without any file data.
-i[name]
Specify the name of a file from which the text for a new SCCS file shall be taken. The text constitutes the first delta of the file (see the -r option for the delta numbering scheme). If the -i option is used, but the name option-argument is omitted, the text shall be obtained by reading the standard input. If this option is omitted, the SCCS file shall be created with control information but without any file data. The -i option implies the -n option.
-r SID
Specify the SID of the initial delta to be inserted. This SID shall be a trunk SID; that is, the branch and sequence numbers shall be zero or missing. The level number is optional, and defaults to 1.
-t[name]
Specify the name of a file from which descriptive text for the SCCS file shall be taken. In the case of existing SCCS files (neither -i nor -n is specified):
*
A -t option without a name option-argument shall cause the removal of descriptive text (if any) currently in the SCCS file.

*
A -t option with a name option-argument shall cause the text (if any) in the named file to replace the descriptive text (if any) currently in the SCCS file.

-f flag
Specify a flag, and, possibly, a value for the flag, to be placed in the SCCS file. Several -f options may be supplied on a single admin command line. Implementations shall recognize the following flags and associated values:
b
Allow use of the -b option on a get command to create branch deltas.
c ceil
Specify the highest release (that is, ceiling), a number less than or equal to 9999, which may be retrieved by a get command for editing. The default value for an unspecified c flag shall be 9999.
f floor
Specify the lowest release (that is, floor), a number greater than 0 but less than 9999, which may be retrieved by a get command for editing. The default value for an unspecified f flag shall be 1.
d SID
Specify the default delta number (SID) to be used by a get command.
i str
Treat the "No ID keywords" message issued by get or delta as a fatal error. In the absence of this flag, the message is only a warning. The message is issued if no SCCS identification keywords (see get ) are found in the text retrieved or stored in the SCCS file. If a value is supplied, the application shall ensure that the keywords exactly match the given string; however, the string shall contain a keyword, and no embedded <newline>s.
j
Allow concurrent get commands for editing on the same SID of an SCCS file. This allows multiple concurrent updates to the same version of the SCCS file.
l list
Specify a list of releases to which deltas can no longer be made (that is, get -e against one of these locked releases fails). Conforming applications shall use the following syntax to specify a list. Implementations may accept additional forms as an extension:

<list> ::= a | <range-list>
<range-list> ::= <range> | <range-list>, <range>
<range> ::= <SID>

The character a in the list shall be equivalent to specifying all releases for the named SCCS file. The non-terminal <SID> in range shall be the delta number of an existing delta associated with the SCCS file.

n
Cause delta to create a null delta in each of those releases (if any) being skipped when a delta is made in a new release (for example, in making delta 5.1 after delta 2.7, releases 3 and 4 are skipped). These null deltas shall serve as anchor points so that branch deltas may later be created from them. The absence of this flag shall cause skipped releases to be nonexistent in the SCCS file, preventing branch deltas from being created from them in the future. During the initial creation of an SCCS file, the n flag may be ignored; that is, if the -r option is used to set the release number of the initial SID to a value greater than 1, null deltas need not be created for the "skipped" releases.
q text
Substitute user-definable text for all occurrences of the %Q% keyword in the SCCS file text retrieved by get.
m mod
Specify the module name of the SCCS file substituted for all occurrences of the %M% keyword in the SCCS file text retrieved by get. If the m flag is not specified, the value assigned shall be the name of the SCCS file with the leading '.' removed.
t type
Specify the type of module in the SCCS file substituted for all occurrences of the %Y% keyword in the SCCS file text retrieved by get.
v pgm
Cause delta to prompt for modification request (MR) numbers as the reason for creating a delta. The optional value specifies the name of an MR number validation program. (If this flag is set when creating an SCCS file, the application shall ensure that the m option is also used even if its value is null.)

-d flag
Remove (delete) the specified flag from an SCCS file. Several -d options may be supplied on a single admin command. See the -f option for allowable flag names. (The l list flag gives a list of releases to be unlocked. See the -f option for further description of the l flag and the syntax of a list.)
-a login
Specify a login name, or numerical group ID, to be added to the list of users who may make deltas (changes) to the SCCS file. A group ID shall be equivalent to specifying all login names common to that group ID. Several -a options may be used on a single admin command line. As many logins, or numerical group IDs, as desired may be on the list simultaneously. If the list of users is empty, then anyone may add deltas. If login or group ID is preceded by a '!' , the users so specified shall be denied permission to make deltas.
-e login
Specify a login name, or numerical group ID, to be erased from the list of users allowed to make deltas (changes) to the SCCS file. Specifying a group ID is equivalent to specifying all login names common to that group ID. Several -e options may be used on a single admin command line.
-y[comment]
Insert the comment text into the SCCS file as a comment for the initial delta in a manner identical to that of delta. In the POSIX locale, omission of the -y option shall result in a default comment line being inserted in the form:

"date and time created %s %s by %s", <date>, <time>, <login>

where <date> is expressed in the format of the date utility's %y / %m / %d conversion specification, <time> in the format of the date utility's %T conversion specification format, and <login> is the login name of the user creating the file.

-m mrlist
Insert the list of modification request (MR) numbers into the SCCS file as the reason for creating the initial delta in a manner identical to delta. The application shall ensure that the v flag is set and the MR numbers are validated if the v flag has a value (the name of an MR number validation program). A diagnostic message shall be written if the v flag is not set or MR validation fails.
-h
Check the structure of the SCCS file and compare the newly computed checksum with the checksum that is stored in the SCCS file. If the newly computed checksum does not match the checksum in the SCCS file, a diagnostic message shall be written.
-z
Recompute the SCCS file checksum and store it in the first line of the SCCS file (see the -h option above). Note that use of this option on a truly corrupted file may prevent future detection of the corruption.

OPERANDS

The following operands shall be supported:

file
A pathname of an existing SCCS file or a directory. If file is a directory, the admin utility shall behave as though each file in the directory were specified as a named file, except that non-SCCS files (last component of the pathname does not begin with s.) and unreadable files shall be silently ignored.
newfile
A pathname of an SCCS file to be created.

If exactly one file or newfile operand appears, and it is '-' , the standard input shall be read; each line of the standard input shall be taken to be the name of an SCCS file to be processed. Non-SCCS files and unreadable files shall be silently ignored.

STDIN

The standard input shall be a text file used only if -i is specified without an option-argument or if a file or newfile operand is specified as '-' . If the first character of any standard input line is <SOH> in the POSIX locale, the results are unspecified.

INPUT FILES

The existing SCCS files shall be text files of an unspecified format.

The application shall ensure that the file named by the -i option's name option-argument shall be a text file; if the first character of any line in this file is <SOH> in the POSIX locale, the results are unspecified. If this file contains more than 99999 lines, the number of lines recorded in the header for this file shall be 99999 for this delta.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of admin:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and the contents of the default -y comment.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

Any SCCS files created shall be text files of an unspecified format. During processing of a file, a locking z-file, as described in get , may be created and deleted.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

It is recommended that directories containing SCCS files be writable by the owner only, and that SCCS files themselves be read-only. The mode of the directories should allow only the owner to modify SCCS files contained in the directories. The mode of the SCCS files prevents any modification at all except by SCCS commands.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

delta , get , prs , what

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qmove(1p)

QMOVE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qmove - move batch jobs

SYNOPSIS

qmove destination job_identifier ...

DESCRIPTION

To move a batch job is to remove the batch job from the batch queue in which it resides and instantiate the batch job in another batch queue. A batch job is moved by a request to the batch server that manages the batch job. The qmove utility is a user-accessible batch client that requests the movement of one or more batch jobs.

The qmove utility shall move those batch jobs, and only those batch jobs, for which a batch job_identifier is presented to the utility.

The qmove utility shall move batch jobs in the order in which the corresponding batch job_identifiers are presented to the utility.

If the qmove utility fails to process a batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

The qmove utility shall move batch jobs by sending a Move Job Request to the batch server that manages each batch job. The qmove utility shall not exit before the batch jobs corresponding to all successfully processed batch job_identifiers have been moved.

OPTIONS

None.

OPERANDS

The qmove utility shall accept one operand that conforms to the syntax for a destination (see Destination ).

The qmove utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qmove:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qmove utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qmove utility waits to output the diagnostic message while attempting to locate the job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qmove utility allows users to move jobs between queues.

The alternative to using the qmove utility-deleting the batch job and requeuing it-entails considerably more typing.

Since the means of selecting jobs based on attributes has been encapsulated in the qselect utility, the only option of the qmove utility concerns authorization. The -u option provides the user with the convenience of changing the user identifier under which the batch job will execute. Minimalism and consistency have taken precedence over convenience; the -u option has been deleted because the equivalent capability exists with the -u option of the qalter utility.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , qalter , qselect

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pathchk(1p)

PATHCHK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pathchk - check pathnames

SYNOPSIS

pathchk [-p] pathname...

DESCRIPTION

The pathchk utility shall check that one or more pathnames are valid (that is, they could be used to access or create a file without causing syntax errors) and portable (that is, no filename truncation results). More extensive portability checks are provided by the -p option.

By default, the pathchk utility shall check each component of each pathname operand based on the underlying file system. A diagnostic shall be written for each pathname operand that:

*
Is longer than {PATH_MAX} bytes (see Pathname Variable Values in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers, <limits.h>)

*
Contains any component longer than {NAME_MAX} bytes in its containing directory

*
Contains any component in a directory that is not searchable

*
Contains any character in any component that is not valid in its containing directory

The format of the diagnostic message is not specified, but shall indicate the error detected and the corresponding pathname operand.

It shall not be considered an error if one or more components of a pathname operand do not exist as long as a file matching the pathname specified by the missing components could be created that does not violate any of the checks specified above.

OPTIONS

The pathchk utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-p
Instead of performing checks based on the underlying file system, write a diagnostic for each pathname operand that:
*
Is longer than {_POSIX_PATH_MAX} bytes (see Minimum Values in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers, <limits.h>)

*
Contains any component longer than {_POSIX_NAME_MAX} bytes

*
Contains any character in any component that is not in the portable filename character set

OPERANDS

The following operand shall be supported:

pathname
A pathname to be checked.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of pathchk:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All pathname operands passed all of the checks.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The test utility can be used to determine whether a given pathname names an existing file; it does not, however, give any indication of whether or not any component of the pathname was truncated in a directory where the _POSIX_NO_TRUNC feature is not in effect. The pathchk utility does not check for file existence; it performs checks to determine whether a pathname does exist or could be created with no pathname component truncation.

The noclobber option in the shell (see the set special built-in) can be used to atomically create a file. As with all file creation semantics in the System Interfaces volume of IEEE Std 1003.1-2001, it guarantees atomic creation, but still depends on applications to agree on conventions and cooperate on the use of files after they have been created.

EXAMPLES

To verify that all pathnames in an imported data interchange archive are legitimate and unambiguous on the current system:

pax -f archive | sed -e '/ == .*/s///' | xargs pathchk
if [ $? -eq 0 ]
then
    pax -r -f archive
else
    echo Investigate problems before importing files.
    exit 1
fi

To verify that all files in the current directory hierarchy could be moved to any system conforming to the System Interfaces volume of IEEE Std 1003.1-2001 that also supports the pax utility:

find . -print | xargs pathchk -p
if [ $? -eq 0 ]
then
    pax -w -f archive .
else
    echo Portable archive cannot be created.
    exit 1
fi

To verify that a user-supplied pathname names a readable file and that the application can create a file extending the given path without truncation and without overwriting any existing file:

case $- in
    *C*)    reset="";;
    *)      reset="set +C"
            set -C;;
esac
test -r "$path" && pathchk "$path.out" &&
    rm "$path.out" > "$path.out"
if [ $? -ne 0 ]; then
    printf "%s: %s not found or %s.out fails \
creation checks.\n" $0 "$path" "$path"
    $reset    # Reset the noclobber option in case a trap
              # on EXIT depends on it.
    exit 1
fi
$reset
PROCESSING < "$path" > "$path.out"

The following assumptions are made in this example:

1.
PROCESSING represents the code that is used by the application to use $path once it is verified that $path.out works as intended.

2.
The state of the noclobber option is unknown when this code is invoked and should be set on exit to the state it was in when this code was invoked. (The reset variable is used in this example to restore the initial state.)

3.
Note the usage of:

rm "$path.out" > "$path.out"
a.
The pathchk command has already verified, at this point, that $path.out is not truncated.

b.
With the noclobber option set, the shell verifies that $path.out does not already exist before invoking rm.

c.
If the shell succeeded in creating $path.out, rm removes it so that the application can create the file again in the PROCESSING step.

d.
If the PROCESSING step wants the file to exist already when it is invoked, the:

rm "$path.out" > "$path.out"

should be replaced with:

> "$path.out"

which verifies that the file did not already exist, but leaves $path.out in place for use by PROCESSING.

RATIONALE

The pathchk utility was new for the ISO POSIX-2:1993 standard. It, along with the set -C( noclobber) option added to the shell, replaces the mktemp, validfnam, and create utilities that appeared in early proposals. All of these utilities were attempts to solve several common problems:

*
Verify the validity (for several different definitions of "valid") of a pathname supplied by a user, generated by an application, or imported from an external source.

*
Atomically create a file.

*
Perform various string handling functions to generate a temporary filename.

The create utility, included in an early proposal, provided checking and atomic creation in a single invocation of the utility; these are orthogonal issues and need not be grouped into a single utility. Note that the noclobber option also provides a way of creating a lock for process synchronization; since it provides an atomic create, there is no race between a test for existence and the following creation if it did not exist.

Having a function like tmpnam() in the ISO C standard is important in many high-level languages. The shell programming language, however, has built-in string manipulation facilities, making it very easy to construct temporary filenames. The names needed obviously depend on the application, but are frequently of a form similar to:

$TMPDIR/application_abbreviation$$.suffix

In cases where there is likely to be contention for a given suffix, a simple shell for or while loop can be used with the shell noclobber option to create a file without risk of collisions, as long as applications trying to use the same filename name space are cooperating on the use of files after they have been created.

FUTURE DIRECTIONS

None.

SEE ALSO

Redirection , set , test

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tty(1p)

TTY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tty - return user's terminal name

SYNOPSIS

tty

DESCRIPTION

The tty utility shall write to the standard output the name of the terminal that is open as standard input. The name that is used shall be equivalent to the string that would be returned by the ttyname() function defined in the System Interfaces volume of IEEE Std 1003.1-2001.

OPTIONS

The tty utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

OPERANDS

None.

STDIN

While no input is read from standard input, standard input shall be examined to determine whether or not it is a terminal, and, if so, to determine the name of the terminal.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of tty:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

If standard input is a terminal device, a pathname of the terminal as specified by the ttyname() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 shall be written in the following format:

"%s\n", <terminal name>

Otherwise, a message shall be written indicating that standard input is not connected to a terminal. In the POSIX locale, the tty utility shall use the format:

"not a tty\n"

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Standard input is a terminal.
1
Standard input is not a terminal.
>1
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

This utility checks the status of the file open as standard input against that of an implementation-defined set of files. It is possible that no match can be found, or that the match found need not be the same file as that which was opened for standard input (although they are the same device).

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, isatty(), ttyname()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


val(1p)

VAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

val - validate SCCS files (DEVELOPMENT)

SYNOPSIS

val -

val [-s][-m name][-r SID][-y type] file...

DESCRIPTION

The val utility shall determine whether the specified file is an SCCS file meeting the characteristics specified by the options.

OPTIONS

The val utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the usage of the '-' operand is not strictly as intended by the guidelines (that is, reading options and operands from standard input).

The following options shall be supported:

-m name
Specify a name, which is compared with the SCCS %M% keyword in file; see get .
-r SID
Specify a SID (SCCS Identification String), an SCCS delta number. A check shall be made to determine whether the SID is ambiguous (for example, -r 1 is ambiguous because it physically does not exist but implies 1.1, 1.2, and so on, which may exist) or invalid (for example, -r 1.0 or -r 1.1.0 are invalid because neither case can exist as a valid delta number). If the SID is valid and not ambiguous, a check shall be made to determine whether it actually exists.
-s
Silence the diagnostic message normally written to standard output for any error that is detected while processing each named file on a given command line.
-y type
Specify a type, which shall be compared with the SCCS %Y% keyword in file; see get .

OPERANDS

The following operands shall be supported:

file
A pathname of an existing SCCS file. If exactly one file operand appears, and it is '-' , the standard input shall be read: each line shall be independently processed as if it were a command line argument list. (However, the line is not subjected to any of the shell word expansions, such as parameter expansion or quote removal.)

STDIN

The standard input shall be a text file used only when the file operand is specified as '-' .

INPUT FILES

Any SCCS files processed shall be files of an unspecified format.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of val:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error, and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall consist of informative messages about either:

1.
Each file processed

2.
Each command line read from standard input

If the standard input is not used, for each file operand yielding a discrepancy, the output line shall have the following format:

"%s: %s\n", <pathname>, <unspecified string>

If standard input is used, a line of input shall be written before each of the preceding lines for files containing discrepancies:

"%s:\n", <input line>

STDERR

Not used.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The 8-bit code returned by val shall be a disjunction of the possible errors; that is, it can be interpreted as a bit string where set bits are interpreted as follows:
0x80 | Missing file argument.
0x40 | Unknown or duplicate option.
0x20 | Corrupted SCCS file.
0x10 | Cannot open file or file not SCCS.
0x08 | SID is invalid or ambiguous.
0x04 | SID does not exist.
0x02 | %Y%, -y mismatch.
0x01 | %M%, -m mismatch.

Note that val can process two or more files on a given command line and can process multiple command lines (when reading the standard input). In these cases an aggregate code shall be returned: a logical OR of the codes generated for each command line and file processed.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since the val exit status sets the 0x80 bit, shell applications checking "$?" cannot tell if it terminated due to a missing file argument or receipt of a signal.

EXAMPLES

In a directory with three SCCS files- s.x (of t type "text"), s.y, and s.z (a corrupted file)-the following command could produce the output shown:

val - <<EOF
-y source s.x
-m y s.y
s.z
EOF

-y source s.x

    s.x: %Y%, -y mismatch
s.z

    s.z: corrupted SCCS file

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

admin , delta , get , prs

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


unlink(1p)

UNLINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unlink - call the unlink function

SYNOPSIS

unlink file

DESCRIPTION

The unlink utility shall perform the function call:

unlink(file);

A user may need appropriate privilege to invoke the unlink utility.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

file
The pathname of an existing file.

STDIN

Not used.

INPUT FILES

Not used.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of unlink:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES

Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

link() , rm , the System Interfaces volume of IEEE Std 1003.1-2001, unlink()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uux(1p)

UUX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uux - remote command execution

SYNOPSIS

uux [-np] command-string

uux [-jnp] command-string

DESCRIPTION

The uux utility shall gather zero or more files from various systems, execute a shell pipeline (see Shell Commands ) on a specified system, and then send the standard output of the command to a file on a specified system. Only the first command of a pipeline can have a system-name! prefix. All other commands in the pipeline shall be executed on the system of the first command.

The following restrictions are applicable to the shell pipeline processed by uux:

*
In gathering files from different systems, pathname expansion shall not be performed by uux. Thus, a request such as:

uux "c99 remsys!~/*.c"

would attempt to copy the file named literally *.c to the local system.

*
The redirection operators ">>" , "<<" , ">|" , and ">&" shall not be accepted. Any use of these redirection operators shall cause this utility to write an error message describing the problem and exit with a non-zero exit status.

*
The reserved word ! cannot be used at the head of the pipeline to modify the exit status. (See the command-string operand description below.)

*
Alias substitution shall not be performed.

A filename can be specified as for uucp; it can be an absolute pathname, a pathname preceded by ~ name (which is replaced by the corresponding login directory), a pathname specified as ~/ dest ( dest is prefixed by the public directory called PUBDIR; the actual location of PUBDIR is implementation-defined), or a simple filename (which is prefixed by uux with the current directory). See uucp for the details.

The execution of commands on remote systems shall take place in an execution directory known to the uucp system. All files required for the execution shall be put into this directory unless they already reside on that machine. Therefore, the application shall ensure that non-local filenames (without path or machine reference) are unique within the uux request.

The uux utility shall attempt to get all files to the execution system. For files that are output files, the application shall ensure that the filename is escaped using parentheses.

The remote system shall notify the user by mail if the requested command on the remote system was disallowed or the files were not accessible. This notification can be turned off by the -n option.

Typical implementations of this utility require a communications line configured to use the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, but other communications means may be used. On systems where there are no available communications means (either temporarily or permanently), this utility shall write an error message describing the problem and exit with a non-zero exit status.

The uux utility cannot guarantee support for all character encodings in all circumstances. For example, transmission data may be restricted to 7 bits by the underlying network, 8-bit data and filenames need not be portable to non-internationalized systems, and so on. Under these circumstances, it is recommended that only characters defined in the ISO/IEC 646:1991 standard International Reference Version (equivalent to ASCII) 7-bit range of characters be used and that only characters defined in the portable filename character set be used for naming files.

OPTIONS

The uux utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-p
Make the standard input to uux the standard input to the command-string.
-j
Write the job identification string to standard output. This job identification can be used by uustat to obtain the status or terminate a job.
-n
Do not notify the user if the command fails.

OPERANDS

The following operand shall be supported:

command-string

A string made up of one or more arguments that are similar to normal command arguments, except that the command and any filenames can be prefixed by system-name!. A null system-name shall be interpreted as the local system.

STDIN

The standard input shall not be used unless the '-' or -p option is specified; in those cases, the standard input shall be made the standard input of the command-string.

INPUT FILES

Input files shall be selected according to the contents of command-string.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uux:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall not be used unless the -j option is specified; in that case, the job identification string shall be written to standard output in the following format:

"%s\n", <jobid>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

Output files shall be created or written, or both, according to the contents of command-string.

If -n is not used, mail files shall be modified following any command or file-access failures on the remote system.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Note that, for security reasons, many installations limit the list of commands executable on behalf of an incoming request from uux. Many sites permit little more than the receipt of mail via uux.

Any characters special to the command interpreter should be quoted either by quoting the entire command-string or quoting the special characters as individual arguments.

As noted in uucp, shell pattern matching notation characters appearing in pathnames are expanded on the appropriate local system. This is done under the control of local settings of LC_COLLATE and LC_CTYPE . Thus, care should be taken when using bracketed filename patterns, as collation and typing rules may vary from one system to another. Also be aware that certain types of expression (that is, equivalence classes, character classes, and collating symbols) need not be supported on non-internationalized systems.

EXAMPLES

1.
The following command gets file1 from system a and file2 from system b, executes diff on the local system, and puts the results in file.diff in the local PUBDIR directory. ( PUBDIR is the uucp public directory on the local system.)

uux "!diff a!/usr/file1 b!/a4/file2 >!~/file.diff"

2.
The following command fails because uux places all files copied to a system in the same working directory. Although the files xyz are from two different systems, their filenames are the same and conflict.

uux "!diff a!/usr1/xyz b!/usr2/xyz >!~/xyz.diff"

3.
The following command succeeds (assuming diff is permitted on system a) because the file local to system a is not copied to the working directory, and hence does not conflict with the file from system c.

uux "a!diff a!/usr/xyz c!/usr/xyz >!~/xyz.diff"

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , uucp , uuencode , uustat

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


who(1p)

WHO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

who - display who is on the system

SYNOPSIS

who [-mTu]

who [-mu]-s[-bHlprt][file]

who [-mTu][-abdHlprt][file]

who -q [file]

who am i

who am I

DESCRIPTION

The who utility shall list various pieces of information about accessible users. The domain of accessibility is implementation-defined.

Based on the options given, who can also list the user's name, terminal line, login time, elapsed time since activity occurred on the line, and the process ID of the command interpreter for each current system user.

OPTIONS

The who utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported. The metavariables, such as <line>, refer to fields described in the STDOUT section.

-a
Process the implementation-defined database or named file with the -b, -d, -l, -p, -r, -t, -T and -u options turned on.
-b
Write the time and date of the last reboot.
-d
Write a list of all processes that have expired and not been respawned by the init system process. The <exit> field shall appear for dead processes and contain the termination and exit values of the dead process. This can be useful in determining why a process terminated.
-H
Write column headings above the regular output.
-l
(The letter ell.) List only those lines on which the system is waiting for someone to login. The <name> field shall be LOGIN in such cases. Other fields shall be the same as for user entries except that the <state> field does not exist.
-m
Output only information about the current terminal.
-p
List any other process that is currently active and has been previously spawned by init.
-q
(Quick.) List only the names and the number of users currently logged on. When this option is used, all other options shall be ignored.
-r
Write the current run-level of the init process.
-s
List only the <name>, <line>, and <time> fields. This is the default case.
-t
Indicate the last change to the system clock.
-T
Show the state of each terminal, as described in the STDOUT section.
-u
Write "idle time" for each displayed user in addition to any other information. The idle time is the time since any activity occurred on the user's terminal. The method of determining this is unspecified. This option shall list only those users who are currently logged in. The <name> is the user's login name. The <line> is the name of the line as found in the directory /dev. The <time> is the time that the user logged in. The <activity> is the number of hours and minutes since activity last occurred on that particular line. A dot indicates that the terminal has seen activity in the last minute and is therefore "current". If more than twenty-four hours have elapsed or the line has not been used since boot time, the entry shall be marked <old>. This field is useful when trying to determine whether a person is working at the terminal or not. The <pid> is the process ID of the user's login process.

OPERANDS

The following operands shall be supported:

am i, am I
In the POSIX locale, limit the output to describing the invoking user, equivalent to the -m option. The am and i or I must be separate arguments.
file
Specify a pathname of a file to substitute for the implementation-defined database of logged-on users that who uses by default.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of who:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_TIME
Determine the locale used for the format and contents of the date and time strings.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone used when writing date and time information. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The who utility shall write its default format to the standard output in an implementation-defined format, subject only to the requirement of containing the information described above.

XSI-conformant systems shall write the default information to the standard output in the following general format:

<name>[<state>]<line><time>[<activity>][<pid>][<comment>][<exit>]

The following format shall be used for the -T option:

"%s %c %s %s\n" <name>, <terminal state>, <terminal name>,
    <time of login>

where <terminal state> is one of the following characters:

+
The terminal allows write access to other users.
-
The terminal denies write access to other users.
?
The terminal write-access state cannot be determined.

In the POSIX locale, the <time of login> shall be equivalent in format to the output of:

date +"%b %e %H:%M"

If the -u option is used with -T, the idle time shall be added to the end of the previous format in an unspecified format.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The name init used for the system process is the most commonly used on historical systems, but it may vary.

The "domain of accessibility" referred to is a broad concept that permits interpretation either on a very secure basis or even to allow a network-wide implementation like the historical rwho.

EXAMPLES

None.

RATIONALE

Due to differences between historical implementations, the base options provided were a compromise to allow users to work with those functions. The standard developers also considered removing all the options, but felt that these options offered users valuable functionality. Additional options to match historical systems are available on XSI-conformant systems.

It is recognized that the who command may be of limited usefulness, especially in a multi-level secure environment. The standard developers considered, however, that having some standard method of determining the "accessibility" of other users would aid user portability.

No format was specified for the default who output for systems not supporting the XSI Extension. In such a user-oriented command, designed only for human use, this was not considered to be a deficiency.

The format of the terminal name is unspecified, but the descriptions of ps, talk, and write require that they use the same format.

It is acceptable for an implementation to produce no output for an invocation of who mil.

FUTURE DIRECTIONS

None.

SEE ALSO

mesg

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uucp(1p)

UUCP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uucp - system-to-system copy

SYNOPSIS

uucp [-cCdfjmr][-n user] source-file... destination-file

DESCRIPTION

The uucp utility shall copy files named by the source-file argument to the destination-file argument. The files named can be on local or remote systems.

The uucp utility cannot guarantee support for all character encodings in all circumstances. For example, transmission data may be restricted to 7 bits by the underlying network, 8-bit data and filenames need not be portable to non-internationalized systems, and so on. Under these circumstances, it is recommended that only characters defined in the ISO/IEC 646:1991 standard International Reference Version (equivalent to ASCII) 7-bit range of characters be used, and that only characters defined in the portable filename character set be used for naming files. The protocol for transfer of files is unspecified by IEEE Std 1003.1-2001.

Typical implementations of this utility require a communications line configured to use the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, but other communications means may be used. On systems where there are no available communications means (either temporarily or permanently), this utility shall write an error message describing the problem and exit with a non-zero exit status.

OPTIONS

The uucp utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-c
Do not copy local file to the spool directory for transfer to the remote machine (default).
-C
Force the copy of local files to the spool directory for transfer.
-d
Make all necessary directories for the file copy (default).
-f
Do not make intermediate directories for the file copy.
-j
Write the job identification string to standard output. This job identification can be used by uustat to obtain the status or terminate a job.
-m
Send mail to the requester when the copy is completed.
-n user
Notify user on the remote system that a file was sent.
-r
Do not start the file transfer; just queue the job.

OPERANDS

The following operands shall be supported:

destination-file, source-file

A pathname of a file to be copied to, or from, respectively. Either name can be a pathname on the local machine, or can have the form:

system-name!pathname

where system-name is taken from a list of system names that uucp knows about. The destination system-name can also be a list of names such as:

system-name!system-name!...!system-name!pathname

in which case, an attempt is made to send the file via the specified route to the destination. Care should be taken to ensure that intermediate nodes in the route are willing to forward information.

The shell pattern matching notation characters '?' , '*' , and "[...]" appearing in pathname shall be expanded on the appropriate system.

Pathnames can be one of:

1.
An absolute pathname.

2.
A pathname preceded by ~ user where user is a login name on the specified system and is replaced by that user's login directory. Note that if an invalid login is specified, the default is to the public directory (called PUBDIR; the actual location of PUBDIR is implementation-defined).

3.
A pathname preceded by ~/ destination where destination is appended to PUBDIR.
Note:
This destination is treated as a filename unless more than one file is being transferred by this request or the destination is already a directory. To ensure that it is a directory, follow the destination with a '/' . For example, ~/dan/ as the destination makes the directory PUBDIR/dan if it does not exist and puts the requested files in that directory.

4.
Anything else shall be prefixed by the current directory.

If the result is an erroneous pathname for the remote system, the copy shall fail. If the destination-file is a directory, the last part of the source-file name shall be used.

The read, write, and execute permissions given by uucp are implementation-defined.

STDIN

Not used.

INPUT FILES

The files to be copied are regular files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of uucp:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within bracketed filename patterns.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files) and the behavior of character classes within bracketed filename patterns (for example, "'[[:lower:]]*'" ).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error, and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output files (which may be on other systems) are copies of the input files.

If -m is used, mail files are modified.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The domain of remotely accessible files can (and for obvious security reasons usually should) be severely restricted.

Note that the '!' character in addresses has to be escaped when using csh as a command interpreter because of its history substitution syntax. For ksh and sh the escape is not necessary, but may be used.

As noted above, shell metacharacters appearing in pathnames are expanded on the appropriate system. On an internationalized system, this is done under the control of local settings of LC_COLLATE and LC_CTYPE . Thus, care should be taken when using bracketed filename patterns, as collation and typing rules may vary from one system to another. Also be aware that certain types of expression (that is, equivalence classes, character classes, and collating symbols) need not be supported on non-internationalized systems.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mailx , uuencode , uustat , uux

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mkdir(1p)

MKDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mkdir - make directories

SYNOPSIS

mkdir [-p][-m mode] dir...

DESCRIPTION

The mkdir utility shall create the directories specified by the operands, in the order specified.

For each dir operand, the mkdir utility shall perform actions equivalent to the mkdir() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:

1.
The dir operand is used as the path argument.

2.
The value of the bitwise-inclusive OR of S_IRWXU, S_IRWXG, and S_IRWXO is used as the mode argument. (If the -m option is specified, the mode option-argument overrides this default.)

OPTIONS

The mkdir utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-m mode
Set the file permission bits of the newly-created directory to the specified mode value. The mode option-argument shall be the same as the mode operand defined for the chmod utility. In the symbolic_mode strings, the op characters '+' and '-' shall be interpreted relative to an assumed initial mode of a= rwx; '+' shall add permissions to the default mode, '-' shall delete permissions from the default mode.
-p
Create any missing intermediate pathname components.

For each dir operand that does not name an existing directory, effects equivalent to those caused by the following command shall occur:

mkdir -p -m $(umask -S),u+wx $(dirname dir) &&
mkdir [-m mode] dir

where the -m mode option represents that option supplied to the original invocation of mkdir, if any.

Each dir operand that names an existing directory shall be ignored without error.

OPERANDS

The following operand shall be supported:

dir
A pathname of a directory to be created.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of mkdir:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All the specified directories were created successfully or the -p option was specified and all the specified directories now exist.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The default file mode for directories is a= rwx (777 on most systems) with selected permissions removed in accordance with the file mode creation mask. For intermediate pathname components created by mkdir, the mode is the default modified by u+ wx so that the subdirectories can always be created regardless of the file mode creation mask; if different ultimate permissions are desired for the intermediate directories, they can be changed afterwards with chmod.

Note that some of the requested directories may have been created even if an error occurs.

EXAMPLES

None.

RATIONALE

The System V -m option was included to control the file mode.

The System V -p option was included to create any needed intermediate directories and to complement the functionality provided by rmdir for removing directories in the path prefix as they become empty. Because no error is produced if any path component already exists, the -p option is also useful to ensure that a particular directory exists.

The functionality of mkdir is described substantially through a reference to the mkdir() function in the System Interfaces volume of IEEE Std 1003.1-2001. For example, by default, the mode of the directory is affected by the file mode creation mask in accordance with the specified behavior of the mkdir() function. In this way, there is less duplication of effort required for describing details of the directory creation.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , rm , rmdir() , umask() , the System Interfaces volume of IEEE Std 1003.1-2001, mkdir()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


command(1p)

COMMAND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

command - execute a simple command

SYNOPSIS

command [-p] command_name [argument ...]

command [ -v | -V ] command_name

DESCRIPTION

The command utility shall cause the shell to treat the arguments as a simple command, suppressing the shell function lookup that is described in Command Search and Execution , item 1b.

If the command_name is the same as the name of one of the special built-in utilities, the special properties in the enumerated list at the beginning of Special Built-In Utilities shall not occur. In every other respect, if command_name is not the name of a function, the effect of command (with no options) shall be the same as omitting command.

On systems supporting the User Portability Utilities option, the command utility also shall provide information concerning how a command name is interpreted by the shell; see -v and -V.

OPTIONS

The command utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-p
Perform the command search using a default value for PATH that is guaranteed to find all of the standard utilities.
-v
(On systems supporting the User Portability Utilities option.) Write a string to standard output that indicates the pathname or command that will be used by the shell, in the current shell execution environment (see Shell Execution Environment ), to invoke command_name, but do not invoke command_name.
*
Utilities, regular built-in utilities, command_names including a slash character, and any implementation-defined functions that are found using the PATH variable (as described in Command Search and Execution ), shall be written as absolute pathnames.

*
Shell functions, special built-in utilities, regular built-in utilities not associated with a PATH search, and shell reserved words shall be written as just their names.

*
An alias shall be written as a command line that represents its alias definition.

*
Otherwise, no output shall be written and the exit status shall reflect that the name was not found.

-V
(On systems supporting the User Portability Utilities option.) Write a string to standard output that indicates how the name given in the command_name operand will be interpreted by the shell, in the current shell execution environment (see Shell Execution Environment ), but do not invoke command_name. Although the format of this string is unspecified, it shall indicate in which of the following categories command_name falls and shall include the information stated:
*
Utilities, regular built-in utilities, and any implementation-defined functions that are found using the PATH variable (as described in Command Search and Execution ), shall be identified as such and include the absolute pathname in the string.

*
Other shell functions shall be identified as functions.

*
Aliases shall be identified as aliases and their definitions included in the string.

*
Special built-in utilities shall be identified as special built-in utilities.

*
Regular built-in utilities not associated with a PATH search shall be identified as regular built-in utilities. (The term "regular" need not be used.)

*
Shell reserved words shall be identified as reserved words.

OPERANDS

The following operands shall be supported:

argument
One of the strings treated as an argument to command_name.
command_name

The name of a utility or a special built-in utility.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of command:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the search path used during the command search described in Command Search and Execution , except as described under the -p option.

ASYNCHRONOUS EVENTS

Default.

STDOUT

When the -v option is specified, standard output shall be formatted as:

"%s\n", <pathname or command>

When the -V option is specified, standard output shall be formatted as:

"%s\n", <unspecified>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

When the -v or -V options are specified, the following exit values shall be returned:

0
Successful completion.
>0
The command_name could not be found or an error occurred.

Otherwise, the following exit values shall be returned:

126
The utility specified by command_name was found but could not be invoked.
127
An error occurred in the command utility or the utility specified by command_name could not be found.

Otherwise, the exit status of command shall be that of the simple command specified by the arguments to command.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The order for command search allows functions to override regular built-ins and path searches. This utility is necessary to allow functions that have the same name as a utility to call the utility (instead of a recursive call to the function).

The system default path is available using getconf; however, since getconf may need to have the PATH set up before it can be called itself, the following can be used:

command -p getconf _CS_PATH

There are some advantages to suppressing the special characteristics of special built-ins on occasion. For example:

command exec > unwritable-file

does not cause a non-interactive script to abort, so that the output status can be checked by the script.

The command, env, nohup, time, and xargs utilities have been specified to use exit code 127 if an error occurs so that applications can distinguish "failure to find a utility" from "invoked utility exited with an error indication". The value 127 was chosen because it is not commonly used for other meanings; most utilities use small values for "normal error conditions" and the values above 128 can be confused with termination due to receipt of a signal. The value 126 was chosen in a similar manner to indicate that the utility could be found, but not invoked. Some scripts produce meaningful error messages differentiating the 126 and 127 cases. The distinction between exit codes 126 and 127 is based on KornShell practice that uses 127 when all attempts to exec the utility fail with [ENOENT], and uses 126 when any attempt to exec the utility fails for any other reason.

Since the -v and -V options of command produce output in relation to the current shell execution environment, command is generally provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:

(PATH=foo command -v)
 nohup command -v

it does not necessarily produce correct results. For example, when called with nohup or an exec function, in a separate utility execution environment, most implementations are not able to identify aliases, functions, or special built-ins.

Two types of regular built-ins could be encountered on a system and these are described separately by command. The description of command search in Command Search and Execution allows for a standard utility to be implemented as a regular built-in as long as it is found in the appropriate place in a PATH search. So, for example, command -v true might yield /bin/true or some similar pathname. Other implementation-defined utilities that are not defined by this volume of IEEE Std 1003.1-2001 might exist only as built-ins and have no pathname associated with them. These produce output identified as (regular) built-ins. Applications encountering these are not able to count on execing them, using them with nohup, overriding them with a different PATH , and so on.

EXAMPLES

1.
Make a version of cd that always prints out the new working directory exactly once:

cd() {
    command cd "$@" >/dev/null
    pwd
}

2.
Start off a "secure shell script" in which the script avoids being spoofed by its parent:

IFS='
#    The preceding value should be <space><tab><newline>.
#    Set IFS to its default value.

\unalias -a
#    Unset all possible aliases.
#    Note that unalias is escaped to prevent an alias
#    being used for unalias.

unset -f command
#    Ensure command is not a user function.

PATH="$(command -p getconf _CS_PATH):$PATH"
#    Put on a reliable PATH prefix.

#    ...

At this point, given correct permissions on the directories called by PATH , the script has the ability to ensure that any utility it calls is the intended one. It is being very cautious because it assumes that implementation extensions may be present that would allow user functions to exist when it is invoked; this capability is not specified by this volume of IEEE Std 1003.1-2001, but it is not prohibited as an extension. For example, the ENV variable precedes the invocation of the script with a user start-up script. Such a script could define functions to spoof the application.

RATIONALE

Since command is a regular built-in utility it is always found prior to the PATH search.

There is nothing in the description of command that implies the command line is parsed any differently from that of any other simple command. For example:

command a | b ; c

is not parsed in any special way that causes '|' or ';' to be treated other than a pipe operator or semicolon or that prevents function lookup on b or c.

The command utility is somewhat similar to the Eighth Edition shell builtin command, but since command also goes to the file system to search for utilities, the name builtin would not be intuitive.

The command utility is most likely to be provided as a regular built-in. It is not listed as a special built-in for the following reasons:

*
The removal of exportable functions made the special precedence of a special built-in unnecessary.

*
A special built-in has special properties (see Special Built-In Utilities ) that were inappropriate for invoking other utilities. For example, two commands such as:

date > unwritable-file

command date > unwritable-file

would have entirely different results; in a non-interactive script, the former would continue to execute the next command, the latter would abort. Introducing this semantic difference along with suppressing functions was seen to be non-intuitive.

The -p option is present because it is useful to be able to ensure a safe path search that finds all the standard utilities. This search might not be identical to the one that occurs through one of the exec functions (as defined in the System Interfaces volume of IEEE Std 1003.1-2001) when PATH is unset. At the very least, this feature is required to allow the script to access the correct version of getconf so that the value of the default path can be accurately retrieved.

The command -v and -V options were added to satisfy requirements from users that are currently accomplished by three different historical utilities: type in the System V shell, whence in the KornShell, and which in the C shell. Since there is no historical agreement on how and what to accomplish here, the POSIX command utility was enhanced and the historical utilities were left unmodified. The C shell which merely conducts a path search. The KornShell whence is more elaborate-in addition to the categories required by POSIX, it also reports on tracked aliases, exported aliases, and undefined functions.

The output format of -V was left mostly unspecified because human users are its only audience. Applications should not be written to care about this information; they can use the output of -v to differentiate between various types of commands, but the additional information that may be emitted by the more verbose -V is not needed and should not be arbitrarily constrained in its verbosity or localization for application parsing reasons.

FUTURE DIRECTIONS

None.

SEE ALSO

Command Search and Execution , Shell Execution Environment , Special Built-In Utilities , sh , type , the System Interfaces volume of IEEE Std 1003.1-2001, exec

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wait(1p)

WAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wait - await process completion

SYNOPSIS

wait [pid...]

DESCRIPTION

When an asynchronous list (see Asynchronous Lists ) is started by the shell, the process ID of the last command in each element of the asynchronous list shall become known in the current shell execution environment; see Shell Execution Environment .

If the wait utility is invoked with no operands, it shall wait until all process IDs known to the invoking shell have terminated and exit with a zero exit status.

If one or more pid operands are specified that represent known process IDs, the wait utility shall wait until all of them have terminated. If one or more pid operands are specified that represent unknown process IDs, wait shall treat them as if they were known process IDs that exited with exit status 127. The exit status returned by the wait utility shall be the exit status of the process requested by the last pid operand.

The known process IDs are applicable only for invocations of wait in the current shell execution environment.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

pid
One of the following:
1.
The unsigned decimal integer process ID of a command, for which the utility is to wait for the termination.

2.
A job control job ID (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.203, Job Control Job ID) that identifies a background process group to be waited for. The job control job ID notation is applicable only for invocations of wait in the current shell execution environment; see Shell Execution Environment . The exit status of wait shall be determined by the last command in the pipeline.
Note:
The job control job ID type of pid is only available on systems supporting the User Portability Utilities option.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of wait:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If one or more operands were specified, all of them have terminated or were not known by the invoking shell, and the status of the last operand specified is known, then the exit status of wait shall be the exit status information of the command indicated by the last operand specified. If the process terminated abnormally due to the receipt of a signal, the exit status shall be greater than 128 and shall be distinct from the exit status generated by other signals, but the exact value is unspecified. (See the kill -l option.) Otherwise, the wait utility shall exit with one of the following values:

0
The wait utility was invoked with no operands and all process IDs known by the invoking shell have terminated.
1-126
The wait utility detected an error.
127
The command identified by the last pid operand specified is unknown.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

On most implementations, wait is a shell built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:

(wait)
nohup wait ...
find . -exec wait ... \;

it returns immediately because there are no known process IDs to wait for in those environments.

Historical implementations of interactive shells have discarded the exit status of terminated background processes before each shell prompt. Therefore, the status of background processes was usually lost unless it terminated while wait was waiting for it. This could be a serious problem when a job that was expected to run for a long time actually terminated quickly with a syntax or initialization error because the exit status returned was usually zero if the requested process ID was not found. This volume of IEEE Std 1003.1-2001 requires the implementation to keep the status of terminated jobs available until the status is requested, so that scripts like:

j1&
p1=$!
j2&
wait $p1
echo Job 1 exited with status $?
wait $!
echo Job 2 exited with status $?

work without losing status on any of the jobs. The shell is allowed to discard the status of any process if it determines that the application cannot get the process ID for that process from the shell. It is also required to remember only {CHILD_MAX} number of processes in this way. Since the only way to get the process ID from the shell is by using the '!' shell parameter, the shell is allowed to discard the status of an asynchronous list if "$!" was not referenced before another asynchronous list was started. (This means that the shell only has to keep the status of the last asynchronous list started if the application did not reference "$!" . If the implementation of the shell is smart enough to determine that a reference to "$!" was not saved anywhere that the application can retrieve it later, it can use this information to trim the list of saved information. Note also that a successful call to wait with no operands discards the exit status of all asynchronous lists.)

If the exit status of wait is greater than 128, there is no way for the application to know if the waited-for process exited with that value or was killed by a signal. Since most utilities exit with small values, there is seldom any ambiguity. Even in the ambiguous cases, most applications just need to know that the asynchronous job failed; it does not matter whether it detected an error and failed or was killed and did not complete its job normally.

EXAMPLES

Although the exact value used when a process is terminated by a signal is unspecified, if it is known that a signal terminated a process, a script can still reliably determine which signal by using kill as shown by the following script:

sleep 1000&
pid=$!
kill -kill $pid
wait $pid
echo $pid was terminated by a SIG$(kill -l $?) signal.

If the following sequence of commands is run in less than 31 seconds:

sleep 257 | sleep 31 &
jobs -l %%

either of the following commands returns the exit status of the second sleep in the pipeline:

wait <pid of sleep 31>wait %%

RATIONALE

The description of wait does not refer to the waitpid() function from the System Interfaces volume of IEEE Std 1003.1-2001 because that would needlessly overspecify this interface. However, the wording means that wait is required to wait for an explicit process when it is given an argument so that the status information of other processes is not consumed. Historical implementations use the wait() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 until wait() returns the requested process ID or finds that the requested process does not exist. Because this means that a shell script could not reliably get the status of all background children if a second background job was ever started before the first job finished, it is recommended that the wait utility use a method such as the functionality provided by the waitpid() function.

The ability to wait for multiple pid operands was adopted from the KornShell.

This new functionality was added because it is needed to determine the exit status of any asynchronous list accurately. The only compatibility problem that this change creates is for a script like

while sleep 60 do
    job& echo Job started $(date) as $!  done

which causes the shell to monitor all of the jobs started until the script terminates or runs out of memory. This would not be a problem if the loop did not reference "$!" or if the script would occasionally wait for jobs it started.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , kill() , sh , the System Interfaces volume of IEEE Std 1003.1-2001, wait(), waitpid()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


alias(1p)

ALIAS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

alias - define or display aliases

SYNOPSIS

alias [alias-name[=string] ...]

DESCRIPTION

The alias utility shall create or redefine alias definitions or write the values of existing alias definitions to standard output. An alias definition provides a string value that shall replace a command name when it is encountered; see Alias Substitution .

An alias definition shall affect the current shell execution environment and the execution environments of the subshells of the current shell. When used as specified by this volume of IEEE Std 1003.1-2001, the alias definition shall not affect the parent process of the current shell nor any utility environment invoked by the shell; see Shell Execution Environment .

OPTIONS

None.

OPERANDS

The following operands shall be supported:

alias-name
Write the alias definition to standard output.
alias-name=string

Assign the value of string to the alias alias-name.

If no operands are given, all alias definitions shall be written to standard output.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of alias:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The format for displaying aliases (when no operands or only name operands are specified) shall be:

"%s=%s\n", name, value

The value string shall be written with appropriate quoting so that it is suitable for reinput to the shell. See the description of shell quoting in Quoting .

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
One of the name operands specified did not have an alias definition, or an error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

1.
Change ls to give a columnated, more annotated output:

alias ls="ls -CF"

2.
Create a simple "redo" command to repeat previous entries in the command history file:

alias r='fc -s'

3.
Use 1K units for du:

alias du=du\ -k

4.
Set up nohup so that it can deal with an argument that is itself an alias name:

alias nohup="nohup "

RATIONALE

The alias description is based on historical KornShell implementations. Known differences exist between that and the C shell. The KornShell version was adopted to be consistent with all the other KornShell features in this volume of IEEE Std 1003.1-2001, such as command line editing.

Since alias affects the current shell execution environment, it is generally provided as a shell regular built-in.

Historical versions of the KornShell have allowed aliases to be exported to scripts that are invoked by the same shell. This is triggered by the alias -x flag; it is allowed by this volume of IEEE Std 1003.1-2001 only when an explicit extension such as -x is used. The standard developers considered that aliases were of use primarily to interactive users and that they should normally not affect shell scripts called by those users; functions are available to such scripts.

Historical versions of the KornShell had not written aliases in a quoted manner suitable for reentry to the shell, but this volume of IEEE Std 1003.1-2001 has made this a requirement for all similar output. Therefore, consistency with this volume of IEEE Std 1003.1-2001 was chosen over this detail of historical practice.

FUTURE DIRECTIONS

None.

SEE ALSO

Function Definition Command

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qselect(1p)

QSELECT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qselect - select batch jobs

SYNOPSIS

qselect [-a [op]date_time][-A account_string][-c [op]interval]
[-h hold_list][-l resource_list][-N name][-p [op]priority]
[-q destination][-r y|n][-s states][-u user_list]

DESCRIPTION

To select a set of batch jobs is to return the batch job_identifiers for each batch job that meets a list of selection criteria. A set of batch jobs is selected by a request to a batch server. The qselect utility is a user-accessible batch client that requests the selection of batch jobs.

Upon successful completion, the qselect utility shall have returned a list of zero or more batch job_identifiers that meet the criteria specified by the options and option-arguments presented to the utility.

The qselect utility shall select batch jobs by sending a Select Jobs Request to a batch server. The qselect utility shall not exit until the server replies to each request generated.

For each option presented to the qselect utility, the utility shall restrict the set of selected batch jobs as described in the OPTIONS section.

The qselect utility shall not restrict selection of batch jobs except by authorization and as required by the options presented to the utility.

When an option is specified with a mandatory or optional op component to the option-argument, then op shall specify a relation between the value of a certain batch job attribute and the value component of the option-argument. If an op is allowable on an option, then the description of the option letter indicates the op as either mandatory or optional. Acceptable strings for the op component, and the relation the string indicates, are shown in the following list:

.eq.
The value represented by the attribute of the batch job is equal to the value represented by the option-argument.
.ge.
The value represented by the attribute of the batch job is greater than or equal to the value represented by the option-argument.
.gt.
The value represented by the attribute of the batch job is greater than the value represented by the option-argument.
.lt.
The value represented by the attribute of the batch job is less than the value represented by the option-argument.
.le.
The value represented by the attribute of the batch job is less than or equal to the value represented by the option-argument.
.ne.
The value represented by the attribute of the batch job is not equal to the value represented by the option-argument.

OPTIONS

The qselect utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-a [op]date_time

Restrict selection to a specific time, or a range of times.

The qselect utility shall select only batch jobs for which the value of the Execution_Time attribute is related to the Epoch equivalent of the local time expressed by the value of the date_time component of the option-argument in the manner indicated by the value of the op component of the option-argument.

The qselect utility shall accept a date_time component of the option-argument that conforms to the syntax of the time operand of the touch utility.

If the op component of the option-argument is not presented to the qselect utility, the utility shall select batch jobs for which the Execution_Time attribute is equal to the date_time component of the option-argument.

When comparing times, the qselect utility shall use the following definitions for the op component of the option-argument:

.eq.
The time represented by value of the Execution_Time attribute of the batch job is equal to the time represented by the date_time component of the option-argument.
.ge.
The time represented by value of the Execution_Time attribute of the batch job is after or equal to the time represented by the date_time component of the option-argument.
.gt.
The time represented by value of the Execution_Time attribute of the batch job is after the time represented by the date_time component of the option-argument.
.lt.
The time represented by value of the Execution_Time attribute of the batch job is before the time represented by the date_time component of the option-argument.
.le.
The time represented by value of the Execution_Time attribute of the batch job is before or equal to the time represented by the date_time component of the option-argument.
.ne.
The time represented by value of the Execution_Time attribute of the batch job is not equal to the time represented by the date_time component of the option-argument.

The qselect utility shall accept the defined character strings for the op component of the option-argument.

-A account_string

Restrict selection to the batch jobs charging a specified account.

The qselect utility shall select only batch jobs for which the value of the Account_Name attribute of the batch job matchs the value of the account_string option-argument.

The syntax of the account_string option-argument is unspecified.

-c [op]interval

Restrict selection to batch jobs within a range of checkpoint intervals.

The qselect utility shall select only batch jobs for which the value of the Checkpoint attribute relates to the value of the interval component of the option-argument in the manner indicated by the value of the op component of the option-argument.

If the op component of the option-argument is omitted, the qselect utility shall select batch jobs for which the value of the Checkpoint attribute is equal to the value of the interval component of the option-argument.

When comparing checkpoint intervals, the qselect utility shall use the following definitions for the op component of the option-argument:

.eq.
The value of the Checkpoint attribute of the batch job equals the value of the interval component of the option-argument.
.ge.
The value of the Checkpoint attribute of the batch job is greater than or equal to the value of the interval component option-argument.
.gt.
The value of the Checkpoint attribute of the batch job is greater than the value of the interval component option-argument.
.lt.
The value of the Checkpoint attribute of the batch job is less than the value of the interval component option-argument.
.le.
The value of the Checkpoint attribute of the batch job is less than or equal to the value of the interval component option-argument.
.ne.
The value of the Checkpoint attribute of the batch job does not equal the value of the interval component option-argument.

The qselect utility shall accept the defined character strings for the op component of the option-argument.

The ordering relationship for the values of the interval option-argument is defined to be:

`n' .gt. `s' .gt. `c=minutes' .ge. `c'
When comparing Checkpoint attributes with an interval having the value of the single character 'u' , only equality or inequality are valid comparisons.
-h hold_list
Restrict selection to batch jobs that have a specific type of hold.

The qselect utility shall select only batch jobs for which the value of the Hold_Types attribute matches the value of the hold_list option-argument.

The qselect -h option shall accept a value for the hold_list option-argument that is a string of alphanumeric characters in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set).

The qselect utility shall accept a value for the hold_list option-argument that is a string of one or more of the characters 'u' , 's' , or 'o' , or the single character 'n' .

Each unique character in the hold_list option-argument of the qselect utility is defined as follows, each representing a different hold type:

u
USER
s
SYSTEM
o
OPERATOR

If any of these characters are duplicated in the hold_list option-argument, the duplicates shall be ignored.

The qselect utility shall consider it an error if any hold type other than 'n' is combined with hold type 'n' .

Strictly conforming applications shall not repeat any of the characters 'u' , 's' , 'o' , or 'n' within the hold_list option-argument. The qselect utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters.

An implementation may define other hold types. The conformance document for an implementation shall describe any additional hold types, how they are specified, their internal behavior, and how they affect the behavior of the utility.

-l resource_list

Restrict selection to batch jobs with specified resource limits and attributes.

The qselect utility shall accept a resource_list option-argument with the following syntax:

resource_name op value [,,resource_name op value,, ...]

When comparing resource values, the qselect utility shall use the following definitions for the op component of the option-argument:

.eq.
The value of the resource of the same name in the Resource_List attribute of the batch job equals the value of the value component of the option-argument.
.ge.
The value of the resource of the same name in the Resource_List attribute of the batch job is greater than or equal to the value of the value component of the option-argument.
.gt.
The value of the resource of the same name in the Resource_List attribute of the batch job is greater than the value of the value component of the option-argument.
.lt.
The value of the resource of the same name in the Resource_List attribute of the batch job is less than the value of the value component of the option-argument.
.ne.
The value of the resource of the same name in the Resource_List attribute of the batch job does not equal the value of the value component of the option-argument.
.le.
The value of the resource of the same name in the Resource_List attribute of the batch job is less than or equal to the value of the value component of the option-argument.

When comparing the limit of a Resource_List attribute with the value component of the option-argument, if the limit, the value, or both are non-numeric, only equality or inequality are valid comparisons.

The qselect utility shall select only batch jobs for which the values of the resource_names listed in the resource_list option-argument match the corresponding limits of the Resource_List attribute of the batch job.

Limits of resource_names present in the Resource_List attribute of the batch job that have no corresponding values in the resource_list option-argument shall not be considered when selecting batch jobs.

-N name
Restrict selection to batch jobs with a specified name.

The qselect utility shall select only batch jobs for which the value of the Job_Name attribute matches the value of the name option-argument. The string specified in the name option-argument shall be passed, uninterpreted, to the server. This allows an implementation to match "wildcard" patterns against batch job names.

An implementation shall describe in the conformance document the format it supports for matching against the Job_Name attribute.

-p [op]priority

Restrict selection to batch jobs of the specified priority or range of priorities.

The qselect utility shall select only batch jobs for which the value of the Priority attribute of the batch job relates to the value of the priority component of the option-argument in the manner indicated by the value of the op component of the option-argument.

If the op component of the option-argument is omitted, the qselect utility shall select batch jobs for which the value of the Priority attribute of the batch job is equal to the value of the priority component of the option-argument.

When comparing priority values, the qselect utility shall use the following definitions for the op component of the option-argument:

.eq.
The value of the Priority attribute of the batch job equals the value of the priority component of the option-argument.
.ge.
The value of the Priority attribute of the batch job is greater than or equal to the value of the priority component option-argument.
.gt.
The value of the Priority attribute of the batch job is greater than the value of the priority component option-argument.
.lt.
The value of the Priority attribute of the batch job is less than the value of the priority component option-argument.
.lt.
The value of the Priority attribute of the batch job is less than or equal to the value of the priority component option-argument.
.ne.
The value of the Priority attribute of the batch job does not equal the value of the priority component option-argument.

-q destination

Restrict selection to the specified batch queue or server, or both.

The qselect utility shall select only batch jobs that are located at the destination indicated by the value of the destination option-argument.

The destination defines a batch queue, a server, or a batch queue at a server.

The qselect utility shall accept an option-argument for the -q option that conforms to the syntax for a destination. If the -q option is not presented to the qselect utility, the utility shall select batch jobs from all batch queues at the default batch server.

If the option-argument describes only a batch queue, the qselect utility shall select only batch jobs from the batch queue of the specified name at the default batch server. The means by which qselect determines the default server is implementation-defined.

If the option-argument describes only a batch server, the qselect utility shall select batch jobs from all the batch queues at that batch server.

If the option-argument describes both a batch queue and a batch server, the qselect utility shall select only batch jobs from the specified batch queue at the specified server.

-r y|n
Restrict selection to batch jobs with the specified rerunability status.

The qselect utility shall select only batch jobs for which the value of the Rerunable attribute of the batch job matches the value of the option-argument.

The qselect utility shall accept a value for the option-argument that consists of either the single character 'y' or the single character 'n' . The character 'y' represents the value TRUE, and the character 'n' represents the value FALSE.

-s states
Restrict selection to batch jobs in the specified states.

The qselect utility shall accept an option-argument that consists of any combination of the characters 'e' , 'q' , 'r' , 'w' , 'h' , and 't' .

Conforming applications shall not repeat any character in the option-argument. The qselect utility shall permit the repetition of characters in the option-argument, but shall not assign additional meaning to repeated characters.

The qselect utility shall interpret the characters in the states option-argument as follows:

e
Represents the EXITING state.
q
Represents the QUEUED state.
r
Represents the RUNNING state.
t
Represents the TRANSITING state.
h
Represents the HELD state.
w
Represents the WAITING state.

For each character in the states option-argument, the qselect utility shall select batch jobs in the corresponding state.

-u user_list
Restrict selection to batch jobs owned by the specified user names.

The qselect utility shall select only the batch jobs of those users specified in the user_list option-argument.

The qselect utility shall accept a user_list option-argument that conforms to the following syntax:

username[@host][,,username[@host],, ...]

The qselect utility shall accept only one user name that is missing a corresponding host name. The qselect utility shall accept only one user name per named host.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qselect:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.
TZ
Determine the timezone used to interpret the date-time option-argument. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

The qselect utility shall write zero or more batch job_identifiers to standard output.

The qselect utility shall separate the batch job_identifiers written to standard output by white space.

The qselect utility shall write batch job_identifiers in the following format:

sequence_number.server_name@server

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

The following example shows how a user might use the qselect utility in conjunction with the qdel utility to delete all of his or her jobs in the queued state without affecting any jobs that are already running:

qdel $(qselect -s q)

or:

qselect -s q || xargs qdel

RATIONALE

The qselect utility allows users to acquire a list of job identifiers that match user-specified selection criteria. The list of identifiers returned by the qselect utility conforms to the syntax of the batch job identifier list processed by a utility such as qmove, qdel, and qrls. The qselect utility is thus a powerful tool for causing another batch system utility to act upon a set of jobs that match a list of selection criteria.

The options of the qselect utility let the user apply a number of useful filters for selecting jobs. Each option further restricts the selection of jobs. Many of the selection options allow the specification of a relational operator. The FORTRAN-like syntax of the operator-that is, ".lt." - was chosen rather than the C-like "<=" meta-characters.

The -a option allows users to restrict the selected jobs to those that have been submitted (or altered) to wait until a particular time. The time period is determined by the argument of this option, which includes both a time and an operator-it is thus possible to select jobs waiting until a specific time, jobs waiting until after a certain time, or those waiting for a time before the specified time.

The -A option allows users to restrict the selected jobs to those that have been submitted (or altered) to charge a particular account.

The -c option allows users to restrict the selected jobs to those whose checkpointing interval falls within the specified range.

The -l option allows users to select those jobs whose resource limits fall within the range indicated by the value of the option. For example, a user could select those jobs for which the CPU time limit is greater than two hours.

The -N option allows users to select jobs by job name. For instance, all the parts of a task that have been divided in parallel jobs might be given the same name, and thus manipulated as a group by means of this option.

The -q option allows users to select jobs in a specified queue.

The -r option allows users to select only those jobs with a specified rerun criteria. For instance, a user might select only those jobs that can be rerun for use with the qrerun utility.

The -s option allows users to select only those jobs that are in a certain state.

The -u option allows users to select jobs that have been submitted to execute under a particular account.

The selection criteria provided by the options of the qselect utility allow users to select jobs based on all the appropriate attributes that can be assigned to jobs by the qsub utility.

Historically, the qselect utility has not been a part of existing practice; it is an improvement that has been introduced in this volume of IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

qdel , qrerun , qrls , qselect , qsub , touch , Batch Environment Services

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qalter(1p)

QALTER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qalter - alter batch job

SYNOPSIS

qalter [-a date_time][-A account_string][-c interval][-e path_name]
[-h hold_list][-j join_list][-k keep_list][-l resource_list]
[-m mail_options][-M mail_list][-N name][-o path_name]
[-p priority][-r y|n][-S path_name_list][-u user_list]
job_identifier ...

DESCRIPTION

The attributes of a batch job are altered by a request to the batch server that manages the batch job. The qalter utility is a user-accessible batch client that requests the alteration of the attributes of one or more batch jobs.

The qalter utility shall alter the attributes of those batch jobs, and only those batch jobs, for which a batch job_identifier is presented to the utility.

The qalter utility shall alter the attributes of batch jobs in the order in which the batch job_identifiers are presented to the utility.

If the qalter utility fails to process a batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

For each batch job_identifier for which the qalter utility succeeds, each attribute of the identified batch job shall be altered as indicated by all the options presented to the utility.

For each identified batch job for which the qalter utility fails, the utility shall not alter any attribute of the batch job.

For each batch job that the qalter utility processes, the utility shall not modify any attribute other than those required by the options and option-arguments presented to the utility.

The qalter utility shall alter batch jobs by sending a Modify Job Request to the batch server that manages each batch job. At the time the qalter utility exits, it shall have modified the batch job corresponding to each successfully processed batch job_identifier. An attempt to alter the attributes of a batch job in the RUNNING state is implementation-defined.

OPTIONS

The qalter utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported by the implementation:

-a date_time
Redefine the time at which the batch job becomes eligible for execution.

The date_time argument shall be in the same form and represent the same time as for the touch utility. The time so represented shall be set into the Execution_Time attribute of the batch job. If the time specified is earlier than the current time, the -a option shall have no effect.

-A account_string

Redefine the account to which the resource consumption of the batch job should be charged.

The syntax of the account_string option-argument is unspecified.

The qalter utility shall set the Account_Name attribute of the batch job to the value of the account_string option-argument.

-c interval
Redefine whether the batch job should be checkpointed, and if so, how often.

The qalter utility shall accept a value for the interval option-argument that is one of the following:

n
No checkpointing is to be performed on the batch job (NO_CHECKPOINT).
s
Checkpointing is to be performed only when the batch server is shut down (CHECKPOINT_AT_SHUTDOWN).
c
Automatic periodic checkpointing is to be performed at the Minimum_Cpu_Interval attribute of the batch queue, in units of CPU minutes (CHECKPOINT_AT_MIN_CPU_INTERVAL).
c=minutes
Automatic periodic checkpointing is to be performed every minutes of CPU time, or every Minimum_Cpu_Interval minutes, whichever is greater. The minutes argument shall conform to the syntax for unsigned integers and shall be greater than zero.

An implementation may define other checkpoint intervals. The conformance document for an implementation shall describe any alternative checkpoint intervals, how they are specified, their internal behavior, and how they affect the behavior of the utility.

The qalter utility shall set the Checkpoint attribute of the batch job to the value of the interval option-argument.

-e path_name
Redefine the path to be used for the standard error stream of the batch job.

The qalter utility shall accept a path_name option-argument that conforms to the syntax of the path_name element defined in the System Interfaces volume of IEEE Std 1003.1-2001, which can be preceded by a host name element of the form hostname:.

If the path_name option-argument constitutes an absolute pathname, the qalter utility shall set the Error_Path attribute of the batch job to the value of the path_name option-argument, including the host name element, if present.

If the path_name option-argument constitutes a relative pathname and no host name element is specified, the qalter utility shall set the Error_Path attribute of the batch job to the value of the absolute pathname derived by expanding the path_name option-argument relative to the current directory of the process that executes the qalter utility.

If the path_name option-argument constitutes a relative pathname and a host name element is specified, the qalter utility shall set the Error_Path attribute of the batch job to the value of the option-argument without expansion.

If the path_name option-argument does not include a host name element, the qalter utility shall prefix the pathname in the Error_Path attribute with hostname:, where hostname is the name of the host upon which the qalter utility is being executed.

-h hold_list
Redefine the types of holds, if any, on the batch job. The qalter -h option shall accept a value for the hold_list option-argument that is a string of alphanumeric characters in the portable character set.

The qalter utility shall accept a value for the hold_list option-argument that is a string of one or more of the characters 'u' , 's' , or 'o' , or the single character 'n' . For each unique character in the hold_list option-argument, the qalter utility shall add a value to the Hold_Types attribute of the batch job as follows, each representing a different hold type:

u
USER
s
SYSTEM
o
OPERATOR

If any of these characters are duplicated in the hold_list option-argument, the duplicates shall be ignored. An existing Hold_Types attribute can be cleared by the hold type:

n
NO_HOLD

The qalter utility shall consider it an error if any hold type other than 'n' is combined with hold type 'n' . Strictly conforming applications shall not repeat any of the characters 'u' , 's' , 'o' , or 'n' within the hold_list option-argument. The qalter utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters. An implementation may define other hold types. The conformance document for an implementation shall describe any additional hold types, how they are specified, their internal behavior, and how they affect the behavior of the utility.

-j join_list
Redefine which streams of the batch job are to be merged. The qalter -j option shall accept a value for the join_list option-argument that is a string of alphanumeric characters in the portable character set.

The qalter utility shall accept a join_list option-argument that consists of one or more of the characters 'e' and 'o' , or the single character 'n' .

All of the other batch job output streams specified shall be merged into the output stream represented by the character listed first in the join_list option-argument.

For each unique character in the join_list option-argument, the qalter utility shall add a value to the Join_Path attribute of the batch job as follows, each representing a different batch job stream to join:

e
The standard error of the batch job (JOIN_STD_ERROR).
o
The standard output of the batch job (JOIN_STD_OUTPUT).

An existing Join_Path attribute can be cleared by the join type:

n
NO_JOIN

If 'n' is specified, then no files are joined. The qalter utility shall consider it an error if any join type other than 'n' is combined with join type 'n' .

Strictly conforming applications shall not repeat any of the characters 'e' , 'o' , or 'n' within the join_list option-argument. The qalter utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters.

An implementation may define other join types. The conformance document for an implementation shall describe any additional batch job streams, how they are specified, their internal behavior, and how they affect the behavior of the utility.

-k keep_list
Redefine which output of the batch job to retain on the execution host.

The qalter -k option shall accept a value for the keep_list option-argument that is a string of alphanumeric characters in the portable character set.

The qalter utility shall accept a keep_list option-argument that consists of one or more of the characters 'e' and 'o' , or the single character 'n' .

For each unique character in the keep_list option-argument, the qalter utility shall add a value to the Keep_Files attribute of the batch job as follows, each representing a different batch job stream to keep:

e
The standard error of the batch job (KEEP_STD_ERROR).
o
The standard output of the batch job (KEEP_STD_OUTPUT).

If both 'e' and 'o' are specified, then both files are retained. An existing Keep_Files attribute can be cleared by the keep type:

n
NO_KEEP

If 'n' is specified, then no files are retained. The qalter utility shall consider it an error if any keep type other than 'n' is combined with keep type 'n' .

Strictly conforming applications shall not repeat any of the characters 'e' , 'o' , or 'n' within the keep_list option-argument. The qalter utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters. An implementation may define other keep types. The conformance document for an implementation shall describe any additional keep types, how they are specified, their internal behavior, and how they affect the behavior of the utility.

-l resource_list

Redefine the resources that are allowed or required by the batch job.

The qalter utility shall accept a resource_list option-argument that conforms to the following syntax:

resource=value[,,resource=value,,...]

The qalter utility shall set one entry in the value of the Resource_List attribute of the batch job for each resource listed in the resource_list option-argument.

Because the list of supported resource names might vary by batch server, the qalter utility shall rely on the batch server to validate the resource names and associated values. See Multiple Keyword-Value Pairs for a means of removing keyword= value (and value@ keyword) pairs and other general rules for list-oriented batch job attributes.

-m mail_options

Redefine the points in the execution of the batch job at which the batch server is to send mail about a change in the state of the batch job.

The qalter -m option shall accept a value for the mail_options option-argument that is a string of alphanumeric characters in the portable character set.

The qalter utility shall accept a value for the mail_options option-argument that is a string of one or more of the characters 'e' , 'b' , and 'a' , or the single character 'n' . For each unique character in the mail_options option-argument, the qalter utility shall add a value to the Mail_Users attribute of the batch job as follows, each representing a different time during the life of a batch job at which to send mail:

e
MAIL_AT_EXIT
b
MAIL_AT_BEGINNING
a
MAIL_AT_ABORT

If any of these characters are duplicated in the mail_options option-argument, the duplicates shall be ignored.

An existing Mail_Points attribute can be cleared by the mail type:

n
NO_MAIL

If 'n' is specified, then mail is not sent. The qalter utility shall consider it an error if any mail type other than 'n' is combined with mail type 'n' . Strictly conforming applications shall not repeat any of the characters 'e' , 'b' , 'a' , or 'n' within the mail_options option-argument. The qalter utility shall permit the repetition of characters but shall not assign additional meaning to the repeated characters.

An implementation may define other mail types. The conformance document for an implementation shall describe any additional mail types, how they are specified, their internal behavior, and how they affect the behavior of the utility.

-M mail_list
Redefine the list of users to which the batch server that executes the batch job is to send mail, if the batch server sends mail about the batch job.

The syntax of the mail_list option-argument is unspecified. If the implementation of the qalter utility uses a name service to locate users, the utility shall accept the syntax used by the name service.

If the implementation of the qalter utility does not use a name service to locate users, the implementation shall accept the following syntax for user names:

mail_address[,,mail_address,,...]

The interpretation of mail_address is implementation-defined.

The qalter utility shall set the Mail_Users attribute of the batch job to the value of the mail_list option-argument.

-N name
Redefine the name of the batch job.

The qalter -N option shall accept a value for the name option-argument that is a string of up to 15 alphanumeric characters in the portable character set where the first character is alphabetic.

The syntax of the name option-argument is unspecified.

The qalter utility shall set the Job_Name attribute of the batch job to the value of the name option-argument.

-o path_name
Redefine the path for the standard output of the batch job.

The qalter utility shall accept a path_name option-argument that conforms to the syntax of the path_name element defined in the System Interfaces volume of IEEE Std 1003.1-2001, which can be preceded by a host name element of the form hostname:.

If the path_name option-argument constitutes an absolute pathname, the qalter utility shall set the Output_Path attribute of the batch job to the value of the path_name option-argument.

If the path_name option-argument constitutes a relative pathname and no host name element is specified, the qalter utility shall set the Output_Path attribute of the batch job to the absolute pathname derived by expanding the path_name option-argument relative to the current directory of the process that executes the qalter utility.

If the path_name option-argument constitutes a relative pathname and a host name element is specified, the qalter utility shall set the Output_Path attribute of the batch job to the value of the path_name option-argument without any expansion of the pathname.

If the path_name option-argument does not include a host name element, the qalter utility shall prefix the pathname in the Output_Path attribute with hostname:, where hostname is the name of the host upon which the qalter utility is being executed.

-p priority
Redefine the priority of the batch job.

The qalter utility shall accept a value for the priority option-argument that conforms to the syntax for signed decimal integers, and which is not less than -1024 and not greater than 1023.

The qalter utility shall set the Priority attribute of the batch job to the value of the priority option-argument.

-r y|n
Redefine whether the batch job is rerunnable.

If the value of the option-argument is 'y' , the qalter utility shall set the Rerunable attribute of the batch job to TRUE.

If the value of the option-argument is 'n' , the qalter utility shall set the Rerunable attribute of the batch job to FALSE.

The qalter utility shall consider it an error if any character other than 'y' or 'n' is specified in the option-argument.

-S path_name_list

Redefine the shell that interprets the script at the destination system.

The qalter utility shall accept a path_name_list option-argument that conforms to the following syntax:

pathname[@host][,pathname[@host],...]

The qalter utility shall accept only one pathname that is missing a corresponding host name. The qalter utility shall allow only one pathname per named host.

The qalter utility shall add a value to the Shell_Path_List attribute of the batch job for each entry in the path_name_list option-argument. See Multiple Keyword-Value Pairs for a means of removing keyword= value (and value@ keyword) pairs and other general rules for list-oriented batch job attributes.

-u user_list
Redefine the user name under which the batch job is to run at the destination system.

The qalter utility shall accept a user_list option-argument that conforms to the following syntax:

username[@host][,,username[@host],,...]

The qalter utility shall accept only one user name that is missing a corresponding host name. The qalter utility shall accept only one user name per named host.

The qalter utility shall add a value to the User_List attribute of the batch job for each entry in the user_list option-argument. See Multiple Keyword-Value Pairs for a means of removing keyword= value (and value@ keyword) pairs and other general rules for list-oriented batch job attributes.

OPERANDS

The qalter utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qalter:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.
TZ
Determine the timezone used to interpret the date-time option-argument. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qalter utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qalter utility attempts to locate the batch job on other batch servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qalter utility allows users to change the attributes of a batch job.

As a means of altering a queued job, the qalter utility is superior to deleting and requeuing the batch job insofar as an altered job retains its place in the queue with some traditional selection algorithms. In addition, the qalter utility is both shorter and simpler than a sequence of qdel and qsub utilities.

The result of an attempt on the part of a user to alter a batch job in a RUNNING state is implementation-defined because a batch job in the RUNNING state will already have opened its output files and otherwise performed any actions indicated by the options in effect at the time the batch job began execution.

The options processed by the qalter utility are identical to those of the qsub utility, with a few exceptions: -V, -v, and -q. The -V and -v are inappropriate for the qalter utility, since they capture potentially transient environment information from the submitting process. The -q option would specify a new queue, which would largely negate the previously stated advantage of using qalter; furthermore, the qmove utility provides a superior means of moving jobs.

Each of the following paragraphs provides the rationale for a qalter option.

Additional rationale concerning these options can be found in the rationale for the qsub utility.

The -a option allows users to alter the date and time at which a batch job becomes eligible to run.

The -A option allows users to change the account that will be charged for the resources consumed by the batch job. Support for the -A option is mandatory for conforming implementations of qalter, even though support of accounting is optional for servers. Whether or not to support accounting is left to the implementor of the server, but mandatory support of the -A option assures users of a consistent interface and allows them to control accounting on servers that support accounting.

The -c option allows users to alter the checkpointing interval of a batch job. A checkpointing system, which is not defined by IEEE Std 1003.1-2001, allows recovery of a batch job at the most recent checkpoint in the event of a crash. Checkpointing is typically used for jobs that consume expensive computing time or must meet a critical schedule. Users should be allowed to make the tradeoff between the overhead of checkpointing and the risk to the timely completion of the batch job; therefore, this volume of IEEE Std 1003.1-2001 provides the checkpointing interval option. Support for checkpointing is optional for servers.

The -e option allows users to alter the name and location of the standard error stream written by a batch job. However, the path of the standard error stream is meaningless if the value of the Join_Path attribute of the batch job is TRUE.

The -h option allows users to set the hold type in the Hold_Types attribute of a batch job. The qhold and qrls utilities add or remove hold types to the Hold_Types attribute, respectively. The -h option has been modified to allow for implementation-defined hold types.

The -j option allows users to alter the decision to join (merge) the standard error stream of the batch job with the standard output stream of the batch job.

The -l option allows users to change the resource limits imposed on a batch job.

The -m option allows users to modify the list of points in the life of a batch job at which the designated users will receive mail notification.

The -M option allows users to alter the list of users who will receive notification about events in the life of a batch job.

The -N option allows users to change the name of a batch job.

The -o option allows users to alter the name and path to which the standard output stream of the batch job will be written.

The -P option allows users to modify the priority of a batch job. Support for priority is optional for batch servers.

The -r option allows users to alter the rerunability status of a batch job.

The -S option allows users to change the name and location of the shell image that will be invoked to interpret the script of the batch job. This option has been modified to allow a list of shell name and locations associated with different hosts.

The -u option allows users to change the user identifier under which the batch job will execute.

The job_identifier operand syntax is provided so that the user can differentiate between the originating and destination (or executing) batch server. These may or may not be the same. The . server_name portion identifies the originating batch server, while the @ server portion identifies the destination batch server.

Historically, the qalter utility has been a component of the Network Queuing System (NQS), the existing practice from which this utility has been derived.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , qdel , qhold , qmove , qrls , qsub , touch

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dirname(1p)

DIRNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dirname - return the directory portion of a pathname

SYNOPSIS

dirname string

DESCRIPTION

The string operand shall be treated as a pathname, as defined in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.266, Pathname. The string string shall be converted to the name of the directory containing the filename corresponding to the last pathname component in string, performing actions equivalent to the following steps in order:

1.
If string is //, skip steps 2 to 5.

2.
If string consists entirely of slash characters, string shall be set to a single slash character. In this case, skip steps 3 to 8.

3.
If there are any trailing slash characters in string, they shall be removed.

4.
If there are no slash characters remaining in string, string shall be set to a single period character. In this case, skip steps 5 to 8.

5.
If there are any trailing non-slash characters in string, they shall be removed.

6.
If the remaining string is //, it is implementation-defined whether steps 7 and 8 are skipped or processed.

7.
If there are any trailing slash characters in string, they shall be removed.

8.
If the remaining string is empty, string shall be set to a single slash character.

The resulting string shall be written to standard output.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

string
A string.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of dirname:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The dirname utility shall write a line to the standard output in the following format:

"%s\n", <resulting string>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The definition of pathname specifies implementation-defined behavior for pathnames starting with two slash characters. Therefore, applications shall not arbitrarily add slashes to the beginning of a pathname unless they can ensure that there are more or less than two or are prepared to deal with the implementation-defined consequences.

EXAMPLES

Command | Results
dirname / | /
dirname // | / or //
dirname /a/b/ | /a
dirname //a//b// | //a
dirname | Unspecified
dirname a | . ($? = 0)
dirname "" | . ($? = 0)
dirname /a | /
dirname /a/b | /a
dirname a/b | a

RATIONALE

The dirname utility originated in System III. It has evolved through the System V releases to a version that matches the requirements specified in this description in System V Release 3. 4.3 BSD and earlier versions did not include dirname.

The behaviors of basename and dirname in this volume of IEEE Std 1003.1-2001 have been coordinated so that when string is a valid pathname:

$(basename "string")

would be a valid filename for the file in the directory:

$(dirname "string")

This would not work for the versions of these utilities in early proposals due to the way processing of trailing slashes was specified. Consideration was given to leaving processing unspecified if there were trailing slashes, but this cannot be done; the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.266, Pathname allows trailing slashes. The basename and dirname utilities have to specify consistent handling for all valid pathnames.

FUTURE DIRECTIONS

None.

SEE ALSO

basename() , Parameters and Variables

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


touch(1p)

TOUCH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

touch - change file access and modification times

SYNOPSIS

touch [-acm][ -r ref_file| -t time] file...

DESCRIPTION

The touch utility shall change the modification times, access times, or both of files. The modification time shall be equivalent to the value of the st_mtime member of the stat structure for a file, as described in the System Interfaces volume of IEEE Std 1003.1-2001; the access time shall be equivalent to the value of st_atime.

The time used can be specified by the -t time option-argument, the corresponding time fields of the file referenced by the -r ref_file option-argument, or the date_time operand, as specified in the following sections. If none of these are specified, touch shall use the current time (the value returned by the equivalent of the time() function defined in the System Interfaces volume of IEEE Std 1003.1-2001).

For each file operand, touch shall perform actions equivalent to the following functions defined in the System Interfaces volume of IEEE Std 1003.1-2001:

1.
If file does not exist, a creat() function call is made with the file operand used as the path argument and the value of the bitwise-inclusive OR of S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH used as the mode argument.

2.
The utime() function is called with the following arguments:
a.
The file operand is used as the path argument.

b.
The utimbuf structure members actime and modtime are determined as described in the OPTIONS section.

OPTIONS

The touch utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-a
Change the access time of file. Do not change the modification time unless -m is also specified.
-c
Do not create a specified file if it does not exist. Do not write any diagnostic messages concerning this condition.
-m
Change the modification time of file. Do not change the access time unless -a is also specified.
-r ref_file
Use the corresponding time of the file named by the pathname ref_file instead of the current time.
-t time
Use the specified time instead of the current time. The option-argument shall be a decimal number of the form:

[[CC]YY]MMDDhhmm[.SS]

where each two digits represents the following:

MM
The month of the year [01,12].
DD
The day of the month [01,31].
hh
The hour of the day [00,23].
mm
The minute of the hour [00,59].
CC
The first two digits of the year (the century).
YY
The second two digits of the year.
SS
The second of the minute [00,60].

Both CC and YY shall be optional. If neither is given, the current year shall be assumed. If YY is specified, but CC is not, CC shall be derived as follows:
If YY is: | CC becomes:
[69,99] | 19
[00,68] | 20

Note:
It is expected that in a future version of IEEE Std 1003.1-2001 the default century inferred from a 2-digit year will change. (This would apply to all commands accepting a 2-digit year as input.)

The resulting time shall be affected by the value of the TZ environment variable. If the resulting time value precedes the Epoch, touch shall exit immediately with an error status. The range of valid times past the Epoch is implementation-defined, but it shall extend to at least the time 0 hours, 0 minutes, 0 seconds, January 1, 2038, Coordinated Universal Time. Some implementations may not be able to represent dates beyond January 18, 2038, because they use signed int as a time holder.

The range for SS is [00,60] rather than [00,59] because of leap seconds. If SS is 60, and the resulting time, as affected by the TZ environment variable, does not refer to a leap second, the resulting time shall be one second after a time where SS is 59. If SS is not given a value, it is assumed to be zero.

If neither the -a nor -m options were specified, touch shall behave as if both the -a and -m options were specified.

OPERANDS

The following operands shall be supported:

file
A pathname of a file whose times shall be modified.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of touch:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone to be used for interpreting the time option-argument. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The utility executed successfully and all requested changes were made.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The interpretation of time is taken to be seconds since the Epoch (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.14, Seconds Since the Epoch). It should be noted that implementations conforming to the System Interfaces volume of IEEE Std 1003.1-2001 do not take leap seconds into account when computing seconds since the Epoch. When SS=60 is used, the resulting time always refers to 1 plus seconds since the Epoch for a time when SS=59.

Although the -t time option-argument specifies values in 1969, the access time and modification time fields are defined in terms of seconds since the Epoch (00:00:00 on 1 January 1970 UTC). Therefore, depending on the value of TZ when touch is run, there is never more than a few valid hours in 1969 and there need not be any valid times in 1969.

One ambiguous situation occurs if -t time is not specified, -r ref_file is not specified, and the first operand is an eight or ten-digit decimal number. A portable script can avoid this problem by using:

touch -- file

or:

touch ./file

in this case.

EXAMPLES

None.

RATIONALE

The functionality of touch is described almost entirely through references to functions in the System Interfaces volume of IEEE Std 1003.1-2001. In this way, there is no duplication of effort required for describing such side effects as the relationship of user IDs to the user database, permissions, and so on.

There are some significant differences between the touch utility in this volume of IEEE Std 1003.1-2001 and those in System V and BSD systems. They are upwards-compatible for historical applications from both implementations:

1.
In System V, an ambiguity exists when a pathname that is a decimal number leads the operands; it is treated as a time value. In BSD, no time value is allowed; files may only be touched to the current time. The -t time construct solves these problems for future conforming applications (note that the -t option is not historical practice).

2.
The inclusion of the century digits, CC, is also new. Note that a ten-digit time value is treated as if YY, and not CC, were specified. The caveat about the range of dates following the Epoch was included as recognition that some implementations are not able to represent dates beyond 18 January 2038 because they use signed int as a time holder.

The -r option was added because several comments requested this capability. This option was named -f in an early proposal, but was changed because the -f option is used in the BSD version of touch with a different meaning.

At least one historical implementation of touch incremented the exit code if -c was specified and the file did not exist. This volume of IEEE Std 1003.1-2001 requires exit status zero if no errors occur.

FUTURE DIRECTIONS

Applications should use the -r or -t options.

SEE ALSO

date , the System Interfaces volume of IEEE Std 1003.1-2001, creat(), time(), utime(), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getopts(1p)

GETOPTS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getopts - parse utility options

SYNOPSIS

getopts optstring name [arg...]

DESCRIPTION

The getopts utility shall retrieve options and option-arguments from a list of parameters. It shall support the Utility Syntax Guidelines 3 to 10, inclusive, described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

Each time it is invoked, the getopts utility shall place the value of the next option in the shell variable specified by the name operand and the index of the next argument to be processed in the shell variable OPTIND . Whenever the shell is invoked, OPTIND shall be initialized to 1.

When the option requires an option-argument, the getopts utility shall place it in the shell variable OPTARG . If no option was found, or if the option that was found does not have an option-argument, OPTARG shall be unset.

If an option character not contained in the optstring operand is found where an option character is expected, the shell variable specified by name shall be set to the question-mark ( '?' ) character. In this case, if the first character in optstring is a colon ( ':' ), the shell variable OPTARG shall be set to the option character found, but no output shall be written to standard error; otherwise, the shell variable OPTARG shall be unset and a diagnostic message shall be written to standard error. This condition shall be considered to be an error detected in the way arguments were presented to the invoking application, but shall not be an error in getopts processing.

If an option-argument is missing:

*
If the first character of optstring is a colon, the shell variable specified by name shall be set to the colon character and the shell variable OPTARG shall be set to the option character found.

*
Otherwise, the shell variable specified by name shall be set to the question-mark character, the shell variable OPTARG shall be unset, and a diagnostic message shall be written to standard error. This condition shall be considered to be an error detected in the way arguments were presented to the invoking application, but shall not be an error in getopts processing; a diagnostic message shall be written as stated, but the exit status shall be zero.

When the end of options is encountered, the getopts utility shall exit with a return value greater than zero; the shell variable OPTIND shall be set to the index of the first non-option-argument, where the first "--" argument is considered to be an option-argument if there are no other non-option-arguments appearing before it, or the value "$#" +1 if there are no non-option-arguments; the name variable shall be set to the question-mark character. Any of the following shall identify the end of options: the special option "--" , finding an argument that does not begin with a '-' , or encountering an error.

The shell variables OPTIND and OPTARG shall be local to the caller of getopts and shall not be exported by default.

The shell variable specified by the name operand, OPTIND , and OPTARG shall affect the current shell execution environment; see Shell Execution Environment .

If the application sets OPTIND to the value 1, a new set of parameters can be used: either the current positional parameters or new arg values. Any other attempt to invoke getopts multiple times in a single shell execution environment with parameters (positional parameters or arg operands) that are not the same in all invocations, or with an OPTIND value modified to be a value other than 1, produces unspecified results.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

optstring
A string containing the option characters recognized by the utility invoking getopts. If a character is followed by a colon, the option shall be expected to have an argument, which should be supplied as a separate argument. Applications should specify an option character and its option-argument as separate arguments, but getopts shall interpret the characters following an option character requiring arguments as an argument whether or not this is done. An explicit null option-argument need not be recognized if it is not supplied as a separate argument when getopts is invoked. (See also the getopt() function defined in the System Interfaces volume of IEEE Std 1003.1-2001.) The characters question-mark and colon shall not be used as option characters by an application. The use of other option characters that are not alphanumeric produces unspecified results. If the option-argument is not supplied as a separate argument from the option character, the value in OPTARG shall be stripped of the option character and the '-' . The first character in optstring determines how getopts behaves if an option character is not known or an option-argument is missing.
name
The name of a shell variable that shall be set by the getopts utility to the option character that was found.

The getopts utility by default shall parse positional parameters passed to the invoking shell procedure. If args are given, they shall be parsed instead of the positional parameters.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of getopts:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
OPTIND
This variable shall be used by the getopts utility as the index of the next argument to be processed.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

Whenever an error is detected and the first character in the optstring operand is not a colon ( ':' ), a diagnostic message shall be written to standard error with the following information in an unspecified format:

*
The invoking program name shall be identified in the message. The invoking program name shall be the value of the shell special parameter 0 (see Special Parameters ) at the time the getopts utility is invoked. A name equivalent to:

basename "$0"

may be used.

*
If an option is found that was not specified in optstring, this error is identified and the invalid option character shall be identified in the message.

*
If an option requiring an option-argument is found, but an option-argument is not found, this error shall be identified and the invalid option character shall be identified in the message.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
An option, specified or unspecified by optstring, was found.
>0
The end of options was encountered or an error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since getopts affects the current shell execution environment, it is generally provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:

(getopts abc value "$@")
nohup getopts ...
find . -exec getopts ... \;

it does not affect the shell variables in the caller's environment.

Note that shell functions share OPTIND with the calling shell even though the positional parameters are changed. If the calling shell and any of its functions uses getopts to parse arguments, the results are unspecified.

EXAMPLES

The following example script parses and displays its arguments:

aflag=
bflag=
while getopts ab: name
do
    case $name in
    a)    aflag=1;;
    b)    bflag=1
          bval="$OPTARG";;
    ?)    printf "Usage: %s: [-a] [-b value] args\n" $0
          exit 2;;
    esac
done
if [ ! -z "$aflag" ]; then
    printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
    printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

RATIONALE

The getopts utility was chosen in preference to the System V getopt utility because getopts handles option-arguments containing <blank>s.

The OPTARG variable is not mentioned in the ENVIRONMENT VARIABLES section because it does not affect the execution of getopts; it is one of the few "output-only" variables used by the standard utilities.

The colon is not allowed as an option character because that is not historical behavior, and it violates the Utility Syntax Guidelines. The colon is now specified to behave as in the KornShell version of the getopts utility; when used as the first character in the optstring operand, it disables diagnostics concerning missing option-arguments and unexpected option characters. This replaces the use of the OPTERR variable that was specified in an early proposal.

The formats of the diagnostic messages produced by the getopts utility and the getopt() function are not fully specified because implementations with superior (``friendlier") formats objected to the formats used by some historical implementations. The standard developers considered it important that the information in the messages used be uniform between getopts and getopt(). Exact duplication of the messages might not be possible, particularly if a utility is built on another system that has a different getopt() function, but the messages must have specific information included so that the program name, invalid option character, and type of error can be distinguished by a user.

Only a rare application program intercepts a getopts standard error message and wants to parse it. Therefore, implementations are free to choose the most usable messages they can devise. The following formats are used by many historical implementations:

"%s: illegal option -- %c\n", <program name>, <option character>

"%s: option requires an argument -- %c\n", <program name>, \
    <option character>

Historical shells with built-in versions of getopt() or getopts have used different formats, frequently not even indicating the option character found in error.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Parameters , the System Interfaces volume of IEEE Std 1003.1-2001, getopt()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


newgrp(1p)

NEWGRP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

newgrp - change to a new group

SYNOPSIS

newgrp [-l][group]

DESCRIPTION

The newgrp utility shall create a new shell execution environment with a new real and effective group identification. Of the attributes listed in Shell Execution Environment , the new shell execution environment shall retain the working directory, file creation mask, and exported variables from the previous environment (that is, open files, traps, unexported variables, alias definitions, shell functions, and set options may be lost). All other aspects of the process environment that are preserved by the exec family of functions defined in the System Interfaces volume of IEEE Std 1003.1-2001 shall also be preserved by newgrp; whether other aspects are preserved is unspecified.

A failure to assign the new group identifications (for example, for security or password-related reasons) shall not prevent the new shell execution environment from being created.

The newgrp utility shall affect the supplemental groups for the process as follows:

*
On systems where the effective group ID is normally in the supplementary group list (or whenever the old effective group ID actually is in the supplementary group list):
*
If the new effective group ID is also in the supplementary group list, newgrp shall change the effective group ID.

*
If the new effective group ID is not in the supplementary group list, newgrp shall add the new effective group ID to the list, if there is room to add it.

*
On systems where the effective group ID is not normally in the supplementary group list (or whenever the old effective group ID is not in the supplementary group list):
*
If the new effective group ID is in the supplementary group list, newgrp shall delete it.

*
If the old effective group ID is not in the supplementary list, newgrp shall add it if there is room.

Note:
The System Interfaces volume of IEEE Std 1003.1-2001 does not specify whether the effective group ID of a process is included in its supplementary group list.

With no operands, newgrp shall change the effective group back to the groups identified in the user's user entry, and shall set the list of supplementary groups to that set in the user's group database entries.

If a password is required for the specified group, and the user is not listed as a member of that group in the group database, the user shall be prompted to enter the correct password for that group. If the user is listed as a member of that group, no password shall be requested. If no password is required for the specified group, it is implementation-defined whether users not listed as members of that group can change to that group. Whether or not a password is required, implementation-defined system accounting or security mechanisms may impose additional authorization restrictions that may cause newgrp to write a diagnostic message and suppress the changing of the group identification.

OPTIONS

The newgrp utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-l
(The letter ell.) Change the environment to what would be expected if the user actually logged in again.

OPERANDS

The following operand shall be supported:

group
A group name from the group database or a non-negative numeric group ID. Specifies the group ID to which the real and effective group IDs shall be set. If group is a non-negative numeric string and exists in the group database as a group name (see getgrnam()), the numeric group ID associated with that group name shall be used as the group ID.

STDIN

Not used.

INPUT FILES

The file /dev/tty shall be used to read a single line of text for password checking, when one is required.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of newgrp:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used for diagnostic messages and a prompt string for a password, if one is required. Diagnostic messages may be written in cases where the exit status is not available. See the EXIT STATUS section.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If newgrp succeeds in creating a new shell execution environment, whether or not the group identification was changed successfully, the exit status shall be the exit status of the shell. Otherwise, the following exit value shall be returned:

>0
An error occurred.

CONSEQUENCES OF ERRORS

The invoking shell may terminate.

The following sections are informative.

APPLICATION USAGE

There is no convenient way to enter a password into the group database. Use of group passwords is not encouraged, because by their very nature they encourage poor security practices. Group passwords may disappear in the future.

A common implementation of newgrp is that the current shell uses exec to overlay itself with newgrp, which in turn overlays itself with a new shell after changing group. On some implementations, however, this may not occur and newgrp may be invoked as a subprocess.

The newgrp command is intended only for use from an interactive terminal. It does not offer a useful interface for the support of applications.

The exit status of newgrp is generally inapplicable. If newgrp is used in a script, in most cases it successfully invokes a new shell and the rest of the original shell script is bypassed when the new shell exits. Used interactively, newgrp displays diagnostic messages to indicate problems. But usage such as:

newgrp foo
echo $?

is not useful because the new shell might not have access to any status newgrp may have generated (and most historical systems do not provide this status). A zero status echoed here does not necessarily indicate that the user has changed to the new group successfully. Following newgrp with the id command provides a portable means of determining whether the group change was successful or not.

EXAMPLES

None.

RATIONALE

Most historical implementations use one of the exec functions to implement the behavior of newgrp. Errors detected before the exec leave the environment unchanged, while errors detected after the exec leave the user in a changed environment. While it would be useful to have newgrp issue a diagnostic message to tell the user that the environment changed, it would be inappropriate to require this change to some historical implementations.

The password mechanism is allowed in the group database, but how this would be implemented is not specified.

The newgrp utility was retained in this volume of IEEE Std 1003.1-2001, even given the existence of the multiple group permissions feature in the System Interfaces volume of IEEE Std 1003.1-2001, for several reasons. First, in some implementations, the group ownership of a newly created file is determined by the group of the directory in which the file is created, as allowed by the System Interfaces volume of IEEE Std 1003.1-2001; on other implementations, the group ownership of a newly created file is determined by the effective group ID. On implementations of the latter type, newgrp allows files to be created with a specific group ownership. Finally, many implementations use the real group ID in accounting, and on such systems, newgrp allows the accounting identity of the user to be changed.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , sh , the System Interfaces volume of IEEE Std 1003.1-2001, exec, getgrnam()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


times(1p)

TIMES

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

times - write process times

SYNOPSIS

times

DESCRIPTION

The times utility shall write the accumulated user and system times for the shell and for all of its child processes, in the following POSIX locale format:

"%dm%fs %dm%fs\n%dm%fs %dm%fs\n", <shell user minutes>,
    <shell user seconds>, <shell system minutes>,
    <shell system seconds>, <children user minutes>,
    <children user seconds>, <children system minutes>,
    <children system seconds>

The four pairs of times shall correspond to the members of the <sys/times.h> tms structure (defined in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 13, Headers) as returned by times(): tms_utime, tms_stime, tms_cutime, and tms_cstime, respectively.

OPTIONS

None.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Zero.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

$ times
0m0.43s 0m1.11s
8m44.18s 1m43.23s

RATIONALE

The times special built-in from the Single UNIX Specification is now required for all conforming shells.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cxref(1p)

CXREF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cxref - generate a C-language program cross-reference table (DEVELOPMENT)

SYNOPSIS

cxref [-cs][-o file][-w num] [-D name[=def]]...[-I dir]...
[-U name]... file ...

DESCRIPTION

The cxref utility shall analyze a collection of C-language files and attempt to build a cross-reference table. Information from #define lines shall be included in the symbol table. A sorted listing shall be written to standard output of all symbols (auto, static, and global) in each file separately, or with the -c option, in combination. Each symbol shall contain an asterisk before the declaring reference.

OPTIONS

The cxref utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines, except that the order of the -D, -I, and -U options (which are identical to their interpretation by c99) is significant. The following options shall be supported:

-c
Write a combined cross-reference of all input files.
-s
Operate silently; do not print input filenames.
-o file
Direct output to named file.
-w num
Format output no wider than num (decimal) columns. This option defaults to 80 if num is not specified or is less than 51.
-D
Equivalent to c99.
-I
Equivalent to c99.
-U
Equivalent to c99.

OPERANDS

The following operand shall be supported:

file
A pathname of a C-language source file.

STDIN

Not used.

INPUT FILES

The input files are C-language source files.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cxref:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_COLLATE

Determine the locale for the ordering of the output.

LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall be used for the cross-reference listing, unless the -o option is used to select a different output file.

The format of standard output is unspecified, except that the following information shall be included:

*
If the -c option is not specified, each portion of the listing shall start with the name of the input file on a separate line.

*
The name line shall be followed by a sorted list of symbols, each with its associated location pathname, the name of the function in which it appears (if it is not a function name itself), and line number references.

*
Each line number may be preceded by an asterisk ( '*' ) flag, meaning that this is the declaring reference. Other single-character flags, with implementation-defined meanings, may be included.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The output file named by the -o option shall be used instead of standard output.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

c99

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


what(1p)

WHAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

what - identify SCCS files (DEVELOPMENT)

SYNOPSIS

what [-s] file...

DESCRIPTION

The what utility shall search the given files for all occurrences of the pattern that get (see get ) substitutes for the %Z% keyword ( "@(#)" ) and shall write to standard output what follows until the first occurrence of one of the following:

"   >   newline   \   NUL

OPTIONS

The what utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-s
Quit after finding the first occurrence of the pattern in each file.

OPERANDS

The following operands shall be supported:

file
A pathname of a file to search.

STDIN

Not used.

INPUT FILES

The input files shall be of any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of what:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

The standard output shall consist of the following for each file operand:

"%s:\n\t%s\n", <pathname>, <identification string>

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Any matches were found.
1
Otherwise.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The what utility is intended to be used in conjunction with the SCCS command get, which automatically inserts identifying information, but it can also be used where the information is inserted by any other means.

When the string "@(#)" is included in a library routine in a shared library, it might not be found in an a.out file using that library routine.

EXAMPLES

If the C-language program in file f.c contains:

char ident[] = "@(#)identification information";

and f.c is compiled to yield f.o and a.out, then the command:

what f.c f.o a.out

writes:

f.c:
    identification information
    ...
f.o:
    identification information
    ...
a.out:
    identification information
    ...

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

get

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


umask(1p)

UMASK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

umask - get or set the file mode creation mask

SYNOPSIS

umask [-S][mask]

DESCRIPTION

The umask utility shall set the file mode creation mask of the current shell execution environment (see Shell Execution Environment ) to the value specified by the mask operand. This mask shall affect the initial value of the file permission bits of subsequently created files. If umask is called in a subshell or separate utility execution environment, such as one of the following:

(umask 002)
nohup umask ...
find . -exec umask ... \;

it shall not affect the file mode creation mask of the caller's environment.

If the mask operand is not specified, the umask utility shall write to standard output the value of the invoking process' file mode creation mask.

OPTIONS

The umask utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported:

-S
Produce symbolic output.

The default output style is unspecified, but shall be recognized on a subsequent invocation of umask on the same system as a mask operand to restore the previous file mode creation mask.

OPERANDS

The following operand shall be supported:

mask
A string specifying the new file mode creation mask. The string is treated in the same way as the mode operand described in the EXTENDED DESCRIPTION section for chmod.

For a symbolic_mode value, the new value of the file mode creation mask shall be the logical complement of the file permission bits portion of the file mode specified by the symbolic_mode string.

In a symbolic_mode value, the permissions op characters '+' and '-' shall be interpreted relative to the current file mode creation mask; '+' shall cause the bits for the indicated permissions to be cleared in the mask; '-' shall cause the bits for the indicated permissions to be set in the mask.

The interpretation of mode values that specify file mode bits other than the file permission bits is unspecified.

In the octal integer form of mode, the specified bits are set in the file mode creation mask.

The file mode creation mask shall be set to the resulting numeric value.

The default output of a prior invocation of umask on the same system with no operand also shall be recognized as a mask operand.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of umask:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

When the mask operand is not specified, the umask utility shall write a message to standard output that can later be used as a umask mask operand.

If -S is specified, the message shall be in the following format:

"u=%s,g=%s,o=%s\n", <owner permissions>, <group permissions>,
    <other permissions>

where the three values shall be combinations of letters from the set { r, w, x}; the presence of a letter shall indicate that the corresponding bit is clear in the file mode creation mask.

If a mask operand is specified, there shall be no output written to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
The file mode creation mask was successfully changed, or no mask operand was supplied.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Since umask affects the current shell execution environment, it is generally provided as a shell regular built-in.

In contrast to the negative permission logic provided by the file mode creation mask and the octal number form of the mask argument, the symbolic form of the mask argument specifies those permissions that are left alone.

EXAMPLES

Either of the commands:

umask a=rx,ug+w

umask 002

sets the mode mask so that subsequently created files have their S_IWOTH bit cleared.

After setting the mode mask with either of the above commands, the umask command can be used to write out the current value of the mode mask:

$ umask
0002

(The output format is unspecified, but historical implementations use the octal integer mode format.)

$ umask -S
u=rwx,g=rwx,o=rx

Either of these outputs can be used as the mask operand to a subsequent invocation of the umask utility.

Assuming the mode mask is set as above, the command:

umask g-w

sets the mode mask so that subsequently created files have their S_IWGRP and S_IWOTH bits cleared.

The command:

umask -- -w

sets the mode mask so that subsequently created files have all their write bits cleared. Note that mask operands -r, -w, -x or anything beginning with a hyphen, must be preceded by "--" to keep it from being interpreted as an option.

RATIONALE

Since umask affects the current shell execution environment, it is generally provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:

(umask 002)
nohup umask ...
find . -exec umask ... \;

it does not affect the file mode creation mask of the environment of the caller.

The description of the historical utility was modified to allow it to use the symbolic modes of chmod. The -s option used in early proposals was changed to -S because -s could be confused with a symbolic_mode form of mask referring to the S_ISUID and S_ISGID bits.

The default output style is implementation-defined to permit implementors to provide migration to the new symbolic style at the time most appropriate to their users. A -o flag to force octal mode output was omitted because the octal mode may not be sufficient to specify all of the information that may be present in the file mode creation mask when more secure file access permission checks are implemented.

It has been suggested that trusted systems developers might appreciate ameliorating the requirement that the mode mask "affects" the file access permissions, since it seems access control lists might replace the mode mask to some degree. The wording has been changed to say that it affects the file permission bits, and it leaves the details of the behavior of how they affect the file access permissions to the description in the System Interfaces volume of IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , chmod , the System Interfaces volume of IEEE Std 1003.1-2001, umask()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


renice(1p)

RENICE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

renice - set nice values of running processes

SYNOPSIS

renice -n increment [-g | -p | -u] ID ...

DESCRIPTION

The renice utility shall request that the nice values (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.239, Nice Value) of one or more running processes be changed. By default, the applicable processes are specified by their process IDs. When a process group is specified (see -g), the request shall apply to all processes in the process group.

The nice value shall be bounded in an implementation-defined manner. If the requested increment would raise or lower the nice value of the executed utility beyond implementation-defined limits, then the limit whose value was exceeded shall be used.

When a user is reniced, the request applies to all processes whose saved set-user-ID matches the user ID corresponding to the user.

Regardless of which options are supplied or any other factor, renice shall not alter the nice values of any process unless the user requesting such a change has appropriate privileges to do so for the specified process. If the user lacks appropriate privileges to perform the requested action, the utility shall return an error status.

The saved set-user-ID of the user's process shall be checked instead of its effective user ID when renice attempts to determine the user ID of the process in order to determine whether the user has appropriate privileges.

OPTIONS

The renice utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following options shall be supported:

-g
Interpret all operands as unsigned decimal integer process group IDs.
-n increment
Specify how the nice value of the specified process or processes is to be adjusted. The increment option-argument is a positive or negative decimal integer that shall be used to modify the nice value of the specified process or processes.

Positive increment values shall cause a lower nice value. Negative increment values may require appropriate privileges and shall cause a higher nice value.

-p
Interpret all operands as unsigned decimal integer process IDs. The -p option is the default if no options are specified.
-u
Interpret all operands as users. If a user exists with a user name equal to the operand, then the user ID of that user is used in further processing. Otherwise, if the operand represents an unsigned decimal integer, it shall be used as the numeric user ID of the user.

OPERANDS

The following operands shall be supported:

ID
A process ID, process group ID, or user name/user ID, depending on the option selected.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of renice:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

1.
Adjust the nice value so that process IDs 987 and 32 would have a lower nice value:

renice -n 5 -p 987 32

2.
Adjust the nice value so that group IDs 324 and 76 would have a higher nice value, if the user has the appropriate privileges to do so:

renice -n -4 -g 324 76

3.
Adjust the nice value so that numeric user ID 8 and user sas would have a lower nice value:

renice -n 4 -u 8 sas

Useful nice value increments on historical systems include 19 or 20 (the affected processes run only when nothing else in the system attempts to run) and any negative number (to make processes run faster).

RATIONALE

The gid, pid, and user specifications do not fit either the definition of operand or option-argument. However, for clarity, they have been included in the OPTIONS section, rather than the OPERANDS section.

The definition of nice value is not intended to suggest that all processes in a system have priorities that are comparable. Scheduling policy extensions such as the realtime priorities in the System Interfaces volume of IEEE Std 1003.1-2001 make the notion of a single underlying priority for all scheduling policies problematic. Some implementations may implement the nice-related features to affect all processes on the system, others to affect just the general time-sharing activities implied by this volume of IEEE Std 1003.1-2001, and others may have no effect at all. Because of the use of "implementation-defined" in nice and renice, a wide range of implementation strategies are possible.

Originally, this utility was written in the historical manner, using the term "nice value". This was always a point of concern with users because it was never intuitively obvious what this meant. With a newer version of renice, which used the term "system scheduling priority", it was hoped that novice users could better understand what this utility was meant to do. Also, it would be easier to document what the utility was meant to do. Unfortunately, the addition of the POSIX realtime scheduling capabilities introduced the concepts of process and thread scheduling priorities that were totally unaffected by the nice/ renice utilities or the nice()/ setpriority() functions. Continuing to use the term "system scheduling priority'' would have incorrectly suggested that these utilities and functions were indeed affecting these realtime priorities. It was decided to revert to the historical term "nice value" to reference this unrelated process attribute.

Although this utility has use by system administrators (and in fact appears in the system administration portion of the BSD documentation), the standard developers considered that it was very useful for individual end users to control their own processes.

FUTURE DIRECTIONS

None.

SEE ALSO

nice()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


write(1p)

WRITE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

write - write to another user

SYNOPSIS

write user_name [terminal]

DESCRIPTION

The write utility shall read lines from the user's standard input and write them to the terminal of another user. When first invoked, it shall write the message:

Message from sender-login-id (sending-terminal) [date]...

to user_name. When it has successfully completed the connection, the sender's terminal shall be alerted twice to indicate that what the sender is typing is being written to the recipient's terminal.

If the recipient wants to reply, this can be accomplished by typing:

write sender-login-id [sending-terminal]

upon receipt of the initial message. Whenever a line of input as delimited by an NL, EOF, or EOL special character (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface) is accumulated while in canonical input mode, the accumulated data shall be written on the other user's terminal. Characters shall be processed as follows:

*
Typing <alert> shall write the alert character to the recipient's terminal.

*
Typing the erase and kill characters shall affect the sender's terminal in the manner described by the termios interface in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface.

*
Typing the interrupt or end-of-file characters shall cause write to write an appropriate message ( "EOT\n" in the POSIX locale) to the recipient's terminal and exit.

*
Typing characters from LC_CTYPE classifications print or space shall cause those characters to be sent to the recipient's terminal.

*
When and only when the stty iexten local mode is enabled, the existence and processing of additional special control characters and multi-byte or single-byte functions is implementation-defined.

*
Typing other non-printable characters shall cause implementation-defined sequences of printable characters to be written to the recipient's terminal.

To write to a user who is logged in more than once, the terminal argument can be used to indicate which terminal to write to; otherwise, the recipient's terminal is selected in an implementation-defined manner and an informational message is written to the sender's standard output, indicating which terminal was chosen.

Permission to be a recipient of a write message can be denied or granted by use of the mesg utility. However, a user's privilege may further constrain the domain of accessibility of other users' terminals. The write utility shall fail when the user lacks the appropriate privileges to perform the requested action.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

user_name
Login name of the person to whom the message shall be written. The application shall ensure that this operand is of the form returned by the who utility.
terminal
Terminal identification in the same format provided by the who utility.

STDIN

Lines to be copied to the recipient's terminal are read from standard input.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of write:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files). If the recipient's locale does not use an LC_CTYPE equivalent to the sender's, the results are undefined.
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

If an interrupt signal is received, write shall write an appropriate message on the recipient's terminal and exit with a status of zero. It shall take the standard action for all other signals.

STDOUT

An informational message shall be written to standard output if a recipient is logged in more than once.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The recipient's terminal is used for output.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
The addressed user is not logged on or the addressed user denies permission.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The talk utility is considered by some users to be a more usable utility on full-screen terminals.

EXAMPLES

None.

RATIONALE

The write utility was included in this volume of IEEE Std 1003.1-2001 since it can be implemented on all terminal types. The standard developers considered the talk utility, which cannot be implemented on certain terminals, to be a "better" communications interface. Both of these programs are in widespread use on historical implementations. Therefore, the standard developers decided that both utilities should be specified.

The format of the terminal name is unspecified, but the descriptions of ps, talk, who, and write require that they all use or accept the same format.

FUTURE DIRECTIONS

None.

SEE ALSO

mesg , talk , who , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ipcs(1p)

IPCS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ipcs - report XSI interprocess communication facilities status

SYNOPSIS

ipcs [-qms][-a | -bcopt]

DESCRIPTION

The ipcs utility shall write information about active interprocess communication facilities.

Without options, information shall be written in short format for message queues, shared memory segments, and semaphore sets that are currently active in the system. Otherwise, the information that is displayed is controlled by the options specified.

OPTIONS

The ipcs facility supports the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The ipcs utility accepts the following options:

-q
Write information about active message queues.
-m
Write information about active shared memory segments.
-s
Write information about active semaphore sets.

If -q, -m, or -s are specified, only information about those facilities shall be written. If none of these three are specified, information about all three shall be written subject to the following options:

-a
Use all print options. (This is a shorthand notation for -b, -c, -o, -p, and -t.)
-b
Write information on maximum allowable size. (Maximum number of bytes in messages on queue for message queues, size of segments for shared memory, and number of semaphores in each set for semaphores.)
-c
Write creator's user name and group name; see below.
-o
Write information on outstanding usage. (Number of messages on queue and total number of bytes in messages on queue for message queues, and number of processes attached to shared memory segments.)
-p
Write process number information. (Process ID of the last process to send a message and process ID of the last process to receive a message on message queues, process ID of the creating process, and process ID of the last process to attach or detach on shared memory segments.)
-t
Write time information. (Time of the last control operation that changed the access permissions for all facilities, time of the last msgsnd() and msgrcv() operations on message queues, time of the last shmat() and shmdt() operations on shared memory, and time of the last semop() operation on semaphores.)

OPERANDS

None.

STDIN

Not used.

INPUT FILES

*
The group database

*
The user database

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of ipcs:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
TZ
Determine the timezone for the date and time strings written by ipcs. If TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

An introductory line shall be written with the format:

"IPC status from %s as of %s\n", <source>, <date>

where <source> indicates the source used to gather the statistics and <date> is the information that would be produced by the date command when invoked in the POSIX locale.

The ipcs utility then shall create up to three reports depending upon the -q, -m, and -s options. The first report shall indicate the status of message queues, the second report shall indicate the status of shared memory segments, and the third report shall indicate the status of semaphore sets.

If the corresponding facility is not installed or has not been used since the last reboot, then the report shall be written out in the format:

"%s facility not in system.\n", <facility>

where <facility> is Message Queue, Shared Memory, or Semaphore, as appropriate. If the facility has been installed and has been used since the last reboot, column headings separated by one or more spaces and followed by a <newline> shall be written as indicated below followed by the facility name written out using the format:

"%s:\n", <facility>

where <facility> is Message Queues, Shared Memory, or Semaphores, as appropriate. On the second and third reports the column headings need not be written if the last column headings written already provide column headings for all information in that report.

The column headings provided in the first column below and the meaning of the information in those columns shall be given in order below; the letters in parentheses indicate the options that shall cause the corresponding column to appear; "all" means that the column shall always appear. Each column is separated by one or more <space>s. Note that these options only determine what information is provided for each report; they do not determine which reports are written.

T (all)
Type of facility:
q
Message queue.
m
Shared memory segment.
s
Semaphore.

This field is a single character written using the format %c .

ID (all)
The identifier for the facility entry. This field shall be written using the format %d .
KEY (all)
The key used as an argument to msgget(), semget(), or shmget() to create the facility entry.
Note:
The key of a shared memory segment is changed to IPC_PRIVATE when the segment has been removed until all processes attached to the segment detach it.

This field shall be written using the format 0x%x.

MODE (all)
The facility access modes and flags. The mode shall consist of 11 characters that are interpreted as follows.

The first character shall be:

S
If a process is waiting on a msgsnd() operation.
-
If the above is not true.

The second character shall be:

R
If a process is waiting on a msgrcv() operation.
C or -
If the associated shared memory segment is to be cleared when the first attach operation is executed.
-
If none of the above is true.

The next nine characters shall be interpreted as three sets of three bits each. The first set refers to the owner's permissions; the next to permissions of others in the usergroup of the facility entry; and the last to all others. Within each set, the first character indicates permission to read, the second character indicates permission to write or alter the facility entry, and the last character is a minus sign ( '-' ).

The permissions shall be indicated as follows:

r
If read permission is granted.
w
If write permission is granted.
a
If alter permission is granted.
-
If the indicated permission is not granted.

The first character following the permissions specifies if there is an alternate or additional access control method associated with the facility. If there is no alternate or additional access control method associated with the facility, a single <space> shall be written; otherwise, another printable character is written.

OWNER (all)
The user name of the owner of the facility entry. If the user name of the owner is found in the user database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the user ID of the owner shall be written using the format %d .
GROUP (all)
The group name of the owner of the facility entry. If the group name of the owner is found in the group database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the group ID of the owner shall be written using the format %d .

The following nine columns shall be only written out for message queues:

CREATOR (a,c)
The user name of the creator of the facility entry. If the user name of the creator is found in the user database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the user ID of the creator shall be written using the format %d .
CGROUP (a,c)
The group name of the creator of the facility entry. If the group name of the creator is found in the group database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the group ID of the creator shall be written using the format %d .
CBYTES (a,o)
The number of bytes in messages currently outstanding on the associated message queue. This field shall be written using the format %d .
QNUM (a,o)
The number of messages currently outstanding on the associated message queue. This field shall be written using the format %d .
QBYTES (a,b)
The maximum number of bytes allowed in messages outstanding on the associated message queue. This field shall be written using the format %d .
LSPID (a,p)
The process ID of the last process to send a message to the associated queue. This field shall be written using the format:

"%d", <pid>

where <pid> is 0 if no message has been sent to the corresponding message queue; otherwise, <pid> shall be the process ID of the last process to send a message to the queue.

LRPID (a,p)
The process ID of the last process to receive a message from the associated queue. This field shall be written using the format:

"%d", <pid>

where <pid> is 0 if no message has been received from the corresponding message queue; otherwise, <pid> shall be the process ID of the last process to receive a message from the queue.

STIME (a,t)
The time the last message was sent to the associated queue. If a message has been sent to the corresponding message queue, the hour, minute, and second of the last time a message was sent to the queue shall be written using the format %d : %2.2d : %2.2d . Otherwise, the format " no-entry" shall be written.
RTIME (a,t)
The time the last message was received from the associated queue. If a message has been received from the corresponding message queue, the hour, minute, and second of the last time a message was received from the queue shall be written using the format %d : %2.2d : %2.2d . Otherwise, the format " no-entry" shall be written.

The following eight columns shall be only written out for shared memory segments.

CREATOR (a,c)
The user of the creator of the facility entry. If the user name of the creator is found in the user database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the user ID of the creator shall be written using the format %d .
CGROUP (a,c)
The group name of the creator of the facility entry. If the group name of the creator is found in the group database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the group ID of the creator shall be written using the format %d .
NATTCH (a,o)
The number of processes attached to the associated shared memory segment. This field shall be written using the format %d .
SEGSZ (a,b)
The size of the associated shared memory segment. This field shall be written using the format %d .
CPID (a,p)
The process ID of the creator of the shared memory entry. This field shall be written using the format %d .
LPID (a,p)
The process ID of the last process to attach or detach the shared memory segment. This field shall be written using the format:

"%d", <pid>

where <pid> is 0 if no process has attached the corresponding shared memory segment; otherwise, <pid> shall be the process ID of the last process to attach or detach the segment.

ATIME (a,t)
The time the last attach on the associated shared memory segment was completed. If the corresponding shared memory segment has ever been attached, the hour, minute, and second of the last time the segment was attached shall be written using the format %d : %2.2d : %2.2d . Otherwise, the format " no-entry" shall be written.
DTIME (a,t)
The time the last detach on the associated shared memory segment was completed. If the corresponding shared memory segment has ever been detached, the hour, minute, and second of the last time the segment was detached shall be written using the format %d : %2.2d : %2.2d . Otherwise, the format " no-entry" shall be written.

The following four columns shall be only written out for semaphore sets:

CREATOR (a,c)
The user of the creator of the facility entry. If the user name of the creator is found in the user database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the user ID of the creator shall be written using the format %d .
CGROUP (a,c)
The group name of the creator of the facility entry. If the group name of the creator is found in the group database, at least the first eight column positions of the name shall be written using the format %s . Otherwise, the group ID of the creator shall be written using the format %d .
NSEMS (a,b)
The number of semaphores in the set associated with the semaphore entry. This field shall be written using the format %d .
OTIME (a,t)
The time the last semaphore operation on the set associated with the semaphore entry was completed. If a semaphore operation has ever been performed on the corresponding semaphore set, the hour, minute, and second of the last semaphore operation on the semaphore set shall be written using the format %d : %2.2d : %2.2d . Otherwise, the format " no-entry" shall be written.

The following column shall be written for all three reports when it is requested:

CTIME (a,t)
The time the associated entry was created or changed. The hour, minute, and second of the time when the associated entry was created shall be written using the format %d : %2.2d : %2.2d .

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

Things can change while ipcs is running; the information it gives is guaranteed to be accurate only when it was retrieved.

EXAMPLES

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The System Interfaces volume of IEEE Std 1003.1-2001, msgrcv(), msgsnd(), semget(), semop(), shmat(), shmdt(), shmget()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strip(1p)

STRIP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strip - remove unnecessary information from executable files (DEVELOPMENT)

SYNOPSIS

strip file...

DESCRIPTION

The strip utility shall remove from executable files named by the file operands any information the implementor deems unnecessary for execution of those files. The nature of that information is unspecified. The effect of strip shall be similar to the use of the -s option to c99 or fort77.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

file
A pathname referring to an executable file.

STDIN

Not used.

INPUT FILES

The input files shall be in the form of executable files successfully produced by any compiler defined by this volume of IEEE Std 1003.1-2001.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of strip:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

The strip utility shall produce executable files of unspecified format.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

Historically, this utility has been used to remove the symbol table from an executable file. It was included since it is known that the amount of symbolic information can amount to several megabytes; the ability to remove it in a portable manner was deemed important, especially for smaller systems.

The behavior of strip is said to be the same as the -s option to a compiler. While the end result is essentially the same, it is not required to be identical.

FUTURE DIRECTIONS

None.

SEE ALSO

ar , c99 , fort77

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


batch(1p)

BATCH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

batch - schedule commands to be executed in a batch queue

SYNOPSIS

batch

DESCRIPTION

The batch utility shall read commands from standard input and schedule them for execution in a batch queue. It shall be the equivalent of the command:

at -q b -m now

where queue b is a special at queue, specifically for batch jobs. Batch jobs shall be submitted to the batch queue with no time constraints and shall be run by the system using algorithms, based on unspecified factors, that may vary with each invocation of batch.

Users shall be permitted to use batch if their name appears in the file /usr/lib/cron/at.allow. If that file does not exist, the file /usr/lib/cron/at.deny shall be checked to determine whether the user shall be denied access to batch. If neither file exists, only a process with the appropriate privileges shall be allowed to submit a job. If only at.deny exists and is empty, global usage shall be permitted. The at.allow and at.deny files shall consist of one user name per line.

OPTIONS

None.

OPERANDS

None.

STDIN

The standard input shall be a text file consisting of commands acceptable to the shell command language described in Shell Command Language .

INPUT FILES

The text files /usr/lib/cron/at.allow and /usr/lib/cron/at.deny shall contain zero or more user names, one per line, of users who are, respectively, authorized or denied access to the at and batch utilities.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of batch:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error and informative messages written to standard output.
LC_TIME
Determine the format and contents for date and time strings written by batch.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
SHELL
Determine the name of a command interpreter to be used to invoke the at-job. If the variable is unset or null, sh shall be used. If it is set to a value other than a name for sh, the implementation shall do one of the following: use that shell; use sh; use the login shell from the user database; any of the preceding accompanied by a warning diagnostic about which was chosen.
TZ
Determine the timezone. The job shall be submitted for execution at the time specified by timespec or -t time relative to the timezone specified by the TZ variable. If timespec specifies a timezone, it overrides TZ . If timespec does not specify a timezone and TZ is unset or null, an unspecified default timezone shall be used.

ASYNCHRONOUS EVENTS

Default.

STDOUT

When standard input is a terminal, prompts of unspecified format for each line of the user input described in the STDIN section may be written to standard output.

STDERR

The following shall be written to standard error when a job has been successfully submitted:

"job %s at %s\n", at_job_id, <date>

where date shall be equivalent in format to the output of:

date +"%a %b %e %T %Y"

The date and time written shall be adjusted so that they appear in the timezone of the user (as determined by the TZ variable).

Neither this, nor warning messages concerning the selection of the command interpreter, are considered a diagnostic that changes the exit status.

Diagnostic messages, if any, shall be written to standard error.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

The job shall not be scheduled.

The following sections are informative.

APPLICATION USAGE

It may be useful to redirect standard output within the specified commands.

EXAMPLES

1.
This sequence can be used at a terminal:

batch
sort < file >outfile
EOT

2.
This sequence, which demonstrates redirecting standard error to a pipe, is useful in a command procedure (the sequence of output redirection specifications is significant):

batch <<
! diff file1 file2 2>&1 >outfile | mailx mygroup
!

RATIONALE

Early proposals described batch in a manner totally separated from at, even though the historical model treated it almost as a synonym for at -qb. A number of features were added to list and control batch work separately from those in at. Upon further reflection, it was decided that the benefit of this did not merit the change to the historical interface.

The -m option was included on the equivalent at command because it is historical practice to mail results to the submitter, even if all job-produced output is redirected. As explained in the RATIONALE for at, the now keyword submits the job for immediate execution (after scheduling delays), despite some historical systems where at now would have been considered an error.

FUTURE DIRECTIONS

None.

SEE ALSO

at

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qdel(1p)

QDEL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qdel - delete batch jobs

SYNOPSIS

qdel job_identifier ...

DESCRIPTION

A batch job is deleted by sending a request to the batch server that manages the batch job. A batch job that has been deleted is no longer subject to management by batch services.

The qdel utility is a user-accessible client of batch services that requests the deletion of one or more batch jobs.

The qdel utility shall request a batch server to delete those batch jobs for which a batch job_identifier is presented to the utility.

The qdel utility shall delete batch jobs in the order in which their batch job_identifiers are presented to the utility.

If the qdel utility fails to process any batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

The qdel utility shall delete each batch job by sending a Delete Job Request to the batch server that manages the batch job.

The qdel utility shall not exit until the batch job corresponding to each successfully processed batch job_identifier has been deleted.

OPTIONS

None.

OPERANDS

The qdel utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qdel:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.

ASYNCHRONOUS EVENTS

Default.

STDOUT

An implementation of the qdel utility may write informative messages to standard output.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qdel utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qdel utility waits to output the diagnostic message while attempting to locate the job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qdel utility allows users and administrators to delete jobs.

The qdel utility provides functionality that is not otherwise available. For example, the kill utility of the operating system does not suffice. First, to use the kill utility, the user might have to log in on a remote node, because the kill utility does not operate across the network. Second, unlike qdel, kill cannot remove jobs from queues. Lastly, the arguments of the qdel utility are job identifiers rather than process identifiers, and so this utility can be passed the output of the qselect utility, thus providing users with a means of deleting a list of jobs.

Because a set of jobs can be selected using the qselect utility, the qdel utility has not been complicated with options that provide for selection of jobs. Instead, the batch jobs to be deleted are identified individually by their job identifiers.

Historically, the qdel utility has been a component of NQS, the existing practice on which it is based. However, the qdel utility defined in this volume of IEEE Std 1003.1-2001 does not provide an option for specifying a signal number to send to the batch job prior to the killing of the process; that capability has been subsumed by the qsig utility.

A discussion was held about the delays of networking and the possibility that the batch server may never respond, due to a down router, down batch server, or other network mishap. The DESCRIPTION records this under the words "fails to process any job identifier". In the broad sense, the network problem is also an error, which causes the failure to process the batch job identifier.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , kill() , qselect , qsig

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


qhold(1p)

QHOLD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qhold - hold batch jobs

SYNOPSIS

qhold [-h hold_list] job_identifier ...

DESCRIPTION

A hold is placed on a batch job by a request to the batch server that manages the batch job. A batch job that has one or more holds is not eligible for execution. The qhold utility is a user-accessible client of batch services that requests one or more types of hold to be placed on one or more batch jobs.

The qhold utility shall place holds on those batch jobs for which a batch job_identifier is presented to the utility.

The qhold utility shall place holds on batch jobs in the order in which their batch job_identifiers are presented to the utility. If the qhold utility fails to process any batch job_identifier successfully, the utility shall proceed to process the remaining batch job_identifiers, if any.

The qhold utility shall place holds on each batch job by sending a Hold Job Request to the batch server that manages the batch job.

The qhold utility shall not exit until holds have been placed on the batch job corresponding to each successfully processed batch job_identifier.

OPTIONS

The qhold utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The following option shall be supported by the implementation:

-h hold_list
Define the types of holds to be placed on the batch job.

The qhold -h option shall accept a value for the hold_list option-argument that is a string of alphanumeric characters in the portable character set (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 6.1, Portable Character Set).

The qhold utility shall accept a value for the hold_list option-argument that is a string of one or more of the characters 'u' , 's' , or 'o' , or the single character 'n' .

For each unique character in the hold_list option-argument, the qhold utility shall add a value to the Hold_Types attribute of the batch job as follows, each representing a different hold type:

u
USER
s
SYSTEM
o
OPERATOR

If any of these characters are duplicated in the hold_list option-argument, the duplicates shall be ignored.

An existing Hold_Types attribute can be cleared by the following hold type:

n
NO_HOLD

The qhold utility shall consider it an error if any hold type other than 'n' is combined with hold type 'n' .

Strictly conforming applications shall not repeat any of the characters 'u' , 's' , 'o' , or 'n' within the hold_list option-argument. The qhold utility shall permit the repetition of characters, but shall not assign additional meaning to the repeated characters.

An implementation may define other hold types. The conformance document for an implementation shall describe any additional hold types, how they are specified, their internal behavior, and how they affect the behavior of the utility.

If the -h option is not presented to the qhold utility, the implementation shall set the Hold_Types attribute to USER.

OPERANDS

The qhold utility shall accept one or more operands that conform to the syntax for a batch job_identifier (see Batch Job Identifier ).

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of qhold:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LOGNAME
Determine the login name of the user.

ASYNCHRONOUS EVENTS

Default.

STDOUT

None.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

In addition to the default behavior, the qhold utility shall not be required to write a diagnostic message to standard error when the error reply received from a batch server indicates that the batch job_identifier does not exist on the server. Whether or not the qhold utility waits to output the diagnostic message while attempting to locate the job on other servers is implementation-defined.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The qhold utility allows users to place a hold on one or more jobs. A hold makes a batch job ineligible for execution.

The qhold utility has options that allow the user to specify the type of hold. Should the user wish to place a hold on a set of jobs that meet a selection criteria, such a list of jobs can be acquired using the qselect utility.

The -h option allows the user to specify the type of hold that is to be placed on the job. This option allows for USER, SYSTEM, OPERATOR, and implementation-defined hold types. The USER and OPERATOR holds are distinct. The batch server that manages the batch job will verify that the user is authorized to set the specified hold for the batch job.

Mail is not required on hold because the administrator has the tools and libraries to build this option if he or she wishes.

Historically, the qhold utility has been a part of some existing batch systems, although it has not traditionally been a part of the NQS.

FUTURE DIRECTIONS

None.

SEE ALSO

Batch Environment Services , qselect

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


return(1p)

RETURN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

return - return from a function

SYNOPSIS

return [n]

DESCRIPTION

The return utility shall cause the shell to stop executing the current function or dot script. If the shell is not currently executing a function or dot script, the results are unspecified.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The value of the special parameter '?' shall be set to n, an unsigned decimal integer, or to the exit status of the last command executed if n is not specified. If the value of n is greater than 255, the results are undefined. When return is executed in a trap action, the last command is considered to be the command that executed immediately preceding the trap action.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The behavior of return when not in a function or dot script differs between the System V shell and the KornShell. In the System V shell this is an error, whereas in the KornShell, the effect is the same as exit.

The results of returning a number greater than 255 are undefined because of differing practices in the various historical implementations. Some shells AND out all but the low-order 8 bits; others allow larger values, but not of unlimited size.

See the discussion of appropriate exit status values under exit .

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cksum(1p)

CKSUM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cksum - write file checksums and sizes

SYNOPSIS

cksum [file ...]

DESCRIPTION

The cksum utility shall calculate and write to standard output a cyclic redundancy check (CRC) for each input file, and also write to standard output the number of octets in each file. The CRC used is based on the polynomial used for CRC error checking in the ISO/IEC 8802-3:1996 standard (Ethernet).

The encoding for the CRC checksum is defined by the generating polynomial:

G(x)=x**32+x**26+x**23+x**22+x**16+x**12+x**11+x**10+x**8+x**7+x**5+x**4+x**2+x+1

Mathematically, the CRC value corresponding to a given file shall be defined by the following procedure:

1.
The n bits to be evaluated are considered to be the coefficients of a mod 2 polynomial M( x) of degree n-1. These n bits are the bits from the file, with the most significant bit being the most significant bit of the first octet of the file and the last bit being the least significant bit of the last octet, padded with zero bits (if necessary) to achieve an integral number of octets, followed by one or more octets representing the length of the file as a binary value, least significant octet first. The smallest number of octets capable of representing this integer shall be used.

2.
M( x) is multiplied by x**32 (that is, shifted left 32 bits) and divided by G( x) using mod 2 division, producing a remainder R( x) of degree <= 31.

3.
The coefficients of R( x) are considered to be a 32-bit sequence.

4.
The bit sequence is complemented and the result is the CRC.

OPTIONS

None.

OPERANDS

The following operand shall be supported:

file
A pathname of a file to be checked. If no file operands are specified, the standard input shall be used.

STDIN

The standard input shall be used only if no file operands are specified. See the INPUT FILES section.

INPUT FILES

The input files can be any file type.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of cksum:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

For each file processed successfully, the cksum utility shall write in the following format:

"%u %d %s\n", <checksum>, <# of octets>, <pathname>

If no file operand was specified, the pathname and its leading <space> shall be omitted.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

0
All files were processed successfully.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The cksum utility is typically used to quickly compare a suspect file against a trusted version of the same, such as to ensure that files transmitted over noisy media arrive intact. However, this comparison cannot be considered cryptographically secure. The chances of a damaged file producing the same CRC as the original are small; deliberate deception is difficult, but probably not impossible.

Although input files to cksum can be any type, the results need not be what would be expected on character special device files or on file types not described by the System Interfaces volume of IEEE Std 1003.1-2001. Since this volume of IEEE Std 1003.1-2001 does not specify the block size used when doing input, checksums of character special files need not process all of the data in those files.

The algorithm is expressed in terms of a bitstream divided into octets. If a file is transmitted between two systems and undergoes any data transformation (such as changing little-endian byte ordering to big-endian), identical CRC values cannot be expected. Implementations performing such transformations may extend cksum to handle such situations.

EXAMPLES

None.

RATIONALE

The following C-language program can be used as a model to describe the algorithm. It assumes that a char is one octet. It also assumes that the entire file is available for one pass through the function. This was done for simplicity in demonstrating the algorithm, rather than as an implementation model.

static unsigned long crctab[] = {
0x00000000,
0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6,
0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac,
0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f,
0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a,
0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58,
0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033,
0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe,
0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4,
0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5,
0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07,
0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c,
0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1,
0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b,
0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698,
0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d,
0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f,
0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80,
0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a,
0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629,
0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c,
0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e,
0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65,
0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8,
0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2,
0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74,
0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21,
0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a,
0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087,
0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d,
0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce,
0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb,
0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09,
0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf,
0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};

unsigned long memcrc(const unsigned char *b, size_t n)
{
/*  Input arguments:
 *  const char*   b == byte sequence to checksum
 *  size_t        n == length of sequence
 */

    register unsigned   i, c, s = 0;

    for (i = n; i > 0; --i) {
        c = (unsigned)(*b++);
        s = (s << 8) ^ crctab[(s >> 24) ^ c];
    }

    /* Extend with the length of the string. */
    while (n != 0) {
        c = n & 0377;
        n >>= 8;
        s = (s << 8) ^ crctab[(s >> 24) ^ c];
    }

    return ~s;
}

The historical practice of writing the number of "blocks" has been changed to writing the number of octets, since the latter is not only more useful, but also since historical implementations have not been consistent in defining what a "block" meant. Octets are used instead of bytes because bytes can differ in size between systems.

The algorithm used was selected to increase the operational robustness of cksum. Neither the System V nor BSD sum algorithm was selected. Since each of these was different and each was the default behavior on those systems, no realistic compromise was available if either were selected-some set of historical applications would break. Therefore, the name was changed to cksum. Although the historical sum commands will probably continue to be provided for many years, programs designed for portability across systems should use the new name.

The algorithm selected is based on that used by the ISO/IEC 8802-3:1996 standard (Ethernet) for the frame check sequence field. The algorithm used does not match the technical definition of a checksum; the term is used for historical reasons. The length of the file is included in the CRC calculation because this parallels inclusion of a length field by Ethernet in its CRC, but also because it guards against inadvertent collisions between files that begin with different series of zero octets. The chance that two different files produce identical CRCs is much greater when their lengths are not considered. Keeping the length and the checksum of the file itself separate would yield a slightly more robust algorithm, but historical usage has always been that a single number (the checksum as printed) represents the signature of the file. It was decided that historical usage was the more important consideration.

Early proposals contained modifications to the Ethernet algorithm that involved extracting table values whenever an intermediate result became zero. This was demonstrated to be less robust than the current method and mathematically difficult to describe or justify.

The calculation used is identical to that given in pseudo-code in the referenced Sarwate article. The pseudo-code rendition is:

X <- 0; Y <- 0;
for i <- m -1 step -1 until 0 do
    begin
    T <- X(1) ^ A[i];
    X(1) <- X(0); X(0) <- Y(1); Y(1) <- Y(0); Y(0) <- 0;
    comment: f[T] and f'[T] denote the T-th words in the
        table f and f' ;
    X <- X ^ f[T]; Y <- Y ^ f'[T];
    end

The pseudo-code is reproduced exactly as given; however, note that in the case of cksum, A[i] represents a byte of the file, the words X and Y are treated as a single 32-bit value, and the tables f and f' are a single table containing 32-bit values.

The referenced Sarwate article also discusses generating the table.

FUTURE DIRECTIONS

None.

SEE ALSO

None.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nohup(1p)

NOHUP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nohup - invoke a utility immune to hangups

SYNOPSIS

nohup utility [argument...]

DESCRIPTION

The nohup utility shall invoke the utility named by the utility operand with arguments supplied as the argument operands. At the time the named utility is invoked, the SIGHUP signal shall be set to be ignored.

If the standard output is a terminal, all output written by the named utility to its standard output shall be appended to the end of the file nohup.out in the current directory. If nohup.out cannot be created or opened for appending, the output shall be appended to the end of the file nohup.out in the directory specified by the HOME environment variable. If neither file can be created or opened for appending, utility shall not be invoked. If a file is created, the file's permission bits shall be set to S_IRUSR | S_IWUSR.

If the standard error is a terminal, all output written by the named utility to its standard error shall be redirected to the same file descriptor as the standard output.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

utility
The name of a utility that is to be invoked. If the utility operand names any of the special built-in utilities in Special Built-In Utilities , the results are undefined.
argument
Any string to be supplied as an argument when invoking the utility named by the utility operand.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of nohup:

HOME
Determine the pathname of the user's home directory: if the output file nohup.out cannot be created in the current directory, the nohup utility shall use the directory named by HOME to create the file.
LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .
PATH
Determine the search path that is used to locate the utility to be invoked. See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

ASYNCHRONOUS EVENTS

The nohup utility shall take the standard action for all signals except that SIGHUP shall be ignored.

STDOUT

If the standard output is not a terminal, the standard output of nohup shall be the standard output generated by the execution of the utility specified by the operands. Otherwise, nothing shall be written to the standard output.

STDERR

If the standard output is a terminal, a message shall be written to the standard error, indicating the name of the file to which the output is being appended. The name of the file shall be either nohup.out or $HOME/nohup.out.

OUTPUT FILES

If the standard output is a terminal, all output written by the named utility to the standard output and standard error is appended to the file nohup.out, which is created if it does not already exist.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The following exit values shall be returned:

126
The utility specified by utility was found but could not be invoked.
127
An error occurred in the nohup utility or the utility specified by utility could not be found.

Otherwise, the exit status of nohup shall be that of the utility specified by the utility operand.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The command, env, nice, nohup, time, and xargs utilities have been specified to use exit code 127 if an error occurs so that applications can distinguish "failure to find a utility" from "invoked utility exited with an error indication". The value 127 was chosen because it is not commonly used for other meanings; most utilities use small values for "normal error conditions" and the values above 128 can be confused with termination due to receipt of a signal. The value 126 was chosen in a similar manner to indicate that the utility could be found, but not invoked. Some scripts produce meaningful error messages differentiating the 126 and 127 cases. The distinction between exit codes 126 and 127 is based on KornShell practice that uses 127 when all attempts to exec the utility fail with [ENOENT], and uses 126 when any attempt to exec the utility fails for any other reason.

EXAMPLES

It is frequently desirable to apply nohup to pipelines or lists of commands. This can be done by placing pipelines and command lists in a single file; this file can then be invoked as a utility, and the nohup applies to everything in the file.

Alternatively, the following command can be used to apply nohup to a complex command:

nohup sh -c 'complex-command-line'

RATIONALE

The 4.3 BSD version ignores SIGTERM and SIGHUP, and if ./nohup.out cannot be used, it fails instead of trying to use $HOME/nohup.out.

The csh utility has a built-in version of nohup that acts differently from the nohup defined in this volume of IEEE Std 1003.1-2001.

The term utility is used, rather than command, to highlight the fact that shell compound commands, pipelines, special built-ins, and so on, cannot be used directly. However, utility includes user application programs and shell scripts, not just the standard utilities.

Historical versions of the nohup utility use default file creation semantics. Some more recent versions use the permissions specified here as an added security precaution.

Some historical implementations ignore SIGQUIT in addition to SIGHUP; others ignore SIGTERM. An early proposal allowed, but did not require, SIGQUIT to be ignored. Several reviewers objected that nohup should only modify the handling of SIGHUP as required by this volume of IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

Shell Command Language , sh , the System Interfaces volume of IEEE Std 1003.1-2001, signal()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


printf(1p)

PRINTF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

printf - write formatted output

SYNOPSIS

printf format[argument...]

DESCRIPTION

The printf utility shall write formatted operands to the standard output. The argument operands shall be formatted under control of the format operand.

OPTIONS

None.

OPERANDS

The following operands shall be supported:

format
A string describing the format to use to write the remaining operands. See the EXTENDED DESCRIPTION section.
argument
The strings to be written to standard output, under the control of format. See the EXTENDED DESCRIPTION section.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of printf:

LANG
Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)
LC_ALL
If set to a non-empty string value, override the values of all the other internationalization variables.
LC_CTYPE
Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
LC_MESSAGES
Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
LC_NUMERIC

Determine the locale for numeric formatting. It shall affect the format of numbers written using the e , E , f , g , and G conversion specifier characters (if supported).

NLSPATH
Determine the location of message catalogs for the processing of LC_MESSAGES .

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the EXTENDED DESCRIPTION section.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

The format operand shall be used as the format string described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation with the following exceptions:

1.
A <space> in the format string, in any context other than a flag of a conversion specification, shall be treated as an ordinary character that is copied to the output.

2.
A ' ' character in the format string shall be treated as a ' ' character, not as a <space>.

3.
In addition to the escape sequences shown in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ), "\ddd" , where ddd is a one, two, or three-digit octal number, shall be written as a byte with the numeric value specified by the octal number.

4.
The implementation shall not precede or follow output from the d or u conversion specifiers with <blank>s not specified by the format operand.

5.
The implementation shall not precede output from the o conversion specifier with zeros not specified by the format operand.

6.
The e , E , f , g , and G conversion specifiers need not be supported.

7.
An additional conversion specifier character, b , shall be supported as follows. The argument shall be taken to be a string that may contain backslash-escape sequences. The following backslash-escape sequences shall be supported:
*
The escape sequences listed in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation ( '\\' , '\a' , '\b' , '\f' , '\n' , '\r' , '\t' , '\v' ), which shall be converted to the characters they represent

*
"\0ddd" , where ddd is a zero, one, two, or three-digit octal number that shall be converted to a byte with the numeric value specified by the octal number

*
'\c' , which shall not be written and shall cause printf to ignore any remaining characters in the string operand containing it, any remaining string operands, and any additional characters in the format operand

The interpretation of a backslash followed by any other sequence of characters is unspecified.

Bytes from the converted string shall be written until the end of the string or the number of bytes indicated by the precision specification is reached. If the precision is omitted, it shall be taken to be infinite, so all bytes up to the end of the converted string shall be written.

8.
For each conversion specification that consumes an argument, the next argument operand shall be evaluated and converted to the appropriate type for the conversion as specified below.

9.
The format operand shall be reused as often as necessary to satisfy the argument operands. Any extra c or s conversion specifiers shall be evaluated as if a null string argument were supplied; other extra conversion specifications shall be evaluated as if a zero argument were supplied. If the format operand contains no conversion specifications and argument operands are present, the results are unspecified.

10.
If a character sequence in the format operand begins with a '%' character, but does not form a valid conversion specification, the behavior is unspecified.

The argument operands shall be treated as strings if the corresponding conversion specifier is b , c , or s ; otherwise, it shall be evaluated as a C constant, as described by the ISO C standard, with the following extensions:

*
A leading plus or minus sign shall be allowed.

*
If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote.

If an argument operand cannot be completely converted into an internal value appropriate to the corresponding conversion specification, a diagnostic message shall be written to standard error and the utility shall not exit with a zero exit status, but shall continue processing any remaining operands and shall write the value accumulated at the time the error was detected to standard output.

It is not considered an error if an argument operand is not completely used for a c or s conversion or if a string operand's first or second character is used to get the numeric value of a character.

EXIT STATUS

The following exit values shall be returned:

0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.

The following sections are informative.

APPLICATION USAGE

The floating-point formatting conversion specifications of printf() are not required because all arithmetic in the shell is integer arithmetic. The awk utility performs floating-point calculations and provides its own printf function. The bc utility can perform arbitrary-precision floating-point arithmetic, but does not provide extensive formatting capabilities. (This printf utility cannot really be used to format bc output; it does not support arbitrary precision.) Implementations are encouraged to support the floating-point conversions as an extension.

Note that this printf utility, like the printf() function defined in the System Interfaces volume of IEEE Std 1003.1-2001 on which it is based, makes no special provision for dealing with multi-byte characters when using the %c conversion specification or when a precision is specified in a %b or %s conversion specification. Applications should be extremely cautious using either of these features when there are multi-byte characters in the character set.

No provision is made in this volume of IEEE Std 1003.1-2001 which allows field widths and precisions to be specified as '*' since the '*' can be replaced directly in the format operand using shell variable substitution. Implementations can also provide this feature as an extension if they so choose.

Hexadecimal character constants as defined in the ISO C standard are not recognized in the format operand because there is no consistent way to detect the end of the constant. Octal character constants are limited to, at most, three octal digits, but hexadecimal character constants are only terminated by a non-hex-digit character. In the ISO C standard, the "##" concatenation operator can be used to terminate a constant and follow it with a hexadecimal character to be written. In the shell, concatenation occurs before the printf utility has a chance to parse the end of the hexadecimal constant.

The %b conversion specification is not part of the ISO C standard; it has been added here as a portable way to process backslash escapes expanded in string operands as provided by the echo utility. See also the APPLICATION USAGE section of echo for ways to use printf as a replacement for all of the traditional versions of the echo utility.

If an argument cannot be parsed correctly for the corresponding conversion specification, the printf utility is required to report an error. Thus, overflow and extraneous characters at the end of an argument being used for a numeric conversion shall be reported as errors.

EXAMPLES

To alert the user and then print and read a series of prompts:

printf "\aPlease fill in the following: \nName: "
read name
printf "Phone number: "
read phone

To read out a list of right and wrong answers from a file, calculate the percentage correctly, and print them out. The numbers are right-justified and separated by a single <tab>. The percentage is written to one decimal place of accuracy:

while read right wrong ; do
    percent=$(echo "scale=1;($right*100)/($right+$wrong)" | bc)
    printf "%2d right\t%2d wrong\t(%s%%)\n" \
        $right $wrong $percent
done < database_file
The command:

printf "%5d%4d\n" 1 21 321 4321 54321

produces:

   1  21
  3214321
54321   0

Note that the format operand is used three times to print all of the given strings and that a '0' was supplied by printf to satisfy the last %4d conversion specification.

The printf utility is required to notify the user when conversion errors are detected while producing numeric output; thus, the following results would be expected on an implementation with 32-bit twos-complement integers when %d is specified as the format operand:
 | Standard |
Argument | Output | Diagnostic Output
5a | 5 | printf: "5a" not completely converted
9999999999 | 2147483647 | printf: "9999999999" arithmetic overflow
-9999999999 | -2147483648 | printf: "-9999999999" arithmetic overflow
ABC | 0 | printf: "ABC" expected numeric value

The diagnostic message format is not specified, but these examples convey the type of information that should be reported. Note that the value shown on standard output is what would be expected as the return value from the strtol() function as defined in the System Interfaces volume of IEEE Std 1003.1-2001. A similar correspondence exists between %u and strtoul() and %e , %f , and %g (if the implementation supports floating-point conversions) and strtod().

In a locale using the ISO/IEC 646:1991 standard as the underlying codeset, the command:

printf "%d\n" 3 +3 -3 \'3 \"+3 "'-3"

produces:

3
Numeric value of constant 3
3
Numeric value of constant 3
-3
Numeric value of constant -3
51
Numeric value of the character '3' in the ISO/IEC 646:1991 standard codeset
43
Numeric value of the character '+' in the ISO/IEC 646:1991 standard codeset
45
Numeric value of the character '-' in the ISO/IEC 646:1991 standard codeset

Note that in a locale with multi-byte characters, the value of a character is intended to be the value of the equivalent of the wchar_t representation of the character as described in the System Interfaces volume of IEEE Std 1003.1-2001.

RATIONALE

The printf utility was added to provide functionality that has historically been provided by echo. However, due to irreconcilable differences in the various versions of echo extant, the version has few special features, leaving those to this new printf utility, which is based on one in the Ninth Edition system.

The EXTENDED DESCRIPTION section almost exactly matches the printf() function in the ISO C standard, although it is described in terms of the file format notation in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 5, File Format Notation.

FUTURE DIRECTIONS

None.

SEE ALSO

awk , bc , echo , the System Interfaces volume of IEEE Std 1003.1-2001, printf()

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


_exit(2)

_EXIT

Section: Linux Programmer's Manual (2)
Updated: 2001-11-17 Return to Main Contents

NAME

_exit, _Exit - terminate the current process

SYNOPSIS

#include <unistd.h>

void _exit(int status);

#include <stdlib.h>

void _Exit(int status);

DESCRIPTION

The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal.

The value status is returned to the parent process as the process's exit status, and can be collected using one of the wait(2) family of calls.

The function _Exit() is equivalent to _exit().

RETURN VALUE

These functions do not return.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD. The function _Exit() was introduced by C99.

NOTES

For a discussion on the effects of an exit, the transmission of exit status, zombie processes, signals sent, etc., see exit(3).

The function _exit() is like exit(3), but does not call any functions registered with atexit(3) or on_exit(3). Whether it flushes standard I/O buffers and removes temporary files created with tmpfile(3) is implementation dependent. On the other hand, _exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish. If the delay is undesired, it may be useful to call functions like tcflush(3) before calling _exit(). Whether any pending I/O is canceled, and which pending I/O may be canceled upon _exit(), is implementation-dependent.

SEE ALSO

execve(2), exit_group(2), fork(2), kill(2), wait(2), wait4(2), waitpid(2), atexit(3), exit(3), on_exit(3), termios(3)


bdflush(2)

BDFLUSH

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

bdflush - start, flush, or tune buffer-dirty-flush daemon

SYNOPSIS

#include <sys/kdaemon.h>

int bdflush(int func, long *address);
int bdflush(int func, long data);

DESCRIPTION

bdflush() starts, flushes, or tunes the buffer-dirty-flush daemon. Only a privileged process (one with the CAP_SYS_ADMIN capability) may call bdflush().

If func is negative or 0, and no daemon has been started, then bdflush() enters the daemon code and never returns.

If func is 1, some dirty buffers are written to disk.

If func is 2 or more and is even (low bit is 0), then address is the address of a long word, and the tuning parameter numbered (func-2)/2 is returned to the caller in that address.

If func is 3 or more and is odd (low bit is 1), then data is a long word, and the kernel sets tuning parameter numbered (func-3)/2 to that value.

The set of parameters, their values, and their legal ranges are defined in the kernel source file fs/buffer.c.

RETURN VALUE

If func is negative or 0 and the daemon successfully starts, bdflush() never returns. Otherwise, the return value is 0 on success and -1 on failure, with errno set to indicate the error.

ERRORS

EBUSY
An attempt was made to enter the daemon code after another process has already entered.
EFAULT
address points outside your accessible address space.
EINVAL
An attempt was made to read or write an invalid parameter number, or to write an invalid value to a parameter.
EPERM
Caller does not have the CAP_SYS_ADMIN capability.

CONFORMING TO

bdflush() is Linux specific and should not be used in programs intended to be portable.

SEE ALSO

fsync(2), sync(2), sync(8), update(8)


chdir(2)

CHDIR

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

chdir, fchdir - change working directory

SYNOPSIS

#include <unistd.h>

int chdir(const char *path);
int fchdir(int fd);

DESCRIPTION

chdir() changes the current working directory to that specified in path.

fchdir() is identical to chdir(); the only difference is that the directory is given as an open file descriptor.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

Depending on the file system, other errors can be returned. The more general errors for chdir() are listed below:
EACCES
Search permission is denied for one of the directories in the path prefix of path. (See also path_resolution(7).)
EFAULT
path points outside your accessible address space.
EIO
An I/O error occurred.
ELOOP
Too many symbolic links were encountered in resolving path.
ENAMETOOLONG
path is too long.
ENOENT
The file does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of path is not a directory.

The general errors for fchdir() are listed below:

EACCES
Search permission was denied on the directory open on fd.
EBADF
fd is not a valid file descriptor.

CONFORMING TO

SVr4, 4.4BSD, POSIX.1-2001.

NOTES

A child process created via fork(2) inherits its parent's current working directory. The current working directory is left unchanged by execve(2).

The prototype for fchdir() is only available if _BSD_SOURCE is defined, or _XOPEN_SOURCE is defined with the value 500.

SEE ALSO

chroot(2), getcwd(3), path_resolution(7)


accept(2)

ACCEPT

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

accept - accept a connection on a socket

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

DESCRIPTION

The accept() system call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections, creates a new connected socket, and returns a new file descriptor referring to that socket. The newly created socket is not in the listening state. The original socket sockfd is unaffected by this call.

The argument sockfd is a socket that has been created with socket(2), bound to a local address with bind(2), and is listening for connections after a listen(2).

The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returned addr is determined by the socket's address family (see socket(2) and the respective protocol man pages). The addrlen argument is a value-result argument: it should initially contain the size of the structure pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. When addr is NULL nothing is filled in.

If no pending connections are present on the queue, and the socket is not marked as non-blocking, accept() blocks the caller until a connection is present. If the socket is marked non-blocking and no pending connections are present on the queue, accept() fails with the error EAGAIN.

In order to be notified of incoming connections on a socket, you can use select(2) or poll(2). A readable event will be delivered when a new connection is attempted and you may then call accept() to get a socket for that connection. Alternatively, you can set the socket to deliver SIGIO when activity occurs on a socket; see socket(7) for details.

For certain protocols which require an explicit confirmation, such as DECNet, accept() can be thought of as merely dequeuing the next connection request and not implying confirmation. Confirmation can be implied by a normal read or write on the new file descriptor, and rejection can be implied by closing the new socket. Currently only DECNet has these semantics on Linux.

RETURN VALUE

On success, accept() returns a non-negative integer that is a descriptor for the accepted socket. On error, -1 is returned, and errno is set appropriately.

Error Handling

Linux accept() passes already-pending network errors on the new socket as an error code from accept(). This behavior differs from other BSD socket implementations. For reliable operation the application should detect the network errors defined for the protocol after accept() and treat them like EAGAIN by retrying. In case of TCP/IP these are ENETDOWN, EPROTO, ENOPROTOOPT, EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH.

ERRORS

accept() shall fail if:
EAGAIN or EWOULDBLOCK
The socket is marked non-blocking and no connections are present to be accepted.
EBADF
The descriptor is invalid.
ECONNABORTED
A connection has been aborted.
EINTR
The system call was interrupted by a signal that was caught before a valid connection arrived.
EINVAL
Socket is not listening for connections, or addrlen is invalid (e.g., is negative).
EMFILE
The per-process limit of open file descriptors has been reached.
ENFILE
The system limit on the total number of open files has been reached.
ENOTSOCK
The descriptor references a file, not a socket.
EOPNOTSUPP
The referenced socket is not of type SOCK_STREAM.

accept() may fail if:

EFAULT
The addr argument is not in a writable part of the user address space.
ENOBUFS, ENOMEM
Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory.
EPROTO
Protocol error.

Linux accept() may fail if:

EPERM
Firewall rules forbid connection.

In addition, network errors for the new socket and as defined for the protocol may be returned. Various Linux kernels can return other errors such as ENOSR, ESOCKTNOSUPPORT, EPROTONOSUPPORT, ETIMEDOUT. The value ERESTARTSYS may be seen during a trace.

CONFORMING TO

SVr4, 4.4BSD, (accept() first appeared in 4.2BSD), POSIX.1-2001.

On Linux, the new socket returned by accept() does not inherit file status flags such as O_NONBLOCK and O_ASYNC from the listening socket. This behavior differs from the canonical BSD sockets implementation. Portable programs should not rely on inheritance or non-inheritance of file status flags and always explicitly set all required flags on the socket returned from accept().

NOTES

There may not always be a connection waiting after a SIGIO is delivered or select(2) or poll(2) return a readability event because the connection might have been removed by an asynchronous network error or another thread before accept() is called. If this happens then the call will block waiting for the next connection to arrive. To ensure that accept() never blocks, the passed socket sockfd needs to have the O_NONBLOCK flag set (see socket(7)).

The socklen_t type

The third argument of accept() was originally declared as an `int *' (and is that under libc4 and libc5 and on many other systems like 4.x BSD, SunOS 4, SGI); a POSIX.1g draft standard wanted to change it into a `size_t *', and that is what it is for SunOS 5. Later POSIX drafts have `socklen_t *', and so do the Single Unix Specification and glibc2. Quoting Linus Torvalds:

"_Any_ sane library _must_ have "socklen_t" be the same size as int. Anything else breaks any BSD socket layer stuff. POSIX initially did make it a size_t, and I (and hopefully others, but obviously not too many) complained to them very loudly indeed. Making it a size_t is completely broken, exactly because size_t very seldom is the same size as "int" on 64-bit architectures, for example. And it has to be the same size as "int" because that's what the BSD socket interface is. Anyway, the POSIX people eventually got a clue, and created "socklen_t". They shouldn't have touched it in the first place, but once they did they felt it had to have a named type for some unfathomable reason (probably somebody didn't like losing face over having done the original stupid thing, so they silently just renamed their blunder)."

EXAMPLE

See bind(2).

SEE ALSO

bind(2), connect(2), listen(2), select(2), socket(2)


connect(2)

CONNECT

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

connect - initiate a connection on a socket

SYNOPSIS

#include <sys/types.h>

#include <sys/socket.h>

int connect(int sockfd, const struct sockaddr *serv_addr,
            socklen_t addrlen);

DESCRIPTION

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by serv_addr. The addrlen argument specifies the size of serv_addr. The format of the address in serv_addr is determined by the address space of the socket sockfd; see socket(2) for further details.

If the socket sockfd is of type SOCK_DGRAM then serv_addr is the address to which datagrams are sent by default, and the only address from which datagrams are received. If the socket is of type SOCK_STREAM or SOCK_SEQPACKET, this call attempts to make a connection to the socket that is bound to the address specified by serv_addr.

Generally, connection-based protocol sockets may successfully connect() only once; connectionless protocol sockets may use connect() multiple times to change their association. Connectionless sockets may dissolve the association by connecting to an address with the sa_family member of sockaddr set to AF_UNSPEC.

RETURN VALUE

If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

The following are general socket errors only. There may be other domain-specific error codes.
EACCES
For Unix domain sockets, which are identified by pathname: Write permission is denied on the socket file, or search permission is denied for one of the directories in the path prefix. (See also path_resolution(7).)
EACCES, EPERM
The user tried to connect to a broadcast address without having the socket broadcast flag enabled or the connection request failed because of a local firewall rule.
EADDRINUSE
Local address is already in use.
EAFNOSUPPORT
The passed address didn't have the correct address family in its sa_family field.
EAGAIN
No more free local ports or insufficient entries in the routing cache. For PF_INET see the net.ipv4.ip_local_port_range sysctl in ip(7) on how to increase the number of local ports.
EALREADY
The socket is non-blocking and a previous connection attempt has not yet been completed.
EBADF
The file descriptor is not a valid index in the descriptor table.
ECONNREFUSED
No one listening on the remote address.
EFAULT
The socket structure address is outside the user's address space.
EINPROGRESS
The socket is non-blocking and the connection cannot be completed immediately. It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select(2) indicates writability, use getsockopt(2) to read the SO_ERROR option at level SOL_SOCKET to determine whether connect() completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).
EINTR
The system call was interrupted by a signal that was caught.
EISCONN
The socket is already connected.
ENETUNREACH
Network is unreachable.
ENOTSOCK
The file descriptor is not associated with a socket.
ETIMEDOUT
Timeout while attempting connection. The server may be too busy to accept new connections. Note that for IP sockets the timeout may be very long when syncookies are enabled on the server.

CONFORMING TO

SVr4, 4.4BSD, (the connect() function first appeared in 4.2BSD), POSIX.1-2001.

NOTES

The third argument of connect() is in reality an int (and this is what 4.x BSD and libc4 and libc5 have). Some POSIX confusion resulted in the present socklen_t, also used by glibc. See also accept(2).

BUGS

Unconnecting a socket by calling connect() with a AF_UNSPEC address is not yet implemented.

EXAMPLE

An example of the use of connect() is shown in getaddrinfo(3).

SEE ALSO

accept(2), bind(2), getsockname(2), listen(2), socket(2), path_resolution(7)


creat (2)

 Continue to this page.


dup2 (2)

 Continue to this page.


execve(2)

EXECVE

Section: Linux Programmer's Manual (2)
Updated: 2006-09-04 Return to Main Contents

NAME

execve - execute program

SYNOPSIS

#include <unistd.h>

int execve(const char *filename, char *const argv[],
char *const envp[]);

DESCRIPTION

execve() executes the program pointed to by filename. filename must be either a binary executable, or a script starting with a line of the form:

#! interpreter [optional-arg]

For details of the latter case, see "Interpreter scripts" below.

argv is an array of argument strings passed to the new program. envp is an array of strings, conventionally of the form key=value, which are passed as environment to the new program. Both argv and envp must be terminated by a null pointer. The argument vector and environment can be accessed by the called program's main function, when it is defined as:

int main(int argc, char *argv[], char *envp[]).

execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded.

If the current program is being ptraced, a SIGTRAP is sent to it after a successful execve().

If the set-user-ID bit is set on the program file pointed to by filename, and the underlying file system is not mounted nosuid (the MS_NOSUID flag for mount(2)), and the calling process is not being ptraced, then the effective user ID of the calling process is changed to that of the owner of the program file. Similarly, when the set-group-ID bit of the program file is set the effective group ID of the calling process is set to the group of the program file.

The effective user ID of the process is copied to the saved set-user-ID; similarly, the effective group ID is copied to the saved set-group-ID. This copying takes place after any effective ID changes that occur because of the set-user-ID and set-group-ID permission bits.

If the executable is an a.out dynamically-linked binary executable containing shared-library stubs, the Linux dynamic linker ld.so(8) is called at the start of execution to bring needed shared libraries into memory and link the executable with them.

If the executable is a dynamically-linked ELF executable, the interpreter named in the PT_INTERP segment is used to load the needed shared libraries. This interpreter is typically /lib/ld-linux.so.1 for binaries linked with the Linux libc version 5, or /lib/ld-linux.so.2 for binaries linked with the GNU libc version 2.

All process attributes are preserved during an execve(), except the following:

*
The set of pending signals is cleared (sigpending(2)).
*
The dispositions of any signals that are being caught are reset to being ignored.
*
Any alternate signal stack is not preserved (sigaltstack(2)).
*
Memory mappings are not preserved (mmap(2)).
*
Attached System V shared memory segments are detached (shmat(2)).
*
POSIX shared memory regions are unmapped (shm_open(3)).
*
Open POSIX message queue descriptors are closed (mq_overview(7)).
*
Any open POSIX named semaphores are closed (sem_overview(7)).
*
POSIX timers are not preserved (timer_create(3)).
*
Any open directory streams are closed (opendir(3)).
*
Memory locks are not preserved (mlock(2), mlockall(2)).
*
Exit handlers are not preserved (atexit(3), on_exit(3)).

The process attributes in the preceding list are all specified in POSIX.1-2001. The following Linux-specific process attributes are also not preserved during an execve():

*
The prctl(2) PR_SET_DUMPABLE flag is set, unless a set-user-ID or set-group ID program is being executed, in which case it is cleared.
*
The prctl(2) PR_SET_KEEPCAPS flag is cleared.
*
The process name, as set by prctl(2) PR_SET_NAME (and displayed by ps -o comm), is reset to the name of the new executable file.
*
The termination signal is reset to SIGCHLD (see clone(2)).

Note the following further points:

*
All threads other than the calling thread are destroyed during an execve(). Mutexes, condition variables, and other pthreads objects are not preserved.
*
The equivalent of setlocale(LC_ALL, "C") is executed at program start-up.
*
POSIX.1-2001 specifies that the dispositions of any signals that are ignored or set to the default are left unchanged. POSIX.1-2001 specifies one exception: if SIGCHLD is being ignored, then an implementation may leave the disposition unchanged or reset it to the default; Linux does the former.
*
Any outstanding asynchronous I/O operations are canceled (aio_read(3), aio_write(3)).
*
For the handling of capabilities during execve(2), see capabilities(7).
*
By default, file descriptors remain open across an execve(). File descriptors that are marked close-on-exec are closed ; see the description of FD_CLOEXEC in fcntl(2). (If a file descriptor is closed, this will cause the release of all record locks obtained on the underlying file by this process. See fcntl(2) for details.) POSIX.1-2001 says that if file descriptors 0, 1, and 2 would otherwise be closed after a successful execve(), and the process would gain privilege because the set-user_ID or set-group_ID permission bit was set on the executed file, then the system may open an unspecified file for each of these file descriptors. As a general principle, no portable program, whether privileged or not, can assume that these three file descriptors will remain closed across an execve().

Interpreter scripts

An interpreter script is a text file that has execute permission enabled and whose first line is of the form:

#! interpreter [optional-arg]

The interpreter must be a valid pathname for an executable which is not itself a script. If the filename argument of execve() specifies an interpreter script, then interpreter will be invoked with the following arguments:

interpreter [optional-arg] filename arg...

where arg... is the series of words pointed to by the argv argument of execve().

For portable use, optional-arg should either be absent, or be specified as a single word (i.e., it should not contain white space); see NOTES below.

RETURN VALUE

On success, execve() does not return, on error -1 is returned, and errno is set appropriately.

ERRORS

E2BIG
The total number of bytes in the environment (envp) and argument list (argv) is too large.
EACCES
Search permission is denied on a component of the path prefix of filename or the name of a script interpreter. (See also path_resolution(7).)
EACCES
The file or a script interpreter is not a regular file.
EACCES
Execute permission is denied for the file or a script or ELF interpreter.
EACCES
The file system is mounted noexec.
EFAULT
filename points outside your accessible address space.
EINVAL
An ELF executable had more than one PT_INTERP segment (i.e., tried to name more than one interpreter).
EIO
An I/O error occurred.
EISDIR
An ELF interpreter was a directory.
ELIBBAD
An ELF interpreter was not in a recognized format.
ELOOP
Too many symbolic links were encountered in resolving filename or the name of a script or ELF interpreter.
EMFILE
The process has the maximum number of files open.
ENAMETOOLONG
filename is too long.
ENFILE
The system limit on the total number of open files has been reached.
ENOENT
The file filename or a script or ELF interpreter does not exist, or a shared library needed for file or interpreter cannot be found.
ENOEXEC
An executable is not in a recognized format, is for the wrong architecture, or has some other format error that means it cannot be executed.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix of filename or a script or ELF interpreter is not a directory.
EPERM
The file system is mounted nosuid, the user is not the superuser, and the file has the set-user-ID or set-group-ID bit set.
EPERM
The process is being traced, the user is not the superuser and the file has the set-user-ID or set-group-ID bit set.
ETXTBSY
Executable was open for writing by one or more processes.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001. POSIX.1-2001 does not document the #! behavior but is otherwise compatible.

NOTES

Set-user-ID and set-group-ID processes can not be ptrace(2)d.

Linux ignores the set-user-ID and set-group-ID bits on scripts.

The result of mounting a filesystem nosuid varies across Linux kernel versions: some will refuse execution of set-user-ID and set-group-ID executables when this would give the user powers she did not have already (and return EPERM), some will just ignore the set-user-ID and set-group-ID bits and exec() successfully.

A maximum line length of 127 characters is allowed for the first line in a #! executable shell script.

The semantics of the optional-arg argument of an interpreter script vary across implementations. On Linux, the entire string following the interpreter name is passed as a single argument to the interpreter, and this string can include white space. However, behavior differs on some other systems. Some systems use the first white space to terminate optional-arg. On some systems, an interpreter script can have multiple arguments, and white spaces in optional-arg are used to delimit the arguments.

On Linux, argv and envp can be specified as NULL, which has the same effect as specifying these arguments as pointers to lists containing a single NULL pointer. Do not take advantage of this misfeature! It is non-standard and non-portable: on most other Unix systems doing this will result in an error.

Historical

With Unix V6 the argument list of an exec() call was ended by 0, while the argument list of main was ended by -1. Thus, this argument list was not directly usable in a further exec() call. Since Unix V7 both are NULL.

EXAMPLE

The following program is designed to execed by the second program below. It just echoes its command-line one per line.

/* myecho.c */

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    int j;

    for (j = 0; j < argc; j++)
        printf("argv[%d]: %s\n", j, argv[j]);

    exit(EXIT_SUCCESS);
}

This program can be used to exec the program named in its command-line argument:

/* execve.c */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

int
main(int argc, char *argv[])
{
    char *newargv[] = { NULL, "hello", "world", NULL };
    char *newenviron[] = { NULL };

    assert(argc == 2);  /* argv[1] identifies
                           program to exec */
    newargv[0] = argv[1];

    execve(argv[1], newargv, newenviron);
    perror("execve");   /* execve() only returns on error */
    exit(EXIT_FAILURE);
}

We can use the second program to exec the first as follows:

$ cc myecho.c -o myecho
$ cc execve.c -o execve
$ ./execve ./myecho
argv[0]: ./myecho
argv[1]: hello
argv[2]: world

We can also use these programs to demonstrate the use of a script interpreter. To do this we create a script whose "interpreter" is our myecho program:

$ cat > script.sh
#! ./myecho script-arg
^D
$ chmod +x script.sh

We can then use our program to exec the script:

$ ./execve ./script.sh
argv[0]: ./myecho
argv[1]: script-arg
argv[2]: ./script.sh
argv[3]: hello
argv[4]: world

SEE ALSO

chmod(2), fork(2), ptrace(2), execl(3), fexecve(3), environ(7), credentials(7), path_resolution(7), ld.so(8)


exit (2)

 Continue to this page.


fchown (2)

 Continue to this page.


fcntl(2)

FCNTL

Section: Linux Programmer's Manual (2)
Updated: 2005-05-20 Return to Main Contents

NAME

fcntl - manipulate file descriptor

SYNOPSIS

#include <unistd.h>
#include <fcntl.h>

int fcntl(int fd, int cmd);
int fcntl(int fd, int cmd, long arg);
int fcntl(int fd, int cmd, struct flock *lock);

DESCRIPTION

fcntl() performs one of the operations described below on the open file descriptor fd. The operation is determined by cmd.

Duplicating a file descriptor

F_DUPFD
Find the lowest numbered available file descriptor greater than or equal to arg and make it be a copy of fd. This is different from dup2(2) which uses exactly the descriptor specified.

On success, the new descriptor is returned.

See dup(2) for further details.

File descriptor flags

The following commands manipulate the flags associated with a file descriptor. Currently, only one such flag is defined: FD_CLOEXEC, the close-on-exec flag. If the FD_CLOEXEC bit is 0, the file descriptor will remain open across an execve(2), otherwise it will be closed.
F_GETFD
Read the file descriptor flags.
F_SETFD
Set the file descriptor flags to the value specified by arg.

File status flags

Each open file description has certain associated status flags, initialized by open(2) and possibly modified by fcntl(2). Duplicated file descriptors (made with dup(2), fcntl(F_DUPFD), fork(2), etc.) refer to the same open file description, and thus share the same file status flags.

The file status flags and their semantics are described in open(2).

F_GETFL
Read the file status flags.
F_SETFL
Set the file status flags to the value specified by arg. File access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags (i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored. On Linux this command can only change the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags.

Advisory locking

F_GETLK, F_SETLK and F_SETLKW are used to acquire, release, and test for the existence of record locks (also known as file-segment or file-region locks). The third argument lock is a pointer to a structure that has at least the following fields (in unspecified order).

struct flock {
    ...
    short l_type;    /* Type of lock: F_RDLCK,
                        F_WRLCK, F_UNLCK */
    short l_whence;  /* How to interpret l_start:
                        SEEK_SET, SEEK_CUR, SEEK_END */
    off_t l_start;   /* Starting offset for lock */
    off_t l_len;     /* Number of bytes to lock */
    pid_t l_pid;     /* PID of process blocking our lock
                        (F_GETLK only) */
    ...
};
The l_whence, l_start, and l_len fields of this structure specify the range of bytes we wish to lock. l_start is the starting offset for the lock, and is interpreted relative to either: the start of the file (if l_whence is SEEK_SET); the current file offset (if l_whence is SEEK_CUR); or the end of the file (if l_whence is SEEK_END). In the final two cases, l_start can be a negative number provided the offset does not lie before the start of the file. l_len is a non-negative integer (but see the NOTES below) specifying the number of bytes to be locked. Bytes past the end of the file may be locked, but not bytes before the start of the file. Specifying 0 for l_len has the special meaning: lock all bytes starting at the location specified by l_whence and l_start through to the end of file, no matter how large the file grows. The l_type field can be used to place a read (F_RDLCK) or a write (F_WRLCK) lock on a file. Any number of processes may hold a read lock (shared lock) on a file region, but only one process may hold a write lock (exclusive lock). An exclusive lock excludes all other locks, both shared and exclusive. A single process can hold only one type of lock on a file region; if a new lock is applied to an already-locked region, then the existing lock is converted to the new lock type. (Such conversions may involve splitting, shrinking, or coalescing with an existing lock if the byte range specified by the new lock does not precisely coincide with the range of the existing lock.)
F_SETLK
Acquire a lock (when l_type is F_RDLCK or F_WRLCK) or release a lock (when l_type is F_UNLCK) on the bytes specified by the l_whence, l_start, and l_len fields of lock. If a conflicting lock is held by another process, this call returns -1 and sets errno to EACCES or EAGAIN.
F_SETLKW
As for F_SETLK, but if a conflicting lock is held on the file, then wait for that lock to be released. If a signal is caught while waiting, then the call is interrupted and (after the signal handler has returned) returns immediately (with return value -1 and errno set to EINTR).
F_GETLK
On input to this call, lock describes a lock we would like to place on the file. If the lock could be placed, fcntl() does not actually place it, but returns F_UNLCK in the l_type field of lock and leaves the other fields of the structure unchanged. If one or more incompatible locks would prevent this lock being placed, then fcntl() returns details about one of these locks in the l_type, l_whence, l_start, and l_len fields of lock and sets l_pid to be the PID of the process holding that lock. In order to place a read lock, fd must be open for reading. In order to place a write lock, fd must be open for writing. To place both types of lock, open a file read-write. As well as being removed by an explicit F_UNLCK, record locks are automatically released when the process terminates or if it closes any file descriptor referring to a file on which locks are held. This is bad: it means that a process can lose the locks on a file like /etc/passwd or /etc/mtab when for some reason a library function decides to open, read and close it. Record locks are not inherited by a child created via fork(2), but are preserved across an execve(2). Because of the buffering performed by the stdio(3) library, the use of record locking with routines in that package should be avoided; use read(2) and write(2) instead.

Mandatory locking

(Non-POSIX.) The above record locks may be either advisory or mandatory, and are advisory by default.

Advisory locks are not enforced and are useful only between cooperating processes.

Mandatory locks are enforced for all processes. If a process tries to perform an incompatible access (e.g., read(2) or write(2)) on a file region that has an incompatible mandatory lock, then the result depends upon whether the O_NONBLOCK flag is enabled for its open file description. If the O_NONBLOCK flag is not enabled, then system call is blocked until the lock is removed or converted to a mode that is compatible with the access. If the O_NONBLOCK flag is enabled, then the system call fails with the error EAGAIN or EWOULDBLOCK.

To make use of mandatory locks, mandatory locking must be enabled both on the file system that contains the file to be locked, and on the file itself. Mandatory locking is enabled on a file system using the "-o mand" option to mount(8), or the MS_MANDLOCK flag for mount(2). Mandatory locking is enabled on a file by disabling group execute permission on the file and enabling the set-group-ID permission bit (see chmod(1) and chmod(2)).

Managing signals

F_GETOWN, F_SETOWN, F_GETSIG and F_SETSIG are used to manage I/O availability signals:
F_GETOWN
Get the process ID or process group currently receiving SIGIO and SIGURG signals for events on file descriptor fd. Process IDs are returned as positive values; process group IDs are returned as negative values (but see BUGS below).
F_SETOWN
Set the process ID or process group ID that will receive SIGIO and SIGURG signals for events on file descriptor fd. A process ID is specified as a positive value; a process group ID is specified as a negative value. Most commonly, the calling process specifies itself as the owner (that is, arg is specified as getpid(2)).

If you set the O_ASYNC status flag on a file descriptor by using the F_SETFL command of fcntl()), a SIGIO signal is sent whenever input or output becomes possible on that file descriptor. F_SETSIG can be used to obtain delivery of a signal other than SIGIO. If this permission check fails, then the signal is silently discarded.

Sending a signal to the owner process (group) specified by F_SETOWN is subject to the same permissions checks as are described for kill(2), where the sending process is the one that employs F_SETOWN (but see BUGS below).

If the file descriptor fd refers to a socket, F_SETOWN also selects the recipient of SIGURG signals that are delivered when out-of-band data arrives on that socket. (SIGURG is sent in any situation where select(2) would report the socket as having an "exceptional condition".)

If a non-zero value is given to F_SETSIG in a multi-threaded process running with a threading library that supports thread groups (e.g., NPTL), then a positive value given to F_SETOWN has a different meaning: instead of being a process ID identifying a whole process, it is a thread ID identifying a specific thread within a process. Consequently, it may be necessary to pass F_SETOWN the result of gettid(2) instead of getpid(2) to get sensible results when F_SETSIG is used. (In current Linux threading implementations, a main thread's thread ID is the same as its process ID. This means that a single-threaded program can equally use gettid(2) or getpid(2) in this scenario.) Note, however, that the statements in this paragraph do not apply to the SIGURG signal generated for out-of-band data on a socket: this signal is always sent to either a process or a process group, depending on the value given to F_SETOWN. Note also that Linux imposes a limit on the number of real-time signals that may be queued to a process (see getrlimit(2) and signal(7)) and if this limit is reached, then the kernel reverts to delivering SIGIO, and this signal is delivered to the entire process rather than to a specific thread.

F_GETSIG
Get the signal sent when input or output becomes possible. A value of zero means SIGIO is sent. Any other value (including SIGIO) is the signal sent instead, and in this case additional info is available to the signal handler if installed with SA_SIGINFO.
F_SETSIG
Sets the signal sent when input or output becomes possible. A value of zero means to send the default SIGIO signal. Any other value (including SIGIO) is the signal to send instead, and in this case additional info is available to the signal handler if installed with SA_SIGINFO.

Additionally, passing a non-zero value to F_SETSIG changes the signal recipient from a whole process to a specific thread within a process. See the description of F_SETOWN for more details.

By using F_SETSIG with a non-zero value, and setting SA_SIGINFO for the signal handler (see sigaction(2)), extra information about I/O events is passed to the handler in a siginfo_t structure. If the si_code field indicates the source is SI_SIGIO, the si_fd field gives the file descriptor associated with the event. Otherwise, there is no indication which file descriptors are pending, and you should use the usual mechanisms (select(2), poll(2), read(2) with O_NONBLOCK set etc.) to determine which file descriptors are available for I/O.

By selecting a real time signal (value >= SIGRTMIN), multiple I/O events may be queued using the same signal numbers. (Queuing is dependent on available memory). Extra information is available if SA_SIGINFO is set for the signal handler, as above.

Using these mechanisms, a program can implement fully asynchronous I/O without using select(2) or poll(2) most of the time.

The use of O_ASYNC, F_GETOWN, F_SETOWN is specific to BSD and Linux. F_GETSIG and F_SETSIG are Linux specific. POSIX has asynchronous I/O and the aio_sigevent structure to achieve similar things; these are also available in Linux as part of the GNU C Library (Glibc).

Leases

F_SETLEASE and F_GETLEASE (Linux 2.4 onwards) are used (respectively) to establish and retrieve the current setting of the calling process's lease on the file referred to by fd. A file lease provides a mechanism whereby the process holding the lease (the "lease holder") is notified (via delivery of a signal) when a process (the "lease breaker") tries to open(2) or truncate(2) that file.
F_SETLEASE
Set or remove a file lease according to which of the following values is specified in the integer arg:

F_RDLCK Take out a read lease. This will cause the calling process to be notified when the file is opened for writing or is truncated. A read lease can only be placed on a file descriptor that is opened read-only.
F_WRLCK
Take out a write lease. This will cause the caller to be notified when the file is opened for reading or writing or is truncated. A write lease may be placed on a file only if no other process currently has the file open.
F_UNLCK
Remove our lease from the file.
A process may hold only one type of lease on a file. Leases may only be taken out on regular files. An unprivileged process may only take out a lease on a file whose UID matches the file system UID of the process. A process with the CAP_LEASE capability may take out leases on arbitrary files.
F_GETLEASE
Indicates what type of lease we hold on the file referred to by fd by returning either F_RDLCK, F_WRLCK, or F_UNLCK, indicating, respectively, that the calling process holds a read, a write, or no lease on the file. (The third argument to fcntl() is omitted.)

When a process (the "lease breaker") performs an open(2) or truncate(2) that conflicts with a lease established via F_SETLEASE, the system call is blocked by the kernel and the kernel notifies the lease holder by sending it a signal (SIGIO by default). The lease holder should respond to receipt of this signal by doing whatever cleanup is required in preparation for the file to be accessed by another process (e.g., flushing cached buffers) and then either remove or downgrade its lease. A lease is removed by performing an F_SETLEASE command specifying arg as F_UNLCK. If we currently hold a write lease on the file, and the lease breaker is opening the file for reading, then it is sufficient to downgrade the lease to a read lease. This is done by performing an F_SETLEASE command specifying arg as F_RDLCK.

If the lease holder fails to downgrade or remove the lease within the number of seconds specified in /proc/sys/fs/lease-break-time then the kernel forcibly removes or downgrades the lease holder's lease.

Once the lease has been voluntarily or forcibly removed or downgraded, and assuming the lease breaker has not unblocked its system call, the kernel permits the lease breaker's system call to proceed.

If the lease breaker's blocked open(2) or truncate(2) is interrupted by a signal handler, then the system call fails with the error EINTR, but the other steps still occur as described above. If the lease breaker is killed by a signal while blocked in open(2) or truncate(2), then the other steps still occur as described above. If the lease breaker specifies the O_NONBLOCK flag when calling open(2), then the call immediately fails with the error EWOULDBLOCK, but the other steps still occur as described above.

The default signal used to notify the lease holder is SIGIO, but this can be changed using the F_SETSIG command to fcntl(). If a F_SETSIG command is performed (even one specifying SIGIO), and the signal handler is established using SA_SIGINFO, then the handler will receive a siginfo_t structure as its second argument, and the si_fd field of this argument will hold the descriptor of the leased file that has been accessed by another process. (This is useful if the caller holds leases against multiple files).

File and directory change notification (dnotify)

F_NOTIFY
(Linux 2.4 onwards) Provide notification when the directory referred to by fd or any of the files that it contains is changed. The events to be notified are specified in arg, which is a bit mask specified by ORing together zero or more of the following bits:
Bit Description (event in directory)
DN_ACCESS
DN_MODIFY A file was modified (write, pwrite,
writev, truncate, ftruncate)
DN_CREATE A file was created (open, creat, mknod,
mkdir, link, symlink, rename)
DN_DELETE A file was unlinked (unlink, rename to
another directory, rmdir)
DN_RENAME A file was renamed within this
directory (rename)
DN_ATTRIB The attributes of a file were changed
(chown, chmod, utime[s])

(In order to obtain these definitions, the _GNU_SOURCE feature test macro must be defined.)

Directory notifications are normally "one-shot", and the application must re-register to receive further notifications. Alternatively, if DN_MULTISHOT is included in arg, then notification will remain in effect until explicitly removed.

A series of F_NOTIFY requests is cumulative, with the events in arg being added to the set already monitored. To disable notification of all events, make an F_NOTIFY call specifying arg as 0.

Notification occurs via delivery of a signal. The default signal is SIGIO, but this can be changed using the F_SETSIG command to fcntl(). In the latter case, the signal handler receives a siginfo_t structure as its second argument (if the handler was established using SA_SIGINFO) and the si_fd field of this structure contains the file descriptor which generated the notification (useful when establishing notification on multiple directories).

Especially when using DN_MULTISHOT, a real time signal should be used for notification, so that multiple notifications can be queued.

NOTE: New applications should consider using the inotify interface (available since kernel 2.6.13), which provides a superior interface for obtaining notifications of file system events. See inotify(7).

RETURN VALUE

For a successful call, the return value depends on the operation:
F_DUPFD
The new descriptor.
F_GETFD
Value of flags.
F_GETFL
Value of flags.
F_GETOWN
Value of descriptor owner.
F_GETSIG
Value of signal sent when read or write becomes possible, or zero for traditional SIGIO behavior.
All other commands
Zero.

On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES or EAGAIN
Operation is prohibited by locks held by other processes.
EAGAIN
The operation is prohibited because the file has been memory-mapped by another process.
EBADF
fd is not an open file descriptor, or the command was F_SETLK or F_SETLKW and the file descriptor open mode doesn't match with the type of lock requested.
EDEADLK
It was detected that the specified F_SETLKW command would cause a deadlock.
EFAULT
lock is outside your accessible address space.
EINTR
For F_SETLKW, the command was interrupted by a signal. For F_GETLK and F_SETLK, the command was interrupted by a signal before the lock was checked or acquired. Most likely when locking a remote file (e.g., locking over NFS), but can sometimes happen locally.
EINVAL
For F_DUPFD, arg is negative or is greater than the maximum allowable value. For F_SETSIG, arg is not an allowable signal number.
EMFILE
For F_DUPFD, the process already has the maximum number of file descriptors open.
ENOLCK
Too many segment locks open, lock table is full, or a remote locking protocol failed (e.g., locking over NFS).
EPERM
Attempted to clear the O_APPEND flag on a file that has the append-only attribute set.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001. Only the operations F_DUPFD, F_GETFD, F_SETFD, F_GETFL, F_SETFL, F_GETLK, F_SETLK, F_SETLKW, F_GETOWN, and F_SETOWN are specified in POSIX.1-2001.

F_GETSIG, F_SETSIG, F_NOTIFY, F_GETLEASE, and F_SETLEASE are Linux specific. (Define the _GNU_SOURCE macro to obtain these definitions.)

NOTES

The errors returned by dup2(2) are different from those returned by F_DUPFD.

Since kernel 2.0, there is no interaction between the types of lock placed by flock(2) and fcntl(2).

POSIX.1-2001 allows l_len to be negative. (And if it is, the interval described by the lock covers bytes l_start+l_len up to and including l_start-1.) This is supported by Linux since Linux 2.4.21 and 2.5.49.

Several systems have more fields in struct flock such as, for example, l_sysid. Clearly, l_pid alone is not going to be very useful if the process holding the lock may live on a different machine.

BUGS

A limitation of the Linux system call conventions on some architectures (notably x86) means that if a (negative) process group ID to be returned by F_GETOWN falls in the range -1 to -4095, then the return value is wrongly interpreted by glibc as an error in the system call; that is, the return value of fcntl() will be -1, and errno will contain the (positive) process group ID.

In Linux 2.4 and earlier, there is bug that can occur when an unprivileged process uses F_SETOWN to specify the owner of a socket file descriptor as a process (group) other than the caller. In this case, fcntl() can return -1 with errno set to EPERM, even when the owner process (group) is one that the caller has permission to send signals to. Despite this error return, the file descriptor owner is set, and signals will be sent to the owner.

SEE ALSO

dup2(2), flock(2), open(2), socket(2), lockf(3), capabilities(7), feature_test_macros(7) See also Documentation/locks.txt, Documentation/mandatory.txt, and Documentation/dnotify.txt in the kernel source.


sgetmask (2)

 Continue to this page.


shmat (2)

 Continue to this page.


getdomainname(2)

GETDOMAINNAME

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

getdomainname, setdomainname - get/set domain name

SYNOPSIS

#include <unistd.h>

int getdomainname(char *name, size_t len);
int setdomainname(const char *name, size_t len);

DESCRIPTION

These functions are used to access or to change the domain name of the current processor. If the null-terminated domain name requires more than len bytes, getdomainname() returns the first len bytes (glibc) or returns an error (libc).

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
For setdomainname(): name pointed outside of user address space.
EINVAL
For getdomainname() under libc: name is NULL or name is longer than len bytes.
EINVAL
For setdomainname(): len was negative or too large.
EPERM
For setdomainname(): the caller is unprivileged (Linux: does not have the CAP_SYS_ADMIN capability).

CONFORMING TO

POSIX does not specify these calls.

SEE ALSO

gethostname(2), sethostname(2), uname(2)


sysfs(2)

SYSFS

Section: Linux Programmer's Manual (2)
Updated: 1995-08-09 Return to Main Contents

NAME

sysfs - get file system type information

SYNOPSIS

int sysfs(int option, const char *fsname);

int sysfs(int option, unsigned int fs_index, char *buf);

int sysfs(int option);

DESCRIPTION

sysfs() returns information about the file system types currently present in the kernel. The specific form of the sysfs() call and the information returned depends on the option in effect:
1
Translate the file-system identifier string fsname into a file-system type index.
2
Translate the file-system type index fs_index into a null-terminated file-system identifier string. This string will be written to the buffer pointed to by buf. Make sure that buf has enough space to accept the string.
3
Return the total number of file system types currently present in the kernel.

The numbering of the file-system type indexes begins with zero.

RETURN VALUE

On success, sysfs() returns the file-system index for option 1, zero for option 2, and the number of currently configured file systems for option 3. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
Either fsname or buf is outside your accessible address space.
EINVAL
fsname is not a valid file-system type identifier; fs_index is out-of-bounds; option is invalid.

CONFORMING TO

SVr4.

NOTES

On Linux with the proc filesystem mounted on /proc, the same information can be derived from /proc/filesystems.

BUGS

There is no libc or glibc support. There is no way to guess how large buf should be.


geteuid (2)

 Continue to this page.


getpgrp (2)

 Continue to this page.


getppid (2)

 Continue to this page.


getpid(2)

GETPID

Section: Linux Programmer's Manual (2)
Updated: 1993-07-23 Return to Main Contents

NAME

getpid, getppid - get process identification

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

pid_t getpid(void);
pid_t getppid(void);

DESCRIPTION

getpid() returns the process ID of the current process. (This is often used by routines that generate unique temporary filenames.)

getppid() returns the process ID of the parent of the current process.

ERRORS

These functions are always successful.

CONFORMING TO

POSIX.1-2001, 4.3BSD, SVr4

SEE ALSO

fork(2), kill(2), exec(3), mkstemp(3), tempnam(3), tmpfile(3), tmpnam(3), credentials(7)


getpriority(2)

GETPRIORITY

Section: Linux Programmer's Manual (2)
Updated: 2002-09-20 Return to Main Contents

NAME

getpriority, setpriority - get/set program scheduling priority

SYNOPSIS

#include <sys/time.h>
#include <sys/resource.h>

int getpriority(int which, int who);
int setpriority(int which, int who, int prio);

DESCRIPTION

The scheduling priority of the process, process group, or user, as indicated by which and who is obtained with the getpriority() call and set with the setpriority() call.

The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. Prio is a value in the range -20 to 19 (but see the Notes below). The default priority is 0; lower priorities cause more favorable scheduling.

The getpriority() call returns the highest priority (lowest numerical value) enjoyed by any of the specified processes. The setpriority() call sets the priorities of all of the specified processes to the specified value. Only the superuser may lower priorities.

RETURN VALUE

Since getpriority() can legitimately return the value -1, it is necessary to clear the external variable errno prior to the call, then check it afterwards to determine if a -1 is an error or a legitimate value. The setpriority() call returns 0 if there is no error, or -1 if there is.

ERRORS

EINVAL
which was not one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER.
ESRCH
No process was located using the which and who values specified.

In addition to the errors indicated above, setpriority() may fail if:

EPERM
A process was located, but its effective user ID did not match either the effective or the real user ID of the caller, and was not privileged (on Linux: did not have the CAP_SYS_NICE capability). But see NOTES below.
EACCES
The caller attempted to lower a process priority, but did not have the required privilege (on Linux: did not have the CAP_SYS_NICE capability). Since Linux 2.6.12, this error only occurs if the caller attempts to set a process priority outside the range of the RLIMIT_NICE soft resource limit of the target process; see getrlimit(2) for details.

CONFORMING TO

SVr4, 4.4BSD (these function calls first appeared in 4.2BSD), POSIX.1-2001.

NOTES

A child created by fork(2) inherits its parent's nice value. The nice value is preserved across execve(2).

The details on the condition for EPERM depend on the system. The above description is what POSIX.1-2001 says, and seems to be followed on all System V-like systems. Linux kernels before 2.6.12 required the real or effective user ID of the caller to match the real user of the process who (instead of its effective user ID). Linux 2.6.12 and later require the effective user ID of the caller to match the real or effective user ID of the process who. All BSD-like systems (SunOS 4.1.3, Ultrix 4.2, 4.3BSD, FreeBSD 4.3, OpenBSD-2.5, ...) behave in the same manner as Linux >= 2.6.12.

The actual priority range varies between kernel versions. Linux before 1.3.36 had -infinity..15. Since kernel 1.3.43 Linux has the range -20..19. Within the kernel, nice values are actually represented using the corresponding range 40..1 (since negative numbers are error codes) and these are the values employed by the setpriority() and getpriority() system calls. The glibc wrapper functions for these system calls handle the translations between the user-land and kernel representations of the nice value according to the formula unice = 20 - knice.

On some systems, the range of nice values is -20..20.

Including <sys/time.h> is not required these days, but increases portability. (Indeed, <sys/resource.h> defines the rusage structure with fields of type struct timeval defined in <sys/time.h>.)

SEE ALSO

nice(1), fork(2), capabilities(7), renice(8)


gettimeofday(2)

GETTIMEOFDAY

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

gettimeofday, settimeofday - get / set time

SYNOPSIS

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv , const struct timezone *tz);

DESCRIPTION

The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone. The tv argument is a struct timeval (as specified in <sys/time.h>):

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

and gives the number of seconds and microseconds since the Epoch (see time(2)). The tz argument is a struct timezone:

struct timezone {
    int tz_minuteswest;     /* minutes west of Greenwich */
    int tz_dsttime;         /* type of DST correction */
};

If either tv or tz is NULL, the corresponding structure is not set or returned.

The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL. The tz_dsttime field has never been used under Linux; it has not been and will not be supported by libc or glibc. Each and every occurrence of this field in the kernel source (other than the declaration) is a bug. Thus, the following is purely of historic interest.

The field tz_dsttime contains a symbolic constant (values are given below) that indicates in which part of the year Daylight Saving Time is in force. (Note: its value is constant throughout the year: it does not indicate that DST is in force, it just selects an algorithm.) The daylight saving time algorithms defined are as follows :

DST_NONE /* not on dst */
DST_USA /* USA style dst */
DST_AUST /* Australian style dst */
DST_WET /* Western European dst */
DST_MET /* Middle European dst */
DST_EET /* Eastern European dst */
DST_CAN /* Canada */
DST_GB /* Great Britain and Eire */
DST_RUM /* Rumania */
DST_TUR /* Turkey */
DST_AUSTALT /* Australian style with shift in 1986 */

Of course it turned out that the period in which Daylight Saving Time is in force cannot be given by a simple algorithm, one per country; indeed, this period is determined by unpredictable political decisions. So this method of representing time zones has been abandoned. Under Linux, in a call to settimeofday() the tz_dsttime field should be zero.

Under Linux there is some peculiar `warp clock' semantics associated to the settimeofday() system call if on the very first call (after booting) that has a non-NULL tz argument, the tv argument is NULL and the tz_minuteswest field is non-zero. In such a case it is assumed that the CMOS clock is on local time, and that it has to be incremented by this amount to get UTC system time. No doubt it is a bad idea to use this feature.

The following macros are defined to operate on a struct timeval:

#define timerisset(tvp)\

        ((tvp)->tv_sec || (tvp)->tv_usec)
#define timercmp(tvp, uvp, cmp)\
((tvp)->tv_sec cmp (uvp)->tv_sec ||\
(tvp)->tv_sec == (uvp)->tv_sec &&\
(tvp)->tv_usec cmp (uvp)->tv_usec)
#define timerclear(tvp)\

        ((tvp)->tv_sec = (tvp)->tv_usec = 0)

RETURN VALUE

gettimeofday() and settimeofday() return 0 for success, or -1 for failure (in which case errno is set appropriately).

ERRORS

EFAULT
One of tv or tz pointed outside the accessible address space.
EINVAL
Timezone (or something else) is invalid.
EPERM
The calling process has insufficient privilege to call settimeofday(); under Linux the CAP_SYS_TIME capability is required.

CONFORMING TO

SVr4, 4.3BSD. POSIX.1-2001 describes gettimeofday() but not settimeofday().

NOTES

The prototype for settimeofday() and the defines for timercmp, timerisset, timerclear, timeradd, timersub are (since glibc 2.2.2) only available if _BSD_SOURCE is defined.

Traditionally, the fields of struct timeval were longs.

SEE ALSO

date(1), adjtimex(2), time(2), ctime(3), ftime(3), capabilities(7), time(7)


gtty (2)

 Continue to this page.


kill(2)

KILL

Section: Linux Programmer's Manual (2)
Updated: 2004-06-24 Return to Main Contents

NAME

kill - send signal to a process

SYNOPSIS

#include <sys/types.h>

#include <signal.h>

int kill(pid_t pid, int sig);

DESCRIPTION

The kill() system call can be used to send any signal to any process group or process.

If pid is positive, then signal sig is sent to pid.

If pid equals 0, then sig is sent to every process in the process group of the current process.

If pid equals -1, then sig is sent to every process for which the calling process has permission to send signals, except for process 1 (init), but see below.

If pid is less than -1, then sig is sent to every process in the process group -pid.

If sig is 0, then no signal is sent, but error checking is still performed.

For a process to have permission to send a signal it must either be privileged (under Linux: have the CAP_KILL capability), or the real or effective user ID of the sending process must equal the real or saved set-user-ID of the target process. In the case of SIGCONT it suffices when the sending and receiving processes belong to the same session.

RETURN VALUE

On success (at least one signal was sent), zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
An invalid signal was specified.
EPERM
The process does not have permission to send the signal to any of the target processes.
ESRCH
The pid or process group does not exist. Note that an existing process might be a zombie, a process which already committed termination, but has not yet been wait(2)ed for.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001

NOTES

The only signals that can be sent process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally.

POSIX.1-2001 requires that kill(-1,sig) send sig to all processes that the current process may send signals to, except possibly for some implementation-defined system processes. Linux allows a process to signal itself, but on Linux the call kill(-1,sig) does not signal the current process.

POSIX.1-2001 requires that if a process sends a signal to itself, and the sending thread does not have the signal blocked, and no other thread has it unblocked or is waiting for it in sigwait(3), at least one unblocked signal must be delivered to the sending thread before the kill().

Linux Notes

Across different kernel versions, Linux has enforced different rules for the permissions required for an unprivileged process to send a signal to another process. In kernels 1.0 to 1.2.2, a signal could be sent if the effective user ID of the sender matched that of the receiver, or the real user ID of the sender matched that of the receiver. From kernel 1.2.3 until 1.3.77, a signal could be sent if the effective user ID of the sender matched either the real or effective user ID of the receiver. The current rules, which conform to POSIX.1-2001, were adopted in kernel 1.3.78.

BUGS

In 2.6 kernels up to and including 2.6.7, there was a bug that meant that when sending signals to a process group, kill() failed with the error EPERM if the caller did have permission to send the signal to any (rather than all) of the members of the process group. Notwithstanding this error return, the signal was still delivered to all of the processes for which the caller had permission to signal.

SEE ALSO

_exit(2), killpg(2), signal(2), sigqueue(2), tkill(2), exit(3), capabilities(7), credentials(7), signal(7)


getsid(2)

GETSID

Section: Linux Programmer's Manual (2)
Updated: 2001-12-17 Return to Main Contents

NAME

getsid - get session ID

SYNOPSIS

#include <unistd.h>

pid_t getsid(pid_t pid);

DESCRIPTION

getsid(0) returns the session ID of the calling process. getsid(p) returns the session ID of the process with process ID p. (The session ID of a process is the process group ID of the session leader.)

RETIRN VALUE

On success, a session ID is returned. On error, (pid_t) -1 will be returned, and errno is set appropriately.

ERRORS

EPERM
A process with process ID p exists, but it is not in the same session as the current process, and the implementation considers this an error.
ESRCH
No process with process ID p was found.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

Linux does not return EPERM.

Linux has this system call since Linux 1.3.44. There is libc support since libc 5.2.19.

To get the prototype under glibc, define both _XOPEN_SOURCE and _XOPEN_SOURCE_EXTENDED, or use "#define _XOPEN_SOURCE n" for some integer n larger than or equal to 500.

SEE ALSO

getpgid(2), setsid(2), credentials(7), feature_test_macros(7)


llseek(2)

LLSEEK

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

_llseek - reposition read/write file offset

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int _llseek(unsigned int fd, unsigned long offset_high,
            unsigned long offset_low, loff_t *result,
            unsigned int whence);

DESCRIPTION

The _llseek() function repositions the offset of the open file associated with the file descriptor fd to (offset_high<<32) | offset_low bytes relative to the beginning of the file, the current position in the file, or the end of the file, depending on whether whence is SEEK_SET, SEEK_CUR, or SEEK_END, respectively. It returns the resulting file position in the argument result.

RETURN VALUE

Upon successful completion, _llseek() returns 0. Otherwise, a value of -1 is returned and errno is set to indicate the error.

ERRORS

EBADF
fd is not an open file descriptor.
EFAULT
Problem with copying results to user space.
EINVAL
whence is invalid.

CONFORMING TO

This function is Linux specific, and should not be used in programs intended to be portable.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

SEE ALSO

lseek(2), lseek64(3)


lock (2)

 Continue to this page.


lseek(2)

LSEEK

Section: Linux Programmer's Manual (2)
Updated: 2001-09-24 Return to Main Contents

NAME

lseek - reposition read/write file offset

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

off_t lseek(int fildes, off_t offset, int whence);

DESCRIPTION

The lseek() function repositions the offset of the open file associated with the file descriptor fildes to the argument offset according to the directive whence as follows:
SEEK_SET
The offset is set to offset bytes.
SEEK_CUR
The offset is set to its current location plus offset bytes.
SEEK_END
The offset is set to the size of the file plus offset bytes.

The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.

RETURN VALUE

Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. Otherwise, a value of (off_t)-1 is returned and errno is set to indicate the error.

ERRORS

EBADF
fildes is not an open file descriptor.
EINVAL
whence is not one of SEEK_SET, SEEK_CUR, SEEK_END; or the resulting file offset would be negative, or beyond the end of a seekable device.
EOVERFLOW
The resulting file offset cannot be represented in an off_t.
ESPIPE
fildes is associated with a pipe, socket, or FIFO.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

This document's use of whence is incorrect English, but maintained for historical reasons.

Some devices are incapable of seeking and POSIX does not specify which devices must support lseek().

On Linux, using lseek() on a tty device returns ESPIPE.

When converting old code, substitute values for whence with the following macros:
old | new
0 | SEEK_SET
1 | SEEK_CUR
2 | SEEK_END
L_SET | SEEK_SET
L_INCR | SEEK_CUR
L_XTND | SEEK_END

SVr1-3 returns long instead of off_t, BSD returns int.

Note that file descriptors created by dup(2) or fork(2) share the current file position pointer, so seeking on such files may be subject to race conditions.

SEE ALSO

dup(2), fork(2), open(2), fseek(3), lseek64(3), posix_fallocate(3)


lstat (2)

 Continue to this page.


mlock(2)

MLOCK

Section: Linux Programmer's Manual (2)
Updated: 2006-02-04 Return to Main Contents

NAME

mlock, munlock, mlockall, munlockall - lock and unlock memory

SYNOPSIS

#include <sys/mman.h>

int mlock(const void *addr, size_t len);

int munlock(const void *addr, size_t len);

int mlockall(int flags);

int munlockall(void);

DESCRIPTION

mlock() and mlockall() respectively lock part or all of the calling process's virtual address space into RAM, preventing that memory from being paged to the swap area. munlock() and munlockall() perform the converse operation, respectively unlocking part or all of the calling process's virtual address space, so that pages in the specified virtual address range may once more to be swapped out if required by the kernel memory manager. Memory locking and unlocking are performed in units of whole pages.

mlock() and munlock()

mlock() locks pages in the address range starting at addr and continuing for len bytes. All pages that contain a part of the specified address range are guaranteed to be resident in RAM when the call returns successfully; the pages are guaranteed to stay in RAM until later unlocked.

munlock() unlocks pages in the address range starting at addr and continuing for len bytes. After this call, all pages that contain a part of the specified memory range can be moved to external swap space again by the kernel.

mlockall() and munlockall()

mlockall() locks all pages mapped into the address space of the calling process. This includes the pages of the code, data and stack segment, as well as shared libraries, user space kernel data, shared memory, and memory-mapped files. All mapped pages are guaranteed to be resident in RAM when the call returns successfully; the pages are guaranteed to stay in RAM until later unlocked.

The flags argument is constructed as the bitwise OR of one or more of the following constants:

MCL_CURRENT
Lock all pages which are currently mapped into the address space of the process.
MCL_FUTURE
Lock all pages which will become mapped into the address space of the process in the future. These could be for instance new pages required by a growing heap and stack as well as new memory mapped files or shared memory regions.

If MCL_FUTURE has been specified, then a later system call (e.g., mmap(2), sbrk(2), malloc(3)), may fail if it would cause the number of locked bytes to exceed the permitted maximum (see below). In the same circumstances, stack growth may likewise fail: the kernel will deny stack expansion and deliver a SIGSEGV signal to the process.

munlockall() unlocks all pages mapped into the address space of the calling process.

RETURN VALUE

On success these system calls return 0. On error, -1 is returned, errno is set appropriately, and no changes are made to any locks in the address space of the process.

ERRORS

ENOMEM
(Linux 2.6.9 and later) the caller had a non-zero RLIMIT_MEMLOCK soft resource limit, but tried to lock more memory than the limit permitted. This limit is not enforced if the process is privileged (CAP_IPC_LOCK).
ENOMEM
(Linux 2.4 and earlier) the calling process tried to lock more than half of RAM.
EPERM
(Linux 2.6.9 and later) the caller was not privileged (CAP_IPC_LOCK) and its RLIMIT_MEMLOCK soft resource limit was 0.
EPERM
(Linux 2.6.8 and earlier) The calling process has insufficient privilege to call munlockall(). Under Linux the CAP_IPC_LOCK capability is required.

For mlock() and munlock():

EINVAL
len was negative.
EINVAL
(Not on Linux) addr was not a multiple of the page size.
ENOMEM
Some of the specified address range does not correspond to mapped pages in the address space of the process.

For mlockall():

EINVAL
Unknown flags were specified.

For munlockall():

EPERM
(Linux 2.6.8 and earlier) The caller was not privileged (CAP_IPC_LOCK).

CONFORMING TO

POSIX.1-2001, SVr4

AVAILABILITY

On POSIX systems on which mlock() and munlock() are available, _POSIX_MEMLOCK_RANGE is defined in <unistd.h> and the number of bytes in a page can be determined from the constant PAGESIZE (if defined) in <limits.h> or by calling sysconf(_SC_PAGESIZE).

On POSIX systems on which mlockall() and munlockall() are available, _POSIX_MEMLOCK is defined in <unistd.h> to a value greater than 0. (See also sysconf(3).)

NOTES

Memory locking has two main applications: real-time algorithms and high-security data processing. Real-time applications require deterministic timing, and, like scheduling, paging is one major cause of unexpected program execution delays. Real-time applications will usually also switch to a real-time scheduler with sched_setscheduler(2). Cryptographic security software often handles critical bytes like passwords or secret keys as data structures. As a result of paging, these secrets could be transferred onto a persistent swap store medium, where they might be accessible to the enemy long after the security software has erased the secrets in RAM and terminated. (But be aware that the suspend mode on laptops and some desktop computers will save a copy of the system's RAM to disk, regardless of memory locks.)

Real-time processes that are using mlockall() to prevent delays on page faults should reserve enough locked stack pages before entering the time-critical section, so that no page fault can be caused by function calls. This can be achieved by calling a function that allocates a sufficiently large automatic variable (an array) and writes to the memory occupied by this array in order to touch these stack pages. This way, enough pages will be mapped for the stack and can be locked into RAM. The dummy writes ensure that not even copy-on-write page faults can occur in the critical section.

Memory locks are not inherited by a child created via fork(2) and are automatically removed (unlocked) during an execve(2) or when the process terminates.

The memory lock on an address range is automatically removed if the address range is unmapped via munmap(2).

Memory locks do not stack, that is, pages which have been locked several times by calls to mlock() or mlockall() will be unlocked by a single call to munlock() for the corresponding range or by munlockall(). Pages which are mapped to several locations or by several processes stay locked into RAM as long as they are locked at least at one location or by at least one process.

Linux Notes

Under Linux, mlock() and munlock() automatically round addr down to the nearest page boundary. However, POSIX.1-2001 allows an implementation to require that addr is page aligned, so portable applications should ensure this.

Limits and permissions

In Linux 2.6.8 and earlier, a process must be privileged (CAP_IPC_LOCK) in order to lock memory and the RLIMIT_MEMLOCK soft resource limit defines a limit on how much memory the process may lock.

Since Linux 2.6.9, no limits are placed on the amount of memory that a privileged process can lock and the RLIMIT_MEMLOCK soft resource limit instead defines a limit on how much memory an unprivileged process may lock.

BUGS

In the 2.4 series Linux kernels up to and including 2.4.17, a bug caused the mlockall() MCL_FUTURE flag to be inherited across a fork(2). This was rectified in kernel 2.4.18.

Since kernel 2.6.9, if a privileged process calls mlockall(MCL_FUTURE) and later drops privileges (loses the CAP_IPC_LOCK capability by, for example, setting its effective UID to a non-zero value), then subsequent memory allocations (e.g., mmap(2), brk(2)) will fail if the RLIMIT_MEMLOCK resource limit is encountered.

SEE ALSO

mmap(2), shmctl(2), setrlimit(2), sysconf(3), capabilities(7)


mlockall (2)

 Continue to this page.


poll(2)

POLL

Section: Linux Programmer's Manual (2)
Updated: 2006-03-13 Return to Main Contents

NAME

poll, ppoll - wait for some event on a file descriptor

SYNOPSIS

#include <poll.h>

int poll(struct pollfd *fds, nfds_t nfds, int timeout);

#define _GNU_SOURCE
#include <poll.h>

int ppoll(struct pollfd *fds, nfds_t nfds,
        const struct timespec *timeout, const sigset_t *sigmask);

DESCRIPTION

poll() performs a similar task to select(2): it waits for one of a set of file descriptors to become ready to perform I/O.

The set of file descriptors to be monitored is specified in the fds argument, which is an array of nfds structures of the following form:

    struct pollfd {
        int   fd;         /* file descriptor */
        short events;     /* requested events */
        short revents;    /* returned events */
    };
The field fd contains a file descriptor for an open file.

The field events is an input parameter, a bitmask specifying the events the application is interested in.

The field revents is an output parameter, filled by the kernel with the events that actually occurred. The bits returned in revents can include any of those specified in events, or one of the values POLLERR, POLLHUP, or POLLNVAL. (These three bits are meaningless in the events field, and will be set in the revents field whenever the corresponding condition is true.)

If none of the events requested (and no error) has occurred for any of the file descriptors, then poll() blocks until one of the events occurs.

The timeout argument specifies an upper limit on the time for which poll() will block, in milliseconds. Specifying a negative value in timeout means an infinite timeout.

The bits that may be set/returned in events and revents are defined in <poll.h>:

POLLIN
There is data to read.
POLLPRI
There is urgent data to read (e.g., out-of-band data on TCP socket; pseudo-terminal master in packet mode has seen state change in slave).
POLLOUT
Writing now will not block.
POLLRDHUP (since Linux 2.6.17)
Stream socket peer closed connection, or shut down writing half of connection. The _GNU_SOURCE feature test macro must be defined in order to obtain this definition.
POLLERR
Error condition (output only).
POLLHUP
Hang up (output only).
POLLNVAL
Invalid request: fd not open (output only).

When compiling with _XOPEN_SOURCE defined, one also has the following, which convey no further information beyond the bits listed above:

POLLRDNORM
Equivalent to POLLIN.
POLLRDBAND
Priority band data can be read (generally unused on Linux).
POLLWRNORM
Equivalent to POLLOUT.
POLLWRBAND
Priority data may be written.

Linux also knows about, but does not use POLLMSG.

ppoll()

The relationship between poll() and ppoll() is analogous to the relationship between select(2) and pselect(2): like pselect(2), ppoll() allows an application to safely wait until either a file descriptor becomes ready or until a signal is caught.

Other than the difference in the timeout argument, the following ppoll() call:

    ready = ppoll(&fds, nfds, timeout, &sigmask);
is equivalent to atomically executing the following calls:

    sigset_t origmask;

    sigprocmask(SIG_SETMASK, &sigmask, &origmask);
    ready = poll(&fds, nfds, timeout);
    sigprocmask(SIG_SETMASK, &origmask, NULL);

See the description of pselect(2) for an explanation of why ppoll() is necessary.

The timeout argument specifies an upper limit on the amount of time that ppoll() will block. This argument is a pointer to a structure of the following form:

struct timespec {
    long    tv_sec;         /* seconds */
    long    tv_nsec;        /* nanoseconds */
};

If timeout is specified as NULL, then ppoll() can block indefinitely.

RETURN VALUE

On success, a positive number is returned; this is the number of structures which have non-zero revents fields (in other words, those descriptors with events or errors reported). A value of 0 indicates that the call timed out and no file descriptors were ready. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
An invalid file descriptor was given in one of the sets.
EFAULT
The array given as argument was not contained in the calling program's address space.
EINTR
A signal occurred before any requested event.
EINVAL
The nfds value exceeds the RLIMIT_NOFILE value.
ENOMEM
There was no space to allocate file descriptor tables.

VERSIONS

The poll() system call was introduced in Linux 2.1.23. The poll() library call was introduced in libc 5.4.28 (and provides emulation using select(2) if your kernel does not have a poll() system call).

The ppoll() system call was added to Linux in kernel 2.6.16. The ppoll() library call was added in glibc 2.4.

CONFORMING TO

poll() conforms to POSIX.1-2001. ppoll() is Linux specific.

NOTES

Some implementations define the non-standard constant INFTIM with the value -1 for use as a timeout. This constant is not provided in glibc.

Linux Notes

The Linux ppoll() system call modifies its timeout argument. However, the glibc wrapper function hides this behavior by using a local variable for the timeout argument that is passed to the system call. Thus, the glibc ppoll() function does not modify its timeout argument.

BUGS

See the discussion of spurious readiness notifications under the BUGS section of select(2).

SEE ALSO

select(2), select_tut(2), feature_test_macros(7)


umask(2)

UMASK

Section: Linux Programmer's Manual (2)
Updated: 2006-05-13 Return to Main Contents

NAME

umask - set file mode creation mask

SYNOPSIS

#include <sys/types.h>
#include <sys/stat.h>

mode_t umask(mode_t mask);

DESCRIPTION

umask() sets the calling process's file mode creation mask (umask) to mask & 0777.

The umask is used by open(2), mkdir(2), and other system calls that create files to modify the permissions placed on newly created files or directories. Specifically, permissions in the umask are turned off from the mode argument to open(2) and mkdir(2).

The constants that should be used to specify mask are described under stat(2).

The typical default value for the process umask is S_IWGRP | S_IWOTH (octal 022). In the usual case where the mode argument to open(2) is specified as:

    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
(octal 0666) when creating a new file, the permissions on the resulting file will be:

    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
(because 0666 & ~022 = 0644; i.e., rw-r--r--).

RETURN VALUE

This system call always succeeds and the previous value of the mask is returned.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

A child process created via fork(2) inherits its parent's umask. The umask is left unchanged by execve(2).

SEE ALSO

chmod(2), mkdir(2), open(2), stat(2)


umount (2)

 Continue to this page.


uname(2)

UNAME

Section: Linux Programmer's Manual (2)
Updated: 2001-12-15 Return to Main Contents

NAME

uname - get name and information about current kernel

SYNOPSIS

#include <sys/utsname.h>

int uname(struct utsname *buf);

DESCRIPTION

uname() returns system information in the structure pointed to by buf. The utsname struct is defined in <sys/utsname.h>:

struct utsname {
    char sysname[];
    char nodename[];
    char release[];
    char version[];
    char machine[];
#ifdef _GNU_SOURCE
    char domainname[];
#endif
};
The length of the arrays in a struct utsname is unspecified; the fields are terminated by a null byte ('\0').

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
buf is not valid.

CONFORMING TO

SVr4, POSIX.1-2001. There is no uname() call in 4.3BSD.

The domainname member (the NIS or YP domain name) is a GNU extension.

NOTES

This is a system call, and the operating system presumably knows its name, release and version. It also knows what hardware it runs on. So, four of the fields of the struct are meaningful. On the other hand, the field nodename is meaningless: it gives the name of the present machine in some undefined network, but typically machines are in more than one network and have several names. Moreover, the kernel has no way of knowing about such things, so it has to be told what to answer here. The same holds for the additional domainname field.

To this end Linux uses the system calls sethostname(2) and setdomainname(2). Note that there is no standard that says that the hostname set by sethostname(2) is the same string as the nodename field of the struct returned by uname() (indeed, some systems allow a 256-byte hostname and an 8-byte nodename), but this is true on Linux. The same holds for setdomainname(2) and the domainname field.

The length of the fields in the struct varies. Some operating systems or libraries use a hardcoded 9 or 33 or 65 or 257. Other systems use SYS_NMLN or _SYS_NMLN or UTSLEN or _UTSNAME_LENGTH. Clearly, it is a bad idea to use any of these constants; just use sizeof(...). Often 257 is chosen in order to have room for an internet hostname.

There have been three Linux system calls uname(). The first one used length 9, the second one used 65, the third one also uses 65 but adds the domainname field.

Part of the utsname information is also accessible via sysctl(2) and via /proc/sys/kernel/{ostype, hostname, osrelease, version, domainname}.

SEE ALSO

uname(1), getdomainname(2), gethostname(2)


quotactl(2)

QUOTACTL

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

quotactl - manipulate disk quota

SYNOPSIS

#include <sys/types.h>

#include <sys/quota.h>

int quotactl(int cmd, const char *special, int id, caddr_t addr);

DESCRIPTION

The quota system defines for each user and/or group a soft limit and a hard limit bounding the amount of disk space that can be used on a given file system. The hard limit cannot be crossed. The soft limit can be crossed, but warnings will ensue. Moreover, the user cannot be above the soft limit for more than one week (by default) at a time: after this week the soft limit counts as hard limit.

The quotactl() system call manipulates these quota. Its first argument is of the form QCMD(subcmd,type) where type is either USRQUOTA or GRPQUOTA (for user quota and group quota, respectively), and subcmd is described below.

The second argument special is the block special device these quota apply to. It must be mounted.

The third argument id is the user or group ID these quota apply to (when relevant).

The fourth argument addr is the address of a data structure, depending on the command.

The subcmd is one of

Q_QUOTAON
Enable quota. The addr argument is the pathname of the file containing the quota for the filesystem.
Q_QUOTAOFF
Disable quota.
Q_GETQUOTA
Get limits and current usage of disk space. The addr argument is a pointer to a dqblk structure (defined in <sys/quota.h>).
Q_SETQUOTA
Set limits and current usage; addr is as before.
Q_SETQLIM
Set limits; addr is as before.
Q_SETUSE
Set usage.
Q_SYNC
Sync disk copy of a filesystem's quota.
Q_GETSTATS
Get collected stats.

RETURN VALUE

On success, quotactl() returns 0. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
The quota file is not an ordinary file.
EBUSY
Q_QUOTAON was asked, but quotas were enabled already.
EFAULT
Bad addr value.
EINVAL
type is not a known quota type. Or, special could not be found.
EIO
Cannot read or write the quota file.
EMFILE
Too many open files: cannot open quota file.
ENODEV
special cannot be found in the mount table.
ENOPKG
The kernel was compiled without quota support.
ENOTBLK
special is not a block special device.
EPERM
The process was not root (for the file system), and Q_GETQUOTA was asked for another id than that of the process itself, or anything other than Q_GETSTATS or Q_SYNC was asked.
ESRCH
Q_GETQUOTA or Q_SETQUOTA or Q_SETUSE or Q_SETQLIM was asked for a file system that didn't have quota enabled.

CONFORMING TO

BSD

SEE ALSO

quota(1), getrlimit(2), setrlimit(2), ulimit(3), quotacheck(8), quotaon(8)


mremap(2)

MREMAP

Section: Linux Programmer's Manual (2)
Updated: 2005-09-13 Return to Main Contents

NAME

mremap - re-map a virtual memory address

SYNOPSIS

#define _GNU_SOURCE

#include <sys/mman.h>

void *mremap(void *old_address, size_t old_size,
             size_t new_size, int flags);

DESCRIPTION

mremap() expands (or shrinks) an existing memory mapping, potentially moving it at the same time (controlled by the flags argument and the available virtual address space).

old_address is the old address of the virtual memory block that you want to expand (or shrink). Note that old_address has to be page aligned. old_size is the old size of the virtual memory block. new_size is the requested size of the virtual memory block after the resize.

In Linux the memory is divided into pages. A user process has (one or) several linear virtual memory segments. Each virtual memory segment has one or more mappings to real memory pages (in the page table). Each virtual memory segment has its own protection (access rights), which may cause a segmentation violation if the memory is accessed incorrectly (e.g., writing to a read-only segment). Accessing virtual memory outside of the segments will also cause a segmentation violation.

mremap() uses the Linux page table scheme. mremap() changes the mapping between virtual addresses and memory pages. This can be used to implement a very efficient realloc(3).

The flags bit-mask argument may be 0, or include the following flag:

MREMAP_MAYMOVE
By default, if there is not sufficient space to expand a mapping at its current location, then mremap() fails. If this flag is specified, then the kernel is permitted to relocate the mapping to a new virtual address, if necessary. If the mapping is relocated, then absolute pointers into the old mapping location become invalid (offsets relative to the starting address of the mapping should be employed).
MREMAP_FIXED (since Linux 2.3.31)
This flag serves a similar purpose to the MAP_FIXED flag of mmap(2). If this flag is specified, then mremap() accepts a fifth argument, void *new_address, which specifies a page-aligned address to which the mapping must be moved. Any previous mapping at the address range specified by new_address and new_size is unmapped. If MREMAP_FIXED is specified, then MREMAP_MAYMOVE must also be specified.

If the memory segment specified by old_address and old_size is locked (using mlock(2) or similar), then this lock is maintained when the segment is resized and/or relocated. As a consequence, the amount of memory locked by the process may change.

RETURN VALUE

On success mremap() returns a pointer to the new virtual memory area. On error, the value MAP_FAILED (that is, (void *) -1) is returned, and errno is set appropriately.

ERRORS

EAGAIN
The caller tried to expand a memory segment that is locked, but this was not possible without exceeding the RLIMIT_MEMLOCK resource limit.
EFAULT
"Segmentation fault." Some address in the range old_address to old_address+old_size is an invalid virtual memory address for this process. You can also get EFAULT even if there exist mappings that cover the whole address space requested, but those mappings are of different types.
EINVAL
An invalid argument was given. Possible causes are: old_address was not page aligned; a value other than MREMAP_MAYMOVE or MREMAP_FIXED was specified in flags; new_size was zero; new_size or new_address was invalid; or the new address range specified by new_address and new_size overlapped the old address range specified by old_address and old_size; or MREMAP_FIXED was specified without also specifying MREMAP_MAYMOVE.
ENOMEM
The memory area cannot be expanded at the current virtual address, and the MREMAP_MAYMOVE flag is not set in flags. Or, there is not enough (virtual) memory available.

CONFORMING TO

This call is Linux specific, and should not be used in programs intended to be portable.

NOTES

Prior to version 2.4, glibc did not expose the definition of MREMAP_FIXED, and the prototype for mremap() did not allow for the new_address argument.

SEE ALSO

brk(2), getpagesize(2), getrlimit(2), mlock(2), mmap(2), sbrk(2), malloc(3), realloc(3), feature_test_macros(7) Your favorite OS text book for more information on paged memory. (Modern Operating Systems by Andrew S. Tannenbaum, Inside Linux by Randolf Bentson, The Design of the UNIX Operating System by Maurice J. Bach.)


reboot(2)

REBOOT

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

reboot - reboot or enable/disable Ctrl-Alt-Del

SYNOPSIS

For libc4 and libc5 the library call and the system call are identical, and since kernel version 2.1.30 there are symbolic names LINUX_REBOOT_* for the constants and a fourth argument to the call:

#include <unistd.h>
#include <linux/reboot.h>

int reboot(int magic, int magic2, int flag, void *arg);

Under glibc some of the constants involved have gotten symbolic names RB_*, and the library call is a 1-argument wrapper around the 3-argument system call:

#include <unistd.h>
#include <sys/reboot.h>

int reboot(int flag);

DESCRIPTION

The reboot() call reboots the system, or enables/disables the reboot keystroke (abbreviated CAD, since the default is Ctrl-Alt-Delete; it can be changed using loadkeys(1)).

This system call will fail (with EINVAL) unless magic equals LINUX_REBOOT_MAGIC1 (that is, 0xfee1dead) and magic2 equals LINUX_REBOOT_MAGIC2 (that is, 672274793). However, since 2.1.17 also LINUX_REBOOT_MAGIC2A (that is, 85072278) and since 2.1.97 also LINUX_REBOOT_MAGIC2B (that is, 369367448) and since 2.5.71 also LINUX_REBOOT_MAGIC2C (that is, 537993216) are permitted as value for magic2. (The hexadecimal values of these constants are meaningful.) The flag argument can have the following values:

LINUX_REBOOT_CMD_RESTART
(RB_AUTOBOOT, 0x1234567). The message `Restarting system.' is printed, and a default restart is performed immediately. If not preceded by a sync(2), data will be lost.
LINUX_REBOOT_CMD_HALT
(RB_HALT_SYSTEM, 0xcdef0123; since 1.1.76). The message `System halted.' is printed, and the system is halted. Control is given to the ROM monitor, if there is one. If not preceded by a sync(2), data will be lost.
LINUX_REBOOT_CMD_POWER_OFF
(0x4321fedc; since 2.1.30). The message `Power down.' is printed, the system is stopped, and all power is removed from the system, if possible. If not preceded by a sync(2), data will be lost.
LINUX_REBOOT_CMD_RESTART2
(0xa1b2c3d4; since 2.1.30). The message `Restarting system with command '%s'' is printed, and a restart (using the command string given in arg) is performed immediately. If not preceded by a sync(2), data will be lost.
LINUX_REBOOT_CMD_CAD_ON
(RB_ENABLE_CAD, 0x89abcdef). CAD is enabled. This means that the CAD keystroke will immediately cause the action associated with LINUX_REBOOT_CMD_RESTART.
LINUX_REBOOT_CMD_CAD_OFF
(RB_DISABLE_CAD, 0). CAD is disabled. This means that the CAD keystroke will cause a SIGINT signal to be sent to init (process 1), whereupon this process may decide upon a proper action (maybe: kill all processes, sync, reboot).

Only the superuser may use this function.

The precise effect of the above actions depends on the architecture. For the i386 architecture, the additional argument does not do anything at present (2.1.122), but the type of reboot can be determined by kernel command line arguments (`reboot=...') to be either warm or cold, and either hard or through the BIOS.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
Problem with getting userspace data under LINUX_REBOOT_CMD_RESTART2.
EINVAL
Bad magic numbers or flag.
EPERM
The calling process has insufficient privilege to call reboot(); the CAP_SYS_BOOT capability is required.

CONFORMING TO

reboot() is Linux specific, and should not be used in programs intended to be portable.

SEE ALSO

sync(2), bootparam(7), capabilities(7), ctrlaltdel(8), halt(8), reboot(8)


recv(2)

RECV

Section: Linux Programmer's Manual (2)
Updated: 2002-12-31 Return to Main Contents

NAME

recv, recvfrom, recvmsg - receive a message from a socket

SYNOPSIS

#include <sys/types.h>

#include <sys/socket.h>

ssize_t recv(int s, void *buf, size_t len, int flags);

ssize_t recvfrom(int s, void *buf, size_t len, int flags,
                 struct sockaddr *from, socklen_t *fromlen);

ssize_t recvmsg(int s, struct msghdr *msg, int flags);

DESCRIPTION

The recvfrom() and recvmsg() calls are used to receive messages from a socket, and may be used to receive data on a socket whether or not it is connection-oriented.

If from is not NULL, and the underlying protocol provides the source address, this source address is filled in. The argument fromlen is a value-result parameter, initialized to the size of the buffer associated with from, and modified on return to indicate the actual size of the address stored there.

The recv() call is normally used only on a connected socket (see connect(2)) and is identical to recvfrom() with a NULL from parameter.

All three routines return the length of the message on successful completion. If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from.

If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket is nonblocking (see fcntl(2)), in which case the value -1 is returned and the external variable errno set to EAGAIN. The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.

The select(2) or poll(2) call may be used to determine when more data arrives.

The flags argument to a recv() call is formed by OR'ing one or more of the following values:

MSG_DONTWAIT
Enables non-blocking operation; if the operation would block, EAGAIN is returned (this can also be enabled using the O_NONBLOCK with the F_SETFL fcntl(2)).
MSG_ERRQUEUE
This flag specifies that queued errors should be received from the socket error queue. The error is passed in an ancillary message with a type dependent on the protocol (for IPv4 IP_RECVERR). The user should supply a buffer of sufficient size. See cmsg(3) and ip(7) for more information. The payload of the original packet that caused the error is passed as normal data via msg_iovec. The original destination address of the datagram that caused the error is supplied via msg_name.
For local errors, no address is passed (this can be checked with the cmsg_len member of the cmsghdr). For error receives, the MSG_ERRQUEUE is set in the msghdr. After an error has been passed, the pending socket error is regenerated based on the next queued error and will be passed on the next socket operation.

The error is supplied in a sock_extended_err structure:

#define SO_EE_ORIGIN_NONE    0
#define SO_EE_ORIGIN_LOCAL   1
#define SO_EE_ORIGIN_ICMP    2
#define SO_EE_ORIGIN_ICMP6   3

struct sock_extended_err
{
    u_int32_t ee_errno;   /* error number */
    u_int8_t  ee_origin;  /* where the error originated */
    u_int8_t  ee_type;    /* type */
    u_int8_t  ee_code;    /* code */
    u_int8_t  ee_pad;
    u_int32_t ee_info;    /* additional information */
    u_int32_t ee_data;    /* other data */
    /* More data may follow */
};

struct sockaddr *SO_EE_OFFENDER(struct sock_extended_err *);
ee_errno contains the errno number of the queued error. ee_origin is the origin code of where the error originated. The other fields are protocol specific. The macro SOCK_EE_OFFENDER returns a pointer to the address of the network object where the error originated from given a pointer to the ancillary message. If this address is not known, the sa_family member of the sockaddr contains AF_UNSPEC and the other fields of the sockaddr are undefined. The payload of the packet that caused the error is passed as normal data.
For local errors, no address is passed (this can be checked with the cmsg_len member of the cmsghdr). For error receives, the MSG_ERRQUEUE is set in the msghdr. After an error has been passed, the pending socket error is regenerated based on the next queued error and will be passed on the next socket operation.
MSG_OOB
This flag requests receipt of out-of-band data that would not be received in the normal data stream. Some protocols place expedited data at the head of the normal data queue, and thus this flag cannot be used with such protocols.
MSG_PEEK
This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.
MSG_TRUNC
Return the real length of the packet, even when it was longer than the passed buffer. Only valid for packet sockets.
MSG_WAITALL
This flag requests that the operation block until the full request is satisfied. However, the call may still return less data than requested if a signal is caught, an error or disconnect occurs, or the next data to be received is of a different type than that returned.

The recvmsg() call uses a msghdr structure to minimize the number of directly supplied parameters. This structure has the following form, as defined in <sys/socket.h>:

struct msghdr {
    void         *msg_name;       /* optional address */
    socklen_t     msg_namelen;    /* size of address */
    struct iovec *msg_iov;        /* scatter/gather array */
    size_t        msg_iovlen;     /* # elements in msg_iov */
    void         *msg_control;    /* ancillary data, see below */
    socklen_t     msg_controllen; /* ancillary data buffer len */
    int           msg_flags;      /* flags on received message */
};

Here msg_name and msg_namelen specify the source address if the socket is unconnected; msg_name may be given as a null pointer if no names are desired or required. The fields msg_iov and msg_iovlen describe scatter-gather locations, as discussed in readv(2). The field msg_control, which has length msg_controllen, points to a buffer for other protocol control-related messages or miscellaneous ancillary data. When recvmsg() is called, msg_controllen should contain the length of the available buffer in msg_control; upon return from a successful call it will contain the length of the control message sequence.

The messages are of the form:

struct cmsghdr {
    socklen_t cmsg_len;     /* data byte count, including hdr */
    int       cmsg_level;   /* originating protocol */
    int       cmsg_type;    /* protocol-specific type */
/* followed by
    u_char    cmsg_data[]; */
};

Ancillary data should only be accessed by the macros defined in cmsg(3).

As an example, Linux uses this auxiliary data mechanism to pass extended errors, IP options or file descriptors over Unix sockets.

The msg_flags field in the msghdr is set on return of recvmsg(). It can contain several flags:

MSG_EOR
indicates end-of-record; the data returned completed a record (generally used with sockets of type SOCK_SEQPACKET).
MSG_TRUNC
indicates that the trailing portion of a datagram was discarded because the datagram was larger than the buffer supplied.
MSG_CTRUNC
indicates that some control data were discarded due to lack of space in the buffer for ancillary data.
MSG_OOB
is returned to indicate that expedited or out-of-band data were received.
MSG_ERRQUEUE
indicates that no data was received but an extended error from the socket error queue.

RETURN VALUE

These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown.

ERRORS

These are some standard errors generated by the socket layer. Additional errors may be generated and returned from the underlying protocol modules; see their manual pages.
EAGAIN
The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.
EBADF
The argument s is an invalid descriptor.
ECONNREFUSED
A remote host refused to allow the network connection (typically because it is not running the requested service).
EFAULT
The receive buffer pointer(s) point outside the process's address space.
EINTR
The receive was interrupted by delivery of a signal before any data were available.
EINVAL
Invalid argument passed.
ENOMEM
Could not allocate memory for recvmsg().
ENOTCONN
The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).
ENOTSOCK
The argument s does not refer to a socket.

CONFORMING TO

4.4BSD (these function calls first appeared in 4.2BSD), POSIX.1-2001.

POSIX.1-2001 only describes the MSG_OOB, MSG_PEEK, and MSG_WAITALL flags.

NOTES

The prototypes given above follow glibc2. The Single Unix Specification agrees, except that it has return values of type `ssize_t' (while 4.x BSD and libc4 and libc5 all have `int'). The flags argument is `int' in 4.x BSD, but `unsigned int' in libc4 and libc5. The len argument is `int' in 4.x BSD, but `size_t' in libc4 and libc5. The fromlen argument is `int *' in 4.x BSD, libc4 and libc5. The present `socklen_t *' was invented by POSIX. See also accept(2).

According to POSIX.1-2001, the msg_controllen field of the msghdr structure should be typed as socklen_t, but glibc currently (2.4) types it as size_t.

EXAMPLE

An example of the use of recvfrom() is shown in getaddrinfo(3).

SEE ALSO

fcntl(2), getsockopt(2), read(2), select(2), shutdown(2), socket(2), cmsg(3), sockatmark(3)


recvmsg (2)

 Continue to this page.


rename(2)

RENAME

Section: Linux Programmer's Manual (2)
Updated: 1998-06-04 Return to Main Contents

NAME

rename - change the name or location of a file

SYNOPSIS

#include <stdio.h>

int rename(const char *oldpath, const char *newpath);

DESCRIPTION

rename() renames a file, moving it between directories if required. Any other hard links to the file (as created using link(2)) are unaffected. Open file descriptors for oldpath are also unaffected.

If newpath already exists it will be atomically replaced (subject to a few conditions; see ERRORS below), so that there is no point at which another process attempting to access newpath will find it missing.

If oldpath and newpath are existing hard links referring to the same file, then rename() does nothing, and returns a success status.

If newpath exists but the operation fails for some reason rename() guarantees to leave an instance of newpath in place.

oldpath can specify a directory. In this case, newpath must either not exist, or it must specify an empty directory.

However, when overwriting there will probably be a window in which both oldpath and newpath refer to the file being renamed.

If oldpath refers to a symbolic link the link is renamed; if newpath refers to a symbolic link the link will be overwritten.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Write permission is denied for the directory containing oldpath or newpath, or, search permission is denied for one of the directories in the path prefix of oldpath or newpath, or oldpath is a directory and does not allow write permission (needed to update the .. entry). (See also path_resolution(7).)
EBUSY
The rename fails because oldpath or newpath is a directory that is in use by some process (perhaps as current working directory, or as root directory, or because it was open for reading) or is in use by the system (for example as mount point), while the system considers this an error. (Note that there is no requirement to return EBUSY in such cases --- there is nothing wrong with doing the rename anyway --- but it is allowed to return EBUSY if the system cannot otherwise handle such situations.)
EFAULT
oldpath or newpath points outside your accessible address space.
EINVAL
The new pathname contained a path prefix of the old, or, more generally, an attempt was made to make a directory a subdirectory of itself.
EISDIR
newpath is an existing directory, but oldpath is not a directory.
ELOOP
Too many symbolic links were encountered in resolving oldpath or newpath.
EMLINK
oldpath already has the maximum number of links to it, or it was a directory and the directory containing newpath has the maximum number of links.
ENAMETOOLONG
oldpath or newpath was too long.
ENOENT
A directory component in oldpath or newpath does not exist or is a dangling symbolic link.
ENOMEM
Insufficient kernel memory was available.
ENOSPC
The device containing the file has no room for the new directory entry.
ENOTDIR
A component used as a directory in oldpath or newpath is not, in fact, a directory. Or, oldpath is a directory, and newpath exists but is not a directory.
ENOTEMPTY or EEXIST
newpath is a non-empty directory, that is, contains entries other than "." and "..".
EPERM or EACCES
The directory containing oldpath has the sticky bit (S_ISVTX) set and the process's effective user ID is neither the user ID of the file to be deleted nor that of the directory containing it, and the process is not privileged (Linux: does not have the CAP_FOWNER capability); or newpath is an existing file and the directory containing it has the sticky bit set and the process's effective user ID is neither the user ID of the file to be replaced nor that of the directory containing it, and the process is not privileged (Linux: does not have the CAP_FOWNER capability); or the filesystem containing pathname does not support renaming of the type requested.
EROFS
The file is on a read-only filesystem.
EXDEV
oldpath and newpath are not on the same mounted filesystem. (Linux permits a filesystem to be mounted at multiple points, but rename(2) does not work across different mount points, even if the same filesystem is mounted on both.)

CONFORMING TO

4.3BSD, C89, C99, POSIX.1-2001.

BUGS

On NFS filesystems, you can not assume that if the operation failed the file was not renamed. If the server does the rename operation and then crashes, the retransmitted RPC which will be processed when the server is up again causes a failure. The application is expected to deal with this. See link(2) for a similar problem.

SEE ALSO

mv(1), chmod(2), link(2), renameat(2), symlink(2), unlink(2), path_resolution(7)


semget(2)

SEMGET

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

semget - get a semaphore set identifier

SYNOPSIS

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int semget(key_t key, int nsems, int semflg);

DESCRIPTION

The semget() system call returns the semaphore set identifier associated with the argument key. A new set of nsems semaphores is created if key has the value IPC_PRIVATE or if no existing semaphore set is associated with key and IPC_CREAT is specified in semflg.

If semflg specifies both IPC_CREAT and IPC_EXCL and a semaphore set already exists for key, then semget() fails with errno set to EEXIST. (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)

Upon creation, the least significant 9 bits of the argument semflg define the permissions (for owner, group and others) for the semaphore set. These bits have the same format, and the same meaning, as the mode argument of open(2) (though the execute permissions are not meaningful for semaphores, and write permissions mean permission to alter semaphore values).

The values of the semaphores in a newly created set are indeterminate. (POSIX.1-2001 is explicit on this point.) Although Linux, like many other implementations, initializes the semaphore values to 0, a portable application cannot rely on this: it should explicitly initialize the semaphores to the desired values.

When creating a new semaphore set, semget() initializes the set's associated data structure, semid_ds (see semctl(2)), as follows:

sem_perm.cuid and sem_perm.uid are set to the effective user ID of the calling process.
sem_perm.cgid and sem_perm.gid are set to the effective group ID of the calling process.
The least significant 9 bits of sem_perm.mode are set to the least significant 9 bits of semflg.
sem_nsems is set to the value of nsems.
sem_otime is set to 0.
sem_ctime is set to the current time.

The argument nsems can be 0 (a don't care) when a semaphore set is not being created. Otherwise nsems must be greater than 0 and less than or equal to the maximum number of semaphores per semaphore set (SEMMSL).

If the semaphore set already exists, the permissions are verified.

RETURN VALUE

If successful, the return value will be the semaphore set identifier (a non-negative integer), otherwise -1 is returned, with errno indicating the error.

ERRORS

On failure errno will be set to one of the following:
EACCES
A semaphore set exists for key, but the calling process does not have permission to access the set, and does not have the CAP_IPC_OWNER capability.
EEXIST
A semaphore set exists for key and semflg specified both IPC_CREAT and IPC_EXCL.
EINVAL
nsems is less than 0 or greater than the limit on the number of semaphores per semaphore set (SEMMSL), or a semaphore set corresponding to key already exists, and nsems is larger than the number of semaphores in that set.
ENOENT
No semaphore set exists for key and semflg did not specify IPC_CREAT.
ENOMEM
A semaphore set has to be created but the system does not have enough memory for the new data structure.
ENOSPC
A semaphore set has to be created but the system limit for the maximum number of semaphore sets (SEMMNI), or the system wide maximum number of semaphores (SEMMNS), would be exceeded.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

IPC_PRIVATE isn't a flag field but a key_t type. If this special value is used for key, the system call ignores everything but the least significant 9 bits of semflg and creates a new semaphore set (on success).

The following limits on semaphore set resources affect the semget() call:

SEMMNI
System wide maximum number of semaphore sets: policy dependent (on Linux, this limit can be read and modified via the fourth field of /proc/sys/kernel/sem).
SEMMSL
Maximum number of semaphores per semid: implementation dependent (on Linux, this limit can be read and modified via the first field of /proc/sys/kernel/sem).
SEMMNS
System wide maximum number of semaphores: policy dependent (on Linux, this limit can be read and modified via the second field of /proc/sys/kernel/sem). Values greater than SEMMSL * SEMMNI makes it irrelevant.

BUGS

The name choice IPC_PRIVATE was perhaps unfortunate, IPC_NEW would more clearly show its function.

The semaphores in a set are not initialized by semget(). In order to initialize the semaphores, semctl(2) must be used to perform a SETVAL or a SETALL operation on the semaphore set. (Where multiple peers do not know who will be the first to initialize the set, checking for a non-zero sem_otime in the associated data structure retrieved by a semctl(2) IPC_STAT operation can be used to avoid races.)

SEE ALSO

semctl(2), semop(2), ftok(3), capabilities(7), sem_overview(7), svipc(7)


semop(2)

SEMOP

Section: Linux Programmer's Manual (2)
Updated: 2004-11-10 Return to Main Contents

NAME

semop, semtimedop - semaphore operations

SYNOPSIS

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int semop(int semid, struct sembuf *sops, unsigned nsops);

int semtimedop(int semid, struct sembuf *sops, unsigned nsops,
               struct timespec *timeout);

DESCRIPTION

Each semaphore in a semaphore set has the following associated values:

unsigned short  semval;   /* semaphore value */
unsigned short  semzcnt;  /* # waiting for zero */
unsigned short  semncnt;  /* # waiting for increase */
pid_t           sempid;   /* process that did last op */
semop() performs operations on selected semaphores in the set indicated by semid. Each of the nsops elements in the array pointed to by sops specifies an operation to be performed on a single semaphore. The elements of this structure are of type struct sembuf, containing the following members:

unsigned short sem_num;  /* semaphore number */
short          sem_op;   /* semaphore operation */
short          sem_flg;  /* operation flags */
Flags recognized in sem_flg are IPC_NOWAIT and SEM_UNDO. If an operation specifies SEM_UNDO, it will be automatically undone when the process terminates.

The set of operations contained in sops is performed in array order, and atomically, that is, the operations are performed either as a complete unit, or not at all. The behavior of the system call if not all operations can be performed immediately depends on the presence of the IPC_NOWAIT flag in the individual sem_flg fields, as noted below.

Each operation is performed on the sem_num-th semaphore of the semaphore set, where the first semaphore of the set is numbered 0. There are three types of operation, distinguished by the value of sem_op.

If sem_op is a positive integer, the operation adds this value to the semaphore value (semval). Furthermore, if SEM_UNDO is specified for this operation, the system updates the process undo count (semadj) for this semaphore. This operation can always proceed --- it never forces a process to wait. The calling process must have alter permission on the semaphore set.

If sem_op is zero, the process must have read permission on the semaphore set. This is a "wait-for-zero" operation: if semval is zero, the operation can immediately proceed. Otherwise, if IPC_NOWAIT is specified in sem_flg, semop() fails with errno set to EAGAIN (and none of the operations in sops is performed). Otherwise semzcnt (the count of processes waiting until this semaphore's value becomes zero) is incremented by one and the process sleeps until one of the following occurs:

*
semval becomes 0, at which time the value of semzcnt is decremented.
*
The semaphore set is removed: semop() fails, with errno set to EIDRM.
*
The calling process catches a signal: the value of semzcnt is decremented and semop() fails, with errno set to EINTR.
*
The time limit specified by timeout in a semtimedop() call expires: semop() fails, with errno set to EAGAIN.

If sem_op is less than zero, the process must have alter permission on the semaphore set. If semval is greater than or equal to the absolute value of sem_op, the operation can proceed immediately: the absolute value of sem_op is subtracted from semval, and, if SEM_UNDO is specified for this operation, the system updates the process undo count (semadj) for this semaphore. If the absolute value of sem_op is greater than semval, and IPC_NOWAIT is specified in sem_flg, semop() fails, with errno set to EAGAIN (and none of the operations in sops is performed). Otherwise semncnt (the counter of processes waiting for this semaphore's value to increase) is incremented by one and the process sleeps until one of the following occurs:

*
semval becomes greater than or equal to the absolute value of sem_op, at which time the value of semncnt is decremented, the absolute value of sem_op is subtracted from semval and, if SEM_UNDO is specified for this operation, the system updates the process undo count (semadj) for this semaphore.
*
The semaphore set is removed from the system: semop() fails, with errno set to EIDRM.
*
The calling process catches a signal: the value of semncnt is decremented and semop() fails, with errno set to EINTR.
*
The time limit specified by timeout in a semtimedop() call expires: the system call fails, with errno set to EAGAIN.

On successful completion, the sempid value for each semaphore specified in the array pointed to by sops is set to the process ID of the calling process. In addition, the sem_otime is set to the current time.

semtimedop() behaves identically to semop() except that in those cases were the calling process would sleep, the duration of that sleep is limited by the amount of elapsed time specified by the timespec structure whose address is passed in the timeout parameter. If the specified time limit has been reached, semtimedop() fails with errno set to EAGAIN (and none of the operations in sops is performed). If the timeout parameter is NULL, then semtimedop() behaves exactly like semop().

RETURN VALUE

If successful semop() and semtimedop() return 0; otherwise they return -1 with errno indicating the error.

ERRORS

On failure, errno is set to one of the following:
E2BIG
The argument nsops is greater than SEMOPM, the maximum number of operations allowed per system call.
EACCES
The calling process does not have the permissions required to perform the specified semaphore operations, and does not have the CAP_IPC_OWNER capability.
EAGAIN
An operation could not proceed immediately and either IPC_NOWAIT was specified in sem_flg or the time limit specified in timeout expired.
EFAULT
An address specified in either the sops or timeout parameters isn't accessible.
EFBIG
For some operation the value of sem_num is less than 0 or greater than or equal to the number of semaphores in the set.
EIDRM
The semaphore set was removed.
EINTR
While blocked in this system call, the process caught a signal.
EINVAL
The semaphore set doesn't exist, or semid is less than zero, or nsops has a non-positive value.
ENOMEM
The sem_flg of some operation specified SEM_UNDO and the system does not have enough memory to allocate the undo structure.
ERANGE
For some operation sem_op+semval is greater than SEMVMX, the implementation dependent maximum value for semval.

VERSIONS

semtimedop() first appeared in Linux 2.5.52, and was subsequently backported into kernel 2.4.22. Glibc support for semtimedop() first appeared in version 2.3.3.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

The sem_undo structures of a process aren't inherited across a fork(2) system call, but they are inherited across an execve(2) system call.

semop() is never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.

semadj is a per-process integer which is simply the (negative) count of all semaphore operations performed specifying the SEM_UNDO flag. When a semaphore's value is directly set using the SETVAL or SETALL request to semctl(2), the corresponding semadj values in all processes are cleared.

The semval, sempid, semzcnt, and semnct values for a semaphore can all be retrieved using appropriate semctl(2) calls.

The following limits on semaphore set resources affect the semop() call:

SEMOPM
Maximum number of operations allowed for one semop() call (32) (on Linux, this limit can be read and modified via the third field of /proc/sys/kernel/sem).
SEMVMX
Maximum allowable value for semval: implementation dependent (32767).

The implementation has no intrinsic limits for the adjust on exit maximum value (SEMAEM), the system wide maximum number of undo structures (SEMMNU) and the per-process maximum number of undo entries system parameters.

BUGS

When a process terminates, its set of associated semadj structures is used to undo the effect of all of the semaphore operations it performed with the SEM_UNDO flag. This raises a difficulty: if one (or more) of these semaphore adjustments would result in an attempt to decrease a semaphore's value below zero, what should an implementation do? One possible approach would be to block until all the semaphore adjustments could be performed. This is however undesirable since it could force process termination to block for arbitrarily long periods. Another possibility is that such semaphore adjustments could be ignored altogether (somewhat analogously to failing when IPC_NOWAIT is specified for a semaphore operation). Linux adopts a third approach: decreasing the semaphore value as far as possible (i.e., to zero) and allowing process termination to proceed immediately.

In kernels 2.6.x, x <= 10, there is a bug that in some circumstances prevents a process that is waiting for a semaphore value to become zero from being woken up when the value does actually become zero. This bug is fixed in kernel 2.6.11.

SEE ALSO

semctl(2), semget(2), sigaction(2), capabilities(7), sem_overview(7), svipc(7)


send(2)

SEND

Section: Linux Programmer's Manual (2)
Updated: 2004-07-01 Return to Main Contents

NAME

send, sendto, sendmsg - send a message on a socket

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>

ssize_t send(int s, const void *buf, size_t len, int flags);

ssize_t sendto(int s, const void *buf, size_t len, int flags,
               const struct sockaddr *to, socklen_t tolen);

ssize_t sendmsg(int s, const struct msghdr *msg, int flags);

DESCRIPTION

The system calls send(), sendto(), and sendmsg() are used to transmit a message to another socket.

The send() call may be used only when the socket is in a connected state (so that the intended recipient is known). The only difference between send() and write(2) is the presence of flags. With zero flags parameter, send() is equivalent to write(2). Also, send(s,buf,len,flags) is equivalent to sendto(s,buf,len,flags,NULL,0).

The parameter s is the file descriptor of the sending socket.

If sendto() is used on a connection-mode (SOCK_STREAM, SOCK_SEQPACKET) socket, the parameters to and tolen are ignored (and the error EISCONN may be returned when they are not NULL and 0), and the error ENOTCONN is returned when the socket was not actually connected. Otherwise, the address of the target is given by to with tolen specifying its size. For sendmsg(), the address of the target is given by msg.msg_name, with msg.msg_namelen specifying its size.

For send() and sendto(), the message is found in buf and has length len. For sendmsg(), the message is pointed to by the elements of the array msg.msg_iov. The sendmsg() call also allows sending ancillary data (also known as control information).

If the message is too long to pass atomically through the underlying protocol, the error EMSGSIZE is returned, and the message is not transmitted.

No indication of failure to deliver is implicit in a send(). Locally detected errors are indicated by a return value of -1.

When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it would return EAGAIN in this case. The select(2) call may be used to determine when it is possible to send more data.

The flags parameter is the bitwise OR of zero or more of the following flags.

MSG_CONFIRM (Linux 2.3+ only)
Tell the link layer that forward progress happened: you got a successful reply from the other side. If the link layer doesn't get this it will regularly reprobe the neighbor (e.g., via a unicast ARP). Only valid on SOCK_DGRAM and SOCK_RAW sockets and currently only implemented for IPv4 and IPv6. See arp(7) for details.
MSG_DONTROUTE
Don't use a gateway to send out the packet, only send to hosts on directly connected networks. This is usually used only by diagnostic or routing programs. This is only defined for protocol families that route; packet sockets don't.
MSG_DONTWAIT
Enables non-blocking operation; if the operation would block, EAGAIN is returned (this can also be enabled using the O_NONBLOCK with the F_SETFL fcntl(2)).
MSG_EOR
Terminates a record (when this notion is supported, as for sockets of type SOCK_SEQPACKET).
MSG_MORE (Since Linux 2.4.4)
The caller has more data to send. This flag is used with TCP sockets to obtain the same effect as the TCP_CORK socket option (see tcp(7)), with the difference that this flag can be set on a per-call basis.

Since Linux 2.6, this flag is also supported for UDP sockets, and informs the kernel to package all of the data sent in calls with this flag set into a single datagram which is only transmitted when a call is performed that does not specify this flag. (See also the UDP_CORK socket option described in udp(7).)

MSG_NOSIGNAL
Requests not to send SIGPIPE on errors on stream oriented sockets when the other end breaks the connection. The EPIPE error is still returned.
MSG_OOB
Sends out-of-band data on sockets that support this notion (e.g., of type SOCK_STREAM); the underlying protocol must also support out-of-band data.

The definition of the msghdr structure follows. See recv(2) and below for an exact description of its fields.

struct msghdr {
    void         *msg_name;       /* optional address */
    socklen_t     msg_namelen;    /* size of address */
    struct iovec *msg_iov;        /* scatter/gather array */
    size_t        msg_iovlen;     /* # elements in msg_iov */
    void         *msg_control;    /* ancillary data, see below */
    socklen_t     msg_controllen; /* ancillary data buffer len */
    int           msg_flags;      /* flags on received message */
};

You may send control information using the msg_control and msg_controllen members. The maximum control buffer length the kernel can process is limited per socket by the net.core.optmem_max sysctl; see socket(7).

RETURN VALUE

On success, these calls return the number of characters sent. On error, -1 is returned, and errno is set appropriately.

ERRORS

These are some standard errors generated by the socket layer. Additional errors may be generated and returned from the underlying protocol modules; see their respective manual pages.
EACCES
(For Unix domain sockets, which are identified by pathname) Write permission is denied on the destination socket file, or search permission is denied for one of the directories the path prefix. (See path_resolution(7).)
EAGAIN or EWOULDBLOCK
The socket is marked non-blocking and the requested operation would block.
EBADF
An invalid descriptor was specified.
ECONNRESET
Connection reset by peer.
EDESTADDRREQ
The socket is not connection-mode, and no peer address is set.
EFAULT
An invalid user space address was specified for a parameter.
EINTR
A signal occurred before any data was transmitted.
EINVAL
Invalid argument passed.
EISCONN
The connection-mode socket was connected already but a recipient was specified. (Now either this error is returned, or the recipient specification is ignored.)
EMSGSIZE
The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible.
ENOBUFS
The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion. (Normally, this does not occur in Linux. Packets are just silently dropped when a device queue overflows.)
ENOMEM
No memory available.
ENOTCONN
The socket is not connected, and no target has been given.
ENOTSOCK
The argument s is not a socket.
EOPNOTSUPP
Some bit in the flags argument is inappropriate for the socket type.
EPIPE
The local end has been shut down on a connection oriented socket. In this case the process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.

CONFORMING TO

4.4BSD, SVr4, POSIX.1-2001. These function calls appeared in 4.2BSD.

POSIX.1-2001 only describes the MSG_OOB and MSG_EOR flags. The MSG_CONFIRM flag is a Linux extension.

NOTES

The prototypes given above follow the Single Unix Specification, as glibc2 also does; the flags argument was `int' in 4.x BSD, but `unsigned int' in libc4 and libc5; the len argument was `int' in 4.x BSD and libc4, but `size_t' in libc5; the tolen argument was `int' in 4.x BSD and libc4 and libc5. See also accept(2).

According to POSIX.1-2001, the msg_controllen field of the msghdr structure should be typed as socklen_t, but glibc currently (2.4) types it as size_t.

BUGS

Linux may return EPIPE instead of ENOTCONN.

EXAMPLE

An example of the use of sendto() is shown in getaddrinfo(3).

SEE ALSO

fcntl(2), getsockopt(2), recv(2), select(2), sendfile(2), shutdown(2), socket(2), write(2), cmsg(3), ip(7), socket(7), tcp(7), udp(7)


readlink(2)

READLINK

Section: Linux Programmer's Manual (2)
Updated: 1997-08-21 Return to Main Contents

NAME

readlink - read value of a symbolic link

SYNOPSIS

#include <unistd.h>

ssize_t readlink(const char *path, char *buf, size_t bufsiz);

DESCRIPTION

readlink() places the contents of the symbolic link path in the buffer buf, which has size bufsiz. readlink() does not append a null byte to buf. It will truncate the contents (to a length of bufsiz characters), in case the buffer is too small to hold all of the contents.

RETURN VALUE

The call returns the count of characters placed in the buffer if it succeeds, or a -1 if an error occurs, placing the error code in errno.

ERRORS

EACCES
Search permission is denied for a component of the path prefix. (See also path_resolution(7).)
EFAULT
buf extends outside the process's allocated address space.
EINVAL
bufsiz is not positive.
EINVAL
The named file is not a symbolic link.
EIO
An I/O error occurred while reading from the file system.
ELOOP
Too many symbolic links were encountered in translating the pathname.
ENAMETOOLONG
A pathname, or a component of a pathname, was too long.
ENOENT
The named file does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix is not a directory.

CONFORMING TO

4.4BSD (the readlink() function call appeared in 4.2BSD), POSIX.1-2001.

NOTES

In versions of glibc up to and including glibc 2.4, the return type of readlink() was declared as int. Nowadays, the return type is declared as ssize_t, as (newly) required in POSIX.1-2001.

SEE ALSO

lstat(2), readlinkat(2), stat(2), symlink(2), path_resolution(7)


setpgid(2)

SETPGID

Section: Linux Programmer's Manual (2)
Updated: 2003-01-20 Return to Main Contents

NAME

setpgid, getpgid, setpgrp, getpgrp - set/get process group

SYNOPSIS

#include <unistd.h>

int setpgid(pid_t pid, pid_t pgid);
pid_t getpgid(pid_t pid);
int setpgrp(void);
pid_t getpgrp(void);

DESCRIPTION

setpgid() sets the process group ID of the process specified by pid to pgid. If pid is zero, the process ID of the current process is used. If pgid is zero, the process ID of the process specified by pid is used. If setpgid() is used to move a process from one process group to another (as is done by some shells when creating pipelines), both process groups must be part of the same session. In this case, the pgid specifies an existing process group to be joined and the session ID of that group must match the session ID of the joining process.

getpgid() returns the process group ID of the process specified by pid. If pid is zero, the process ID of the current process is used.

The call setpgrp() is equivalent to setpgid(0,0).

Similarly, getpgrp() is equivalent to getpgid(0). Each process group is a member of a session and each process is a member of the session of which its process group is a member.

Process groups are used for distribution of signals, and by terminals to arbitrate requests for their input: Processes that have the same process group as the terminal are foreground and may read, while others will block with a signal if they attempt to read. These calls are thus used by programs such as csh(1) to create process groups in implementing job control. The TIOCGPGRP and TIOCSPGRP calls described in termios(3) are used to get/set the process group of the control terminal.

If a session has a controlling terminal, CLOCAL is not set and a hangup occurs, then the session leader is sent a SIGHUP. If the session leader exits, the SIGHUP signal will be sent to each process in the foreground process group of the controlling terminal.

If the exit of the process causes a process group to become orphaned, and if any member of the newly-orphaned process group is stopped, then a SIGHUP signal followed by a SIGCONT signal will be sent to each process in the newly-orphaned process group.

RETURN VALUE

On success, setpgid() and setpgrp() return zero. On error, -1 is returned, and errno is set appropriately.

getpgid() returns a process group on success. On error, -1 is returned, and errno is set appropriately.

getpgrp() always returns the current process group.

ERRORS

EACCES
An attempt was made to change the process group ID of one of the children of the calling process and the child had already performed an execve(2) (setpgid(), setpgrp()).
EINVAL
pgid is less than 0 (setpgid(), setpgrp()).
EPERM
An attempt was made to move a process into a process group in a different session, or to change the process group ID of one of the children of the calling process and the child was in a different session, or to change the process group ID of a session leader (setpgid(), setpgrp()).
ESRCH
For getpgid(): pid does not match any process. For setpgid(): pid is not the current process and not a child of the current process.

CONFORMING TO

The functions setpgid() and getpgrp() conform to POSIX.1-2001. The function setpgrp() is from 4.2BSD. The function getpgid() conforms to SVr4.

NOTES

A child created via fork(2) inherits its parent's process group ID. The process group ID is preserved across an execve(2).

POSIX took setpgid() from the BSD function setpgrp(). Also System V has a function with the same name, but it is identical to setsid(2).

To get the prototypes under glibc, define both _XOPEN_SOURCE and _XOPEN_SOURCE_EXTENDED, or use "#define _XOPEN_SOURCE n" for some integer n larger than or equal to 500.

SEE ALSO

getuid(2), setsid(2), tcgetpgrp(3), tcsetpgrp(3), termios(3), feature_test_macros(7)


setpriority (2)

 Continue to this page.


ustat(2)

USTAT

Section: Linux Programmer's Manual (2)
Updated: 2003-08-04 Return to Main Contents

NAME

ustat - get file system statistics

SYNOPSIS

#include <sys/types.h>

#include <unistd.h>    /* libc[45] */

#include <ustat.h>     /* glibc2 */

int ustat(dev_t dev, struct ustat *ubuf);

DESCRIPTION

ustat() returns information about a mounted file system. dev is a device number identifying a device containing a mounted file system. ubuf is a pointer to a ustat structure that contains the following members:

daddr_t f_tfree;      /* Total free blocks */
ino_t   f_tinode;     /* Number of free inodes */
char    f_fname[6];   /* Filsys name */
char    f_fpack[6];   /* Filsys pack name */

The last two fields, f_fname and f_fpack, are not implemented and will always be filled with null bytes ('\0').

RETURN VALUE

On success, zero is returned and the ustat structure pointed to by ubuf will be filled in. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
ubuf points outside of your accessible address space.
EINVAL
dev does not refer to a device containing a mounted file system.
ENOSYS
The mounted file system referenced by dev does not support this operation, or any version of Linux before 1.3.16.

CONFORMING TO

SVr4.

NOTES

ustat() is deprecated and has only been provided for compatibility. All new programs should use statfs(2) instead.

HP-UX Notes

The HP-UX version of the ustat structure has an additional field, f_blksize, that is unknown elsewhere. HP-UX warns: For some file systems, the number of free inodes does not change. Such file systems will return -1 in the field f_tinode. For some file systems, inodes are dynamically allocated. Such file systems will return the current number of free inodes.

SEE ALSO

stat(2), statfs(2)


setup(2)

SETUP

Section: Linux Programmer's Manual (2)
Updated: 1996-05-03 Return to Main Contents

NAME

setup - setup devices and file systems, mount root file system

SYNOPSIS

#include <unistd.h>

_syscall0(int, setup)

int setup(void);

DESCRIPTION

setup() is called once from within linux/init/main.c. It calls initialization functions for devices and file systems configured into the kernel and then mounts the root file system.

No user process may call setup(). Any user process, even a process with superuser permission, will receive EPERM.

RETURN VALUE

setup() always returns -1 for a user process.

ERRORS

EPERM
Always, for a user process.

CONFORMING TO

This function is Linux specific, and should not be used in programs intended to be portable, or indeed in any programs at all. Since Linux 2.1.121, no such function exists anymore. The calling sequence varied: it has had a single parameter void * BIOS and at other times a single parameter int magic.


shmctl(2)

SHMCTL

Section: Linux Programmer's Manual (2)
Updated: 2005-05-30 Return to Main Contents

NAME

shmctl - shared memory control

SYNOPSIS

#include <sys/ipc.h> #include <sys/shm.h>

int shmctl(int shmid, int cmd, struct shmid_ds *buf);

DESCRIPTION

shmctl() performs the control operation specified by cmd on the shared memory segment whose identifier is given in shmid.

The buf argument is a pointer to a shmid_ds structure, defined in <sys/shm.h> as follows:

struct shmid_ds {
    struct ipc_perm shm_perm;    /* Ownership and permissions */
    size_t          shm_segsz;   /* Size of segment (bytes) */
    time_t          shm_atime;   /* Last attach time */
    time_t          shm_dtime;   /* Last detach time */
    time_t          shm_ctime;   /* Last change time */
    pid_t           shm_cpid;    /* PID of creator */
    pid_t           shm_lpid;    /* PID of last shmat(2)/shmdt(2) */
    shmatt_t        shm_nattch;  /* No. of current attaches */
    ...
};

The ipc_perm structure is defined in <sys/ipc.h> as follows (the highlighted fields are settable using IPC_SET):

struct ipc_perm {
    key_t key;            /* Key supplied to shmget(2) */
    uid_t uid;            /* Effective UID of owner */
    gid_t gid;            /* Effective GID of owner */
    uid_t cuid;           /* Effective UID of creator */
    gid_t cgid;           /* Effective GID of creator */
    unsigned short mode;  /* Permissions + SHM_DEST and
                             SHM_LOCKED flags */
    unsigned short seq;   /* Sequence number */
};

Valid values for cmd are:

IPC_STAT
Copy information from the kernel data structure associated with shmid into the shmid_ds structure pointed to by buf. The caller must have read permission on the shared memory segment.
IPC_SET
Write the values of some members of the shmid_ds structure pointed to by buf to the kernel data structure associated with this shared memory segment, updating also its shm_ctime member. The following fields can be changed: shm_perm.uid, shm_perm.gid, and (the least significant 9 bits of) shm_perm.mode. The effective UID of the calling process must match the owner (shm_perm.uid) or creator (shm_perm.cuid) of the shared memory segment, or the caller must be privileged.
IPC_RMID
Mark the segment to be destroyed. The segment will only actually be destroyed after the last process detaches it (i.e., when the shm_nattch member of the associated structure shmid_ds is zero). The caller must be the owner or creator, or be privileged. If a segment has been marked for destruction, then the (non-standard) SHM_DEST flag of the shm_perm.mode field in the associated data structure retrieved by IPC_STAT will be set.

The caller must ensure that a segment is eventually destroyed; otherwise its pages that were faulted in will remain in memory or swap.

IPC_INFO (Linux specific)
Returns information about system-wide shared memory limits and parameters in the structure pointed to by buf. This structure is of type shminfo (thus, a cast is required), defined in <sys/shm.h> if the _GNU_SOURCE feature test macro is defined:

struct  shminfo {
    unsigned long shmmax; /* Max. segment size */
    unsigned long shmmin; /* Min. segment size; always 1 */
    unsigned long shmmni; /* Max. # of segments */
    unsigned long shmseg; /* Max. # of segments that a
                             process can attach; unused */
    unsigned long shmall; /* Max. # of pages of shared
                             memory, system-wide */
};
The shmmni, shmmax, and shmall settings can be changed via /proc files of the same name; see proc(5) for details.
SHM_INFO (Linux specific)
Returns a shm_info structure whose fields contain information about system resources consumed by shared memory. This structure is defined in <sys/shm.h> if the _GNU_SOURCE feature test macro is defined:

struct shm_info {
    int used_ids;           /* # of currently existing
                               segments */
    unsigned long shm_tot;  /* Total number of shared
                               memory pages */
    unsigned long shm_rss;  /* # of resident shared
                               memory pages */
    unsigned long shm_swp;  /* # of swapped shared
                               memory pages */
    unsigned long swap_attempts;  /* Unused since Linux 2.4 */
    unsigned long swap_successes; /* Unused since Linux 2.4 */
};
SHM_STAT (Linux specific)
Returns a shmid_ds structure as for IPC_STAT. However, the shmid argument is not a segment identifier, but instead an index into the kernel's internal array that maintains information about all shared memory segments on the system.

The caller can prevent or allow swapping of a shared memory segment with the following cmd values:

SHM_LOCK (Linux specific)
Prevent swapping of the shared memory segment. The caller must fault in any pages that are required to be present after locking is enabled. If a segment has been locked, then the (non-standard) SHM_LOCKED flag of the shm_perm.mode field in the associated data structure retrieved by IPC_STAT will be set.
SHM_UNLOCK (Linux specific)
Unlock the segment, allowing it to be swapped out.

In kernels before 2.6.10, only a privileged process could employ SHM_LOCK and SHM_UNLOCK. Since kernel 2.6.10, an unprivileged process can employ these operations if its effective UID matches the owner or creator UID of the segment, and (for SHM_LOCK) the amount of memory to be locked falls within the RLIMIT_MEMLOCK resource limit (see setrlimit(2)).

RETURN VALUE

A successful IPC_INFO or SHM_INFO operation returns the index of the highest used entry in the kernel's internal array recording information about all shared memory segments. (This information can be used with repeated SHM_STAT operations to obtain information about all shared memory segments on the system.) A successful SHM_STAT operation returns the identifier of the shared memory segment whose index was given in shmid. Other operations return 0 on success.

On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
IPC_STAT or SHM_STAT is requested and shm_perm.mode does not allow read access for shmid, and the calling process does not have the CAP_IPC_OWNER capability.
EFAULT
The argument cmd has value IPC_SET or IPC_STAT but the address pointed to by buf isn't accessible.
EIDRM
shmid points to a removed identifier.
EINVAL
shmid is not a valid identifier, or cmd is not a valid command. Or: for a SHM_STAT operation, the index value specified in shmid referred to an array slot that is currently unused.
ENOMEM
(In kernels since 2.6.9), SHM_LOCK was specified and the size of the to-be-locked segment would mean that the total bytes in locked shared memory segments would exceed the limit for the real user ID of the calling process. This limit is defined by the RLIMIT_MEMLOCK soft resource limit (see setrlimit(2)).
EOVERFLOW
IPC_STAT is attempted, and the GID or UID value is too large to be stored in the structure pointed to by buf.
EPERM
IPC_SET or IPC_RMID is attempted, and the effective user ID of the calling process is not that of the creator (found in shm_perm.cuid), or the owner (found in shm_perm.uid), and the process was not privileged (Linux: did not have the CAP_SYS_ADMIN capability).

Or (in kernels before 2.6.9), SHM_LOCK or SHM_UNLOCK was specified, but the process was not privileged (Linux: did not have the CAP_IPC_LOCK capability). (Since Linux 2.6.9, this error can also occur if the RLIMIT_MEMLOCK is 0 and the caller is not privileged.)

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

The IPC_INFO, SHM_STAT and SHM_INFO operations are used by the ipcs(8) program to provide information on allocated resources. In the future these may modified or moved to a /proc file system interface.

Linux permits a process to attach (shmat(2)) a shared memory segment that has already been marked for deletion using shmctl(IPC_RMID). This feature is not available on other Unix implementations; portable applications should avoid relying on it.

Various fields in a struct shmid_ds were shorts under Linux 2.2 and have become longs under Linux 2.4. To take advantage of this, a recompilation under glibc-2.1.91 or later should suffice. (The kernel distinguishes old and new calls by an IPC_64 flag in cmd.)

SEE ALSO

mlock(2), setrlimit(2), shmget(2), shmop(2), capabilities(7)


shmdt (2)

 Continue to this page.


shmget(2)

SHMGET

Section: Linux Programmer's Manual (2)
Updated: 2006-05-02 Return to Main Contents

NAME

shmget - allocates a shared memory segment

SYNOPSIS

#include <sys/ipc.h> #include <sys/shm.h>

int shmget(key_t key, size_t size, int shmflg);

DESCRIPTION

shmget() returns the identifier of the shared memory segment associated with the value of the argument key. A new shared memory segment, with size equal to the value of size rounded up to a multiple of PAGE_SIZE, is created if key has the value IPC_PRIVATE or key isn't IPC_PRIVATE, no shared memory segment corresponding to key exists, and IPC_CREAT is specified in shmflg.

If shmflg specifies both IPC_CREAT and IPC_EXCL and a shared memory segment already exists for key, then shmget() fails with errno set to EEXIST. (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)

The value shmflg is composed of:

IPC_CREAT
to create a new segment. If this flag is not used, then shmget() will find the segment associated with key and check to see if the user has permission to access the segment.
IPC_EXCL
used with IPC_CREAT to ensure failure if the segment already exists.
mode_flags
(least significant 9 bits) specifying the permissions granted to the owner, group, and world. These bits have the same format, and the same meaning, as the mode argument of open(2). Presently, the execute permissions are not used by the system.
SHM_HUGETLB (since Linux 2.6)
Allocate the segment using "huge pages." See the kernel source file Documentation/vm/hugetlbpage.txt for further information.
SHM_NORESERVE (since Linux 2.6.15)
This flag serves the same purpose as the mmap(2) MAP_NORESERVE flag. Do not reserve swap space for this segment. When swap space is reserved, one has the guarantee that it is possible to modify the segment. When swap space is not reserved one might get SIGSEGV upon a write if no physical memory is available. See also the discussion of the file /proc/sys/vm/overcommit_memory in proc(5).

When a new shared memory segment is created, its contents are initialized to zero values, and its associated data structure, shmid_ds (see shmctl(2)), is initialized as follows:

shm_perm.cuid and shm_perm.uid are set to the effective user ID of the calling process.
shm_perm.cgid and shm_perm.gid are set to the effective group ID of the calling process.
The least significant 9 bits of shm_perm.mode are set to the least significant 9 bit of shmflg.
shm_segsz is set to the value of size.
shm_lpid, shm_nattch, shm_atime and shm_dtime are set to 0.
shm_ctime is set to the current time.

If the shared memory segment already exists, the permissions are verified, and a check is made to see if it is marked for destruction.

RETURN VALUE

A valid segment identifier, shmid, is returned on success, -1 on error.

ERRORS

On failure, errno is set to one of the following:
EACCES
The user does not have permission to access the shared memory segment, and does not have the CAP_IPC_OWNER capability.
EEXIST
IPC_CREAT | IPC_EXCL was specified and the segment exists.
EINVAL
A new segment was to be created and size < SHMMIN or size > SHMMAX, or no new segment was to be created, a segment with given key existed, but size is greater than the size of that segment.
ENFILE
The system limit on the total number of open files has been reached.
ENOENT
No segment exists for the given key, and IPC_CREAT was not specified.
ENOMEM
No memory could be allocated for segment overhead.
ENOSPC
All possible shared memory IDs have been taken (SHMMNI), or allocating a segment of the requested size would cause the system to exceed the system-wide limit on shared memory (SHMALL).
EPERM
The SHM_HUGETLB flag was specified, but the caller was not privileged (did not have the CAP_IPC_LOCK capability).

CONFORMING TO

SVr4, POSIX.1-2001.

SHM_HUGETLB is a non-portable Linux extension.

NOTES

IPC_PRIVATE isn't a flag field but a key_t type. If this special value is used for key, the system call ignores everything but the least significant 9 bits of shmflg and creates a new shared memory segment (on success).

The following limits on shared memory segment resources affect the shmget() call:

SHMALL
System wide maximum of shared memory pages (on Linux, this limit can be read and modified via /proc/sys/kernel/shmall).
SHMMAX
Maximum size in bytes for a shared memory segment: policy dependent (on Linux, this limit can be read and modified via /proc/sys/kernel/shmmax).
SHMMIN
Minimum size in bytes for a shared memory segment: implementation dependent (currently 1 byte, though PAGE_SIZE is the effective minimum size).
SHMMNI
System wide maximum number of shared memory segments: implementation dependent (currently 4096, was 128 before Linux 2.3.99; on Linux, this limit can be read and modified via /proc/sys/kernel/shmmni).

The implementation has no specific limits for the per process maximum number of shared memory segments (SHMSEG).

Linux Notes

Until version 2.3.30 Linux would return EIDRM for a shmget() on a shared memory segment scheduled for deletion.

BUGS

The name choice IPC_PRIVATE was perhaps unfortunate, IPC_NEW would more clearly show its function.

SEE ALSO

shmat(2), shmctl(2), shmdt(2), ftok(3), capabilities(7), svipc(7)


shmop(2)

SHMOP

Section: Linux Programmer's Manual (2)
Updated: 2004-11-10 Return to Main Contents

NAME

shmop, shmat, shmdt - shared memory operations

SYNOPSIS

#include <sys/types.h>
#include <sys/shm.h>

void *shmat(int shmid, const void *shmaddr, int shmflg);

int shmdt(const void *shmaddr);

DESCRIPTION

shmat() attaches the shared memory segment identified by shmid to the address space of the calling process. The attaching address is specified by shmaddr with one of the following criteria:

If shmaddr is NULL, the system chooses a suitable (unused) address at which to attach the segment.

If shmaddr isn't NULL and SHM_RND is specified in shmflg, the attach occurs at the address equal to shmaddr rounded down to the nearest multiple of SHMLBA. Otherwise shmaddr must be a page-aligned address at which the attach occurs.

If SHM_RDONLY is specified in shmflg, the segment is attached for reading and the process must have read permission for the segment. Otherwise the segment is attached for read and write and the process must have read and write permission for the segment. There is no notion of a write-only shared memory segment.

The (Linux-specific) SHM_REMAP flag may be specified in shmflg to indicate that the mapping of the segment should replace any existing mapping in the range starting at shmaddr and continuing for the size of the segment. (Normally an EINVAL error would result if a mapping already exists in this address range.) In this case, shmaddr must not be NULL.

The brk(2) value of the calling process is not altered by the attach. The segment will automatically be detached at process exit. The same segment may be attached as a read and as a read-write one, and more than once, in the process's address space.

A successful shmat() call updates the members of the shmid_ds structure (see shmctl(2)) associated with the shared memory segment as follows:

shm_atime is set to the current time.
shm_lpid is set to the process-ID of the calling process.
shm_nattch is incremented by one.

shmdt() detaches the shared memory segment located at the address specified by shmaddr from the address space of the calling process. The to-be-detached segment must be currently attached with shmaddr equal to the value returned by the attaching shmat() call.

On a successful shmdt() call the system updates the members of the shmid_ds structure associated with the shared memory segment as follows:

shm_dtime is set to the current time.
shm_lpid is set to the process-ID of the calling process.
shm_nattch is decremented by one. If it becomes 0 and the segment is marked for deletion, the segment is deleted.

After a fork(2) the child inherits the attached shared memory segments.

After an execve(2) all attached shared memory segments are detached from the process.

Upon _exit(2) all attached shared memory segments are detached from the process.

RETURN VALUE

On success shmat() returns the address of the attached shared memory segment; on error (void *) -1 is returned, and errno is set to indicate the cause of the error.

On success shmdt() returns 0; on error -1 is returned, and errno is set to indicate the cause of the error.

ERRORS

When shmat() fails, errno is set to one of the following:
EACCES
The calling process does not have the required permissions for the requested attach type, and does not have the CAP_IPC_OWNER capability.
EINVAL
Invalid shmid value, unaligned (i.e., not page-aligned and SHM_RND was not specified) or invalid shmaddr value, or failing attach at brk(2), or SHM_REMAP was specified and shmaddr was NULL.
ENOMEM
Could not allocate memory for the descriptor or for the page tables.

When shmdt() fails, errno is set as follows:

EINVAL
There is no shared memory segment attached at shmaddr; or, shmaddr is not aligned on a page boundary.

CONFORMING TO

SVr4, POSIX.1-2001.

In SVID 3 (or perhaps earlier) the type of the shmaddr argument was changed from char * into const void *, and the returned type of shmat() from char * into void *. (Linux libc4 and libc5 have the char * prototypes; glibc2 has void *.)

NOTES

Using shmat() with shmaddr equal to NULL is the preferred, portable way of attaching a shared memory segment. Be aware that the shared memory segment attached in this way may be attached at different addresses in different processes. Therefore, any pointers maintained within the shared memory must be made relative (typically to the starting address of the segment), rather than absolute.

On Linux, it is possible to attach a shared memory segment even if it is already marked to be deleted. However, POSIX.1-2001 does not specify this behavior and many other implementations do not support it.

The following system parameter affects shmat():

SHMLBA Segment low boundary address multiple. Must be page aligned. For the current implementation the SHMLBA value is PAGE_SIZE.

The implementation places no intrinsic limit on the per-process maximum number of shared memory segments (SHMSEG).

SEE ALSO

brk(2), mmap(2), shmctl(2), shmget(2), capabilities(7), svipc(7)


signal(2)

SIGNAL

Section: Linux Programmer's Manual (2)
Updated: 2007-06-03 Return to Main Contents

NAME

signal - ANSI C signal handling

SYNOPSIS

#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler);

DESCRIPTION

The behavior of signal() varies across Unix versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead. See Portability below.

signal() sets the disposition of the signal signum to handler, which is either SIG_IGN, SIG_DFL, or the address of a programmer-defined function (a "signal handler"),

If the signal signum is delivered to the process, then one of the following happens:

*
If the disposition is set to SIG_IGN, then the signal is ignored.
*
If the disposition is set to SIG_DFL, then the default action associated with the signal (see signal(7)) occurs.
*
If the disposition is set to a function, then first either the disposition is reset to SIG_DFL, or the signal is blocked (see Portability below), and then handler is called with argument signum. If invocation of the handler caused the signal to be blocked, then the signal is unblocked upon return from the handler.

The signals SIGKILL and SIGSTOP cannot be caught or ignored.

RETURN VALUE

signal() returns the previous value of the signal handler, or SIG_ERR on error.

ERRORS

EINVAL
signum is invalid.

CONFORMING TO

C89, C99, POSIX.1-2001.

NOTES

The effects of signal() in a multi-threaded process are unspecified.

According to POSIX, the behavior of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(2) or the raise(3). Integer division by zero has undefined result. On some architectures it will generate a SIGFPE signal. (Also dividing the most negative integer by -1 may generate SIGFPE.) Ignoring this signal might lead to an endless loop.

See sigaction(2) for details on what happens when SIGCHLD is set to SIG_IGN.

See signal(7) for a list of the async-signal-safe functions that can be safely called inside from inside a signal handler.

The use of sighandler_t is a GNU extension. Various versions of libc predefine this type; libc4 and libc5 define SignalHandler, glibc defines sig_t and, when _GNU_SOURCE is defined, also sighandler_t.

Portability

The original Unix signal() would reset the handler to SIG_DFL, and System V (and the Linux kernel and libc4,5) does the same. On the other hand, BSD does not reset the handler, but blocks new instances of this signal from occurring during a call of the handler. The glibc2 library follows the BSD behavior.

If one on a libc5 system includes <bsd/signal.h> instead of <signal.h> then signal() is redefined as __bsd_signal() and signal() has the BSD semantics. This is not recommended.

If one on a glibc2 system defines a feature test macro such as _XOPEN_SOURCE or uses a separate sysv_signal(3) function, one obtains classical behavior. This is not recommended.

SEE ALSO

kill(1), alarm(2), kill(2), pause(2), sigaction(2), sigpending(2), sigprocmask(2), sigqueue(2), sigsuspend(2), bsd_signal(3), killpg(3), raise(3), siginterrupt(3), sigsetops(3), sigvec(3), sysv_signal(3), feature_test_macros(7), signal(7)


stty (2)

 Continue to this page.


swapon(2)

SWAPON

Section: Linux Programmer's Manual (2)
Updated: 2004-10-10 Return to Main Contents

NAME

swapon, swapoff - start/stop swapping to file/device

SYNOPSIS

#include <unistd.h>
#include <asm/page.h> /* to find PAGE_SIZE */
#include <sys/swap.h>

int swapon(const char *path, int swapflags);
int swapoff(const char *path);

DESCRIPTION

swapon() sets the swap area to the file or block device specified by path. swapoff() stops swapping to the file or block device specified by path.

swapon() takes a swapflags argument. If swapflags has the SWAP_FLAG_PREFER bit turned on, the new swap area will have a higher priority than default. The priority is encoded within swapflags as:

(prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK

These functions may only be used by a privileged process (one having the CAP_SYS_ADMIN capability).

Priority

Each swap area has a priority, either high or low. The default priority is low. Within the low-priority areas, newer areas are even lower priority than older areas.

All priorities set with swapflags are high-priority, higher than default. They may have any non-negative value chosen by the caller. Higher numbers mean higher priority.

Swap pages are allocated from areas in priority order, highest priority first. For areas with different priorities, a higher-priority area is exhausted before using a lower-priority area. If two or more areas have the same priority, and it is the highest priority available, pages are allocated on a round-robin basis between them.

As of Linux 1.3.6, the kernel usually follows these rules, but there are exceptions.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBUSY
(for swapon()) The specified path is already being used as a swap area.
EINVAL
The file path exists, but refers neither to a regular file nor to a block device; or, for swapon(), the indicated path does not contain a valid swap signature; or, for swapoff(), path is not currently a swap area.
ENFILE
The system limit on the total number of open files has been reached.
ENOENT
The file path does not exist.
ENOMEM
The system has insufficient memory to start swapping.
EPERM
The caller does not have the CAP_SYS_ADMIN capability, or all MAX_SWAPFILES (earlier 8; 32 since Linux 2.4.10) are in use.

CONFORMING TO

These functions are Linux specific and should not be used in programs intended to be portable. The second swapflags argument was introduced in Linux 1.3.2.

NOTES

The partition or path must be prepared with mkswap(8).

SEE ALSO

mkswap(8), swapoff(8), swapon(8)


socket(2)

SOCKET

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

socket - create an endpoint for communication

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>

int socket(int domain, int type, int protocol);

DESCRIPTION

socket() creates an endpoint for communication and returns a descriptor.

The domain parameter specifies a communication domain; this selects the protocol family which will be used for communication. These families are defined in <sys/socket.h>. The currently understood formats include:
Name | Purpose | Man page
PF_UNIX, PF_LOCAL | Local communication | unix(7)
PF_INET | IPv4 Internet protocols | ip(7)
PF_INET6 | IPv6 Internet protocols | ipv6(7)
PF_IPX | IPX - Novell protocols |
PF_NETLINK | Kernel user interface device | netlink(7)
PF_X25 | ITU-T X.25 / ISO-8208 protocol | x25(7)
PF_AX25 | Amateur radio AX.25 protocol |
PF_ATMPVC | Access to raw ATM PVCs |
PF_APPLETALK | Appletalk | ddp(7)
PF_PACKET | Low level packet interface | packet(7)

The socket has the indicated type, which specifies the communication semantics. Currently defined types are:

SOCK_STREAM
Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported.
SOCK_DGRAM
Supports datagrams (connectionless, unreliable messages of a fixed maximum length).
SOCK_SEQPACKET
Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read system call.
SOCK_RAW
Provides raw network protocol access.
SOCK_RDM
Provides a reliable datagram layer that does not guarantee ordering.
SOCK_PACKET
Obsolete and should not be used in new programs; see packet(7).

Some socket types may not be implemented by all protocol families; for example, SOCK_SEQPACKET is not implemented for AF_INET.

The protocol specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family, in which case protocol can be specified as 0. However, it is possible that many protocols may exist, in which case a particular protocol must be specified in this manner. The protocol number to use is specific to the ``communication domain'' in which communication is to take place; see protocols(5). See getprotoent(3) on how to map protocol name strings to protocol numbers.

Sockets of type SOCK_STREAM are full-duplex byte streams, similar to pipes. They do not preserve record boundaries. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect(2) call. Once connected, data may be transferred using read(2) and write(2) calls or some variant of the send(2) and recv(2) calls. When a session has been completed a close(2) may be performed. Out-of-band data may also be transmitted as described in send(2) and received as described in recv(2).

The communications protocols which implement a SOCK_STREAM ensure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, then the connection is considered to be dead. When SO_KEEPALIVE is enabled on the socket the protocol checks in a protocol-specific manner if the other end is still alive. A SIGPIPE signal is raised if a process sends or receives on a broken stream; this causes naive processes, which do not handle the signal, to exit. SOCK_SEQPACKET sockets employ the same system calls as SOCK_STREAM sockets. The only difference is that read(2) calls will return only the amount of data requested, and any data remaining in the arriving packet will be discarded. Also all message boundaries in incoming datagrams are preserved.

SOCK_DGRAM and SOCK_RAW sockets allow sending of datagrams to correspondents named in sendto(2) calls. Datagrams are generally received with recvfrom(2), which returns the next datagram along with the address of its sender.

SOCK_PACKET is an obsolete socket type to receive raw packets directly from the device driver. Use packet(7) instead.

An fcntl(2) F_SETOWN operation can be used to specify a process or process group to receive a SIGURG signal when the out-of-band data arrives or SIGPIPE signal when a SOCK_STREAM connection breaks unexpectedly. This operation may also be used to set the process or process group that receives the I/O and asynchronous notification of I/O events via SIGIO. Using F_SETOWN is equivalent to an ioctl(2) call with the FIOSETOWN or SIOCSPGRP argument.

When the network signals an error condition to the protocol module (e.g., using a ICMP message for IP) the pending error flag is set for the socket. The next operation on this socket will return the error code of the pending error. For some protocols it is possible to enable a per-socket error queue to retrieve detailed information about the error; see IP_RECVERR in ip(7).

The operation of sockets is controlled by socket level options. These options are defined in <sys/socket.h>. The functions setsockopt(2) and getsockopt(2) are used to set and get options, respectively.

RETURN VALUE

On success, a file descriptor for the new socket is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Permission to create a socket of the specified type and/or protocol is denied.
EAFNOSUPPORT
The implementation does not support the specified address family.
EINVAL
Unknown protocol, or protocol family not available.
EMFILE
Process file table overflow.
ENFILE
The system limit on the total number of open files has been reached.
ENOBUFS or ENOMEM
Insufficient memory is available. The socket cannot be created until sufficient resources are freed.
EPROTONOSUPPORT
The protocol type or the specified protocol is not supported within this domain.

Other errors may be generated by the underlying protocol modules.

CONFORMING TO

4.4BSD, POSIX.1-2001. socket() appeared in 4.2BSD. It is generally portable to/from non-BSD systems supporting clones of the BSD socket layer (including System V variants).

NOTES

The manifest constants used under 4.x BSD for protocol families are PF_UNIX, PF_INET, etc., while AF_UNIX etc. are used for address families. However, already the BSD man page promises: "The protocol family generally is the same as the address family", and subsequent standards use AF_* everywhere.

BUGS

SOCK_UUCP is not implemented yet.

EXAMPLE

An example of the use of socket() is shown in getaddrinfo(3).

SEE ALSO

accept(2), bind(2), connect(2), fcntl(2), getpeername(2), getsockname(2), getsockopt(2), ioctl(2), listen(2), read(2), recv(2), select(2), send(2), shutdown(2), socketpair(2), write(2), getprotoent(3), ip(7), socket(7), tcp(7), udp(7), unix(7)

"An Introductory 4.3BSD Interprocess Communication Tutorial" is reprinted in UNIX Programmer's Supplementary Documents Volume 1.

"BSD Interprocess Communication Tutorial" is reprinted in UNIX Programmer's Supplementary Documents Volume 1.


socketpair(2)

SOCKETPAIR

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

socketpair - create a pair of connected sockets

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>

int socketpair(int d, int type, int protocol, int sv[2]);

DESCRIPTION

The socketpair() call creates an unnamed pair of connected sockets in the specified domain d, of the specified type, and using the optionally specified protocol. The descriptors used in referencing the new sockets are returned in sv[0] and sv[1]. The two sockets are indistinguishable.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EAFNOSUPPORT
The specified address family is not supported on this machine.
EFAULT
The address sv does not specify a valid part of the process address space.
EMFILE
Too many descriptors are in use by this process.
ENFILE
The system limit on the total number of open files has been reached.
EOPNOTSUPP
The specified protocol does not support creation of socket pairs.
EPROTONOSUPPORT
The specified protocol is not supported on this machine.

CONFORMING TO

4.4BSD, POSIX.1-2001. The socketpair() function call appeared in 4.2BSD. It is generally portable to/from non-BSD systems supporting clones of the BSD socket layer (including System V variants).

NOTES

On Linux, the only supported domain for this call is AF_UNIX (or synonymously, AF_LOCAL). (Most implementations have the same restriction.)

SEE ALSO

pipe(2), read(2), socket(2), write(2), unix(7)


shutdown(2)

SHUTDOWN

Section: Linux Programmer's Manual (2)
Updated: 1993-07-24 Return to Main Contents

NAME

shutdown - shut down part of a full-duplex connection

SYNOPSIS

#include <sys/socket.h>

int shutdown(int s, int how);

DESCRIPTION

The shutdown() call causes all or part of a full-duplex connection on the socket associated with s to be shut down. If how is SHUT_RD, further receptions will be disallowed. If how is SHUT_WR, further transmissions will be disallowed. If how is SHUT_RDWR, further receptions and transmissions will be disallowed.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
s is not a valid descriptor.
ENOTCONN
The specified socket is not connected.
ENOTSOCK
s is a file, not a socket.

CONFORMING TO

POSIX.1-2001, 4.4BSD (the shutdown() function call first appeared in 4.2BSD).

NOTES

The constants SHUT_RD, SHUT_WR, SHUT_RDWR have the value 0, 1, 2, respectively, and are defined in <sys/socket.h> since glibc-2.1.91.

SEE ALSO

connect(2), socket(2)


symlink(2)

SYMLINK

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

symlink - make a new name for a file

SYNOPSIS

#include <unistd.h>

int symlink(const char *oldpath, const char *newpath);

DESCRIPTION

symlink() creates a symbolic link named newpath which contains the string oldpath.

Symbolic links are interpreted at run-time as if the contents of the link had been substituted into the path being followed to find a file or directory.

Symbolic links may contain .. path components, which (if used at the start of the link) refer to the parent directories of that in which the link resides.

A symbolic link (also known as a soft link) may point to an existing file or to a nonexistent one; the latter case is known as a dangling link.

The permissions of a symbolic link are irrelevant; the ownership is ignored when following the link, but is checked when removal or renaming of the link is requested and the link is in a directory with the sticky bit (S_ISVTX) set.

If newpath exists it will not be overwritten.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Write access to the directory containing newpath is denied, or one of the directories in the path prefix of newpath did not allow search permission. (See also path_resolution(7).)
EEXIST
newpath already exists.
EFAULT
oldpath or newpath points outside your accessible address space.
EIO
An I/O error occurred.
ELOOP
Too many symbolic links were encountered in resolving newpath.
ENAMETOOLONG
oldpath or newpath was too long.
ENOENT
A directory component in newpath does not exist or is a dangling symbolic link, or oldpath is the empty string.
ENOMEM
Insufficient kernel memory was available.
ENOSPC
The device containing the file has no room for the new directory entry.
ENOTDIR
A component used as a directory in newpath is not, in fact, a directory.
EPERM
The filesystem containing newpath does not support the creation of symbolic links.
EROFS
newpath is on a read-only filesystem.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

No checking of oldpath is done.

Deleting the name referred to by a symlink will actually delete the file (unless it also has other hard links). If this behavior is not desired, use link(2).

SEE ALSO

ln(1), link(2), lstat(2), open(2), readlink(2), rename(2), symlinkat(2), unlink(2) path_resolution(7)


sync(2)

SYNC

Section: Linux Programmer's Manual (2)
Updated: 2001-10-10 Return to Main Contents

NAME

sync - commit buffer cache to disk

SYNOPSIS

#include <unistd.h>

void sync(void);

DESCRIPTION

sync() first commits inodes to buffers, and then buffers to disk.

ERRORS

This function is always successful.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

Since glibc 2.2.2 the Linux prototype is as listed above, following the various standards. In libc4, libc5, and glibc up to 2.2.1 it was "int sync(void)", and sync() always returned 0.

BUGS

According to the standard specification (e.g., POSIX.1-2001), sync() schedules the writes, but may return before the actual writing is done. However, since version 1.3.20 Linux does actually wait. (This still does not guarantee data integrity: modern disks have large caches.)

SEE ALSO

bdflush(2), fdatasync(2), fsync(2), sync(8), update(8)


sysctl(2)

SYSCTL

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

sysctl - read/write system parameters

SYNOPSIS

#include <unistd.h>

#include <linux/sysctl.h>

int _sysctl(struct __sysctl_args *args);

DESCRIPTION

The _sysctl() call reads and/or writes kernel parameters. For example, the hostname, or the maximum number of open files. The argument has the form

struct __sysctl_args {
    int    *name;    /* integer vector describing variable */
    int     nlen;    /* length of this vector */
    void   *oldval;  /* 0 or address where to store old value */
    size_t *oldlenp; /* available room for old value,
                        overwritten by actual size of old value */
    void   *newval;  /* 0 or address of new value */
    size_t  newlen;  /* size of new value */
};

This call does a search in a tree structure, possibly resembling a directory tree under /proc/sys, and if the requested item is found calls some appropriate routine to read or modify the value.

RETURN VALUE

Upon successful completion, _sysctl() returns 0. Otherwise, a value of -1 is returned and errno is set to indicate the error.

ERRORS

EFAULT
The invocation asked for the previous value by setting oldval non-NULL, but allowed zero room in oldlenp.
ENOTDIR
name was not found.
EPERM
No search permission for one of the encountered `directories', or no read permission where oldval was non-zero, or no write permission where newval was non-zero.

CONFORMING TO

This call is Linux specific, and should not be used in programs intended to be portable. A sysctl() call has been present in Linux since version 1.3.57. It originated in 4.4BSD. Only Linux has the /proc/sys mirror, and the object naming schemes differ between Linux and 4.4BSD, but the declaration of the sysctl(2) function is the same in both.

BUGS

The object names vary between kernel versions. THIS MAKES THIS SYSTEM CALL WORTHLESS FOR APPLICATIONS. Use the /proc/sys interface instead.

Not all available objects are properly documented.

It is not yet possible to change operating system by writing to /proc/sys/kernel/ostype.

EXAMPLE

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <linux/sysctl.h>

int _sysctl(struct __sysctl_args *args );

#define OSNAMESZ 100

int
main(void)
{
    struct __sysctl_args args;
    char osname[OSNAMESZ];
    size_t osnamelth;
    int name[] = { CTL_KERN, KERN_OSTYPE };

    memset(&args, 0, sizeof(struct __sysctl_args));
    args.name = name;
    args.nlen = sizeof(name)/sizeof(name[0]);
    args.oldval = osname;
    args.oldlenp = &osnamelth;

    osnamelth = sizeof(osname);

    if (syscall(SYS__sysctl, &args) == -1) {
        perror("_sysctl");
        exit(EXIT_FAILURE);
    }
    printf("This machine is running %*s\n", osnamelth, osname);
    exit(EXIT_SUCCESS);
}

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

SEE ALSO

proc(5)


sysinfo(2)

SYSINFO

Section: Linux Programmer's Manual (2)
Updated: 1997-08-25 Return to Main Contents

NAME

sysinfo - returns information on overall system statistics

SYNOPSIS

#include <sys/sysinfo.h>

int sysinfo(struct sysinfo *info);

DESCRIPTION

Until Linux 2.3.16, sysinfo() used to return information in the following structure:

struct sysinfo {
    long uptime;             /* Seconds since boot */
    unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
    unsigned long totalram;  /* Total usable main memory size */
    unsigned long freeram;   /* Available memory size */
    unsigned long sharedram; /* Amount of shared memory */
    unsigned long bufferram; /* Memory used by buffers */
    unsigned long totalswap; /* Total swap space size */
    unsigned long freeswap;  /* swap space still available */
    unsigned short procs;    /* Number of current processes */
    char _f[22];             /* Pads structure to 64 bytes */
};

and the sizes were given in bytes.

Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure is:

struct sysinfo {
    long uptime;             /* Seconds since boot */
    unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
    unsigned long totalram;  /* Total usable main memory size */
    unsigned long freeram;   /* Available memory size */
    unsigned long sharedram; /* Amount of shared memory */
    unsigned long bufferram; /* Memory used by buffers */
    unsigned long totalswap; /* Total swap space size */
    unsigned long freeswap;  /* swap space still available */
    unsigned short procs;    /* Number of current processes */
    unsigned long totalhigh; /* Total high memory size */
    unsigned long freehigh;  /* Available high memory size */
    unsigned int mem_unit;   /* Memory unit size in bytes */
    char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};

and the sizes are given as multiples of mem_unit bytes.

sysinfo() provides a simple way of getting overall system statistics. This is more portable than reading /dev/kmem. For an example of its use, see intro(2).

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
pointer to struct sysinfo is invalid

CONFORMING TO

This function is Linux specific, and should not be used in programs intended to be portable.

The Linux kernel has a sysinfo() system call since 0.98.pl6. Linux libc contains a sysinfo() routine since 5.3.5, and glibc has one since 1.90.

SEE ALSO

proc(5)


time(2)

TIME

Section: Linux Programmer's Manual (2)
Updated: 1997-09-09 Return to Main Contents

NAME

time - get time in seconds

SYNOPSIS

#include <time.h>

time_t time(time_t *t);

DESCRIPTION

time() returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds.

If t is non-NULL, the return value is also stored in the memory pointed to by t.

RETURN VALUE

On success, the value of time in seconds since the Epoch is returned. On error, ((time_t)-1) is returned, and errno is set appropriately.

ERRORS

EFAULT
t points outside your accessible address space.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001. POSIX does not specify any error conditions.

NOTES

POSIX.1 defines seconds since the Epoch as a value to be interpreted as the number of seconds between a specified time and the Epoch, according to a formula for conversion from UTC equivalent to conversion on the naive basis that leap seconds are ignored and all years divisible by 4 are leap years. This value is not the same as the actual number of seconds between the time and the Epoch, because of leap seconds and because clocks are not required to be synchronized to a standard reference. The intention is that the interpretation of seconds since the Epoch values be consistent; see POSIX.1 Annex B 2.2.2 for further rationale.

SEE ALSO

date(1), gettimeofday(2), ctime(3), ftime(3), time(7)


access(2)

ACCESS

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

access - check user's permissions for a file

SYNOPSIS

#include <unistd.h>

int access(const char *pathname, int mode);

DESCRIPTION

access() checks whether the calling process would be allowed to read, write or test for existence of the file (or other file system object) whose name is pathname. If pathname is a symbolic link permissions of the file referred to by this symbolic link are tested.

mode is either the value F_OK or a mask consisting of the bitwise OR of one or more of R_OK, W_OK and X_OK.

R_OK, W_OK and X_OK request checking whether the file exists and has read, write and execute permissions, respectively. F_OK just requests checking for the existence of the file.

The tests depend on the permissions of the directories occurring in the path to the file, as given in pathname, and on the permissions of directories and files referred to by symbolic links encountered on the way.

The check is done with the calling process's real UID and GID, rather than with the effective IDs as is done when actually attempting an operation. This is to allow set-user-ID programs to easily determine the invoking user's authority.

Only access bits are checked, not the file type or contents. Therefore, if a directory is found to be "writable," it probably means that files can be created in the directory, and not that the directory can be written as a file. Similarly, a DOS file may be found to be "executable," but the execve(2) call will still fail.

If the calling process has appropriate privileges, an implementation may indicate success for X_OK even if none of the execute file permission bits are set.

RETURN VALUE

On success (all requested permissions granted), zero is returned. On error (at least one bit in mode asked for a permission that is denied, or some other error occurred), -1 is returned, and errno is set appropriately.

ERRORS

access() shall fail if:
EACCES
The requested access would be denied to the file, or search permission is denied for one of the directories in the path prefix of pathname. (See also path_resolution(7).)
ELOOP
Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname is too long.
ENOENT
A component of pathname does not exist or is a dangling symbolic link.
ENOTDIR
A component used as a directory in pathname is not, in fact, a directory.
EROFS
Write permission was requested for a file on a read-only filesystem.

access() may fail if:

EFAULT
pathname points outside your accessible address space.
EINVAL
mode was incorrectly specified.
EIO
An I/O error occurred.
ENOMEM
Insufficient kernel memory was available.
ETXTBSY
Write access was requested to an executable which is being executed.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

access() returns an error if any of the access types in the requested call fails, even if other types might be successful.

access() may not work correctly on NFS file systems with UID mapping enabled, because UID mapping is done on the server and hidden from the client, which checks permissions.

Warning: Using access() to check if a user is authorized to, for example, open a file before actually doing so using open(2) creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it.

Linux Notes

In kernels before 2.6.20, access() ignored the effect of the MS_NOEXEC flag if it was used to mount(2) the underlying file system. Since kernel 2.6.20, access() honors this flag.

SEE ALSO

chmod(2), chown(2), faccessat(2), open(2), setgid(2), setuid(2), stat(2), euidaccess(3), credentials(7), path_resolution(7)


setsid(2)

SETSID

Section: Linux Programmer's Manual (2)
Updated: 1994-08-27 Return to Main Contents

NAME

setsid - creates a session and sets the process group ID

SYNOPSIS

#include <unistd.h>

pid_t setsid(void);

DESCRIPTION

setsid() creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session, the process group leader of the new process group, and has no controlling tty. The process group ID and session ID of the calling process are set to the PID of the calling process. The calling process will be the only process in this new process group and in this new session.

RETURN VALUE

The session ID of the calling process.

ERRORS

On error, -1 is returned, and errno is set. The only error which can happen is EPERM. It is returned when the process group ID of any process equals the PID of the calling process. Thus, in particular, setsid() fails if the calling process is already a process group leader.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

A child created via fork(2) inherits its parent's session ID. The session ID is preserved across an execve(2).

A process group leader is a process with process group ID equal to its PID. In order to be sure that setsid() will succeed, fork(2) and _exit(2), and have the child do setsid().

SEE ALSO

setpgid(2), setpgrp(2), tcgetsid(3)


setsockopt (2)

 Continue to this page.


utimes (2)

 Continue to this page.


vfork(2)

VFORK

Section: Linux Programmer's Manual (2)
Updated: 1999-11-01 Return to Main Contents

NAME

vfork - create a child process and block parent

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

pid_t vfork(void);

DESCRIPTION

Standard Description

(From SUSv2 / POSIX draft.) The vfork() function has the same effect as fork(2), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit(2) or one of the exec(3) family of functions.

Linux Description

vfork(), just like fork(2), creates a child process of the calling process. For details and return value and errors, see fork(2).

vfork() is a special case of clone(2). It is used to create new processes without copying the page tables of the parent process. It may be useful in performance sensitive applications where a child will be created which then immediately issues an execve(2).

vfork() differs from fork(2) in that the parent is suspended until the child makes a call to execve(2) or _exit(2). The child shares all memory with its parent, including the stack, until execve(2) is issued by the child. The child must not return from the current function or call exit(3), but may call _exit(2).

Signal handlers are inherited, but not shared. Signals to the parent arrive after the child releases the parent's memory.

Historic Description

Under Linux, fork(2) is implemented using copy-on-write pages, so the only penalty incurred by fork(2) is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child. However, in the bad old days a fork(2) would require making a complete copy of the caller's data space, often needlessly, since usually immediately afterwards an exec(3) is done. Thus, for greater efficiency, BSD introduced the vfork() system call, that did not fully copy the address space of the parent process, but borrowed the parent's memory and thread of control until a call to execve(2) or an exit occurred. The parent process was suspended while the child was using its resources. The use of vfork() was tricky: for example, not modifying data in the parent process depended on knowing which variables are held in a register.

CONFORMING TO

4.3BSD, POSIX.1-2001. The requirements put on vfork() by the standards are weaker than those put on fork(2), so an implementation where the two are synonymous is compliant. In particular, the programmer cannot rely on the parent remaining blocked until a call of execve(2) or _exit(2) and cannot rely on any specific behavior wth respect to shared memory.

NOTES

Linux Notes

Fork handlers established using pthread_atfork(3) are not called when a multithreaded program employing the NPTL threading library calls vfork(). Fork handlers are called in this case in a program using the LinuxThreads threading library. (See pthreads(7) for a description of Linux threading libraries.)

History

The vfork() system call appeared in 3.0BSD. In 4.4BSD it was made synonymous to fork(2) but NetBSD introduced it again, cf. http://www.netbsd.org/Documentation/kernel/vfork.html . In Linux, it has been equivalent to fork(2) until 2.2.0-pre6 or so. Since 2.2.0-pre9 (on i386, somewhat later on other architectures) it is an independent system call. Support was added in glibc 2.0.112.

BUGS

It is rather unfortunate that Linux revived this specter from the past. The BSD man page states: "This system call will be eliminated when proper system sharing mechanisms are implemented. Users should not depend on the memory sharing semantics of vfork() as it will, in that case, be made synonymous to fork(2)."

Details of the signal handling are obscure and differ between systems. The BSD man page states: "To avoid a possible deadlock situation, processes that are children in the middle of a vfork() are never sent SIGTTOU or SIGTTIN signals; rather, output or ioctls are allowed and input attempts result in an end-of-file indication."

SEE ALSO

clone(2), execve(2), fork(2), unshare(2), wait(2)


vm86(2)

VM86

Section: Linux Programmer's Manual (2)
Updated: 1997-07-17 Return to Main Contents

NAME

vm86old, vm86 - enter virtual 8086 mode

SYNOPSIS

#include <sys/vm86.h>

int vm86old(struct vm86_struct *info);

int vm86(unsigned long fn, struct vm86plus_struct *v86);

DESCRIPTION

The system call vm86() was introduced in Linux 0.97p2. In Linux 2.1.15 and 2.0.28 it was renamed to vm86old(), and a new vm86() was introduced. The definition of `struct vm86_struct' was changed in 1.1.8 and 1.1.9.

These calls cause the process to enter VM86 mode (virtual-8086 in Intel literature), and are used by dosemu.

VM86 mode is an emulation of real mode within a protected mode task.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
This return value is specific to i386 and indicates a problem with getting userspace data.
ENOSYS
This return value indicates the call is not implemented on the present architecture.
EPERM
Saved kernel stack exists. (This is a kernel sanity check; the saved stack should only exist within vm86 mode itself.)

CONFORMING TO

This call is specific to Linux on Intel processors, and should not be used in programs intended to be portable.


setresgid (2)

 Continue to this page.


sigaction(2)

SIGACTION

Section: Linux Programmer's Manual (2)
Updated: 2005-09-15 Return to Main Contents

NAME

sigaction - examine and change a signal action

SYNOPSIS

#include <signal.h>

int sigaction(int signum, const struct sigaction *act,
              struct sigaction *oldact);

DESCRIPTION

The sigaction() system call is used to change the action taken by a process on receipt of a specific signal.

signum specifies the signal and can be any valid signal except SIGKILL and SIGSTOP.

If act is non-null, the new action for signal signum is installed from act. If oldact is non-null, the previous action is saved in oldact.

The sigaction structure is defined as something like

struct sigaction {
    void     (*sa_handler)(int);
    void     (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t   sa_mask;
    int        sa_flags;
    void     (*sa_restorer)(void);
}

On some architectures a union is involved: do not assign to both sa_handler and sa_sigaction.

The sa_restorer element is obsolete and should not be used. POSIX does not specify a sa_restorer element.

sa_handler specifies the action to be associated with signum and may be SIG_DFL for the default action, SIG_IGN to ignore this signal, or a pointer to a signal handling function. This function receives the signal number as its only argument.

If SA_SIGINFO is specified in sa_flags, then sa_sigaction (instead of sa_handler) specifies the signal-handling function for signum. This function receives the signal number as its first argument, a pointer to a siginfo_t as its second argument and a pointer to a ucontext_t (cast to void *) as its third argument.

sa_mask gives a mask of signals which should be blocked during execution of the signal handler. In addition, the signal which triggered the handler will be blocked, unless the SA_NODEFER flag is used.

sa_flags specifies a set of flags which modify the behavior of the signal handling process. It is formed by the bitwise OR of zero or more of the following:

SA_NOCLDSTOP
If signum is SIGCHLD, do not receive notification when child processes stop (i.e., when they receive one of SIGSTOP, SIGTSTP, SIGTTIN or SIGTTOU) or resume (i.e., they receive SIGCONT) (see wait(2)).
SA_NOCLDWAIT
(Linux 2.6 and later) If signum is SIGCHLD, do not transform children into zombies when they terminate. See also waitpid(2).
SA_RESETHAND
Restore the signal action to the default state once the signal handler has been called. SA_ONESHOT is an obsolete, non-standard synonym for this flag.
SA_ONSTACK
Call the signal handler on an alternate signal stack provided by sigaltstack(2). If an alternate stack is not available, the default stack will be used.
SA_RESTART
Provide behavior compatible with BSD signal semantics by making certain system calls restartable across signals.
SA_NODEFER
Do not prevent the signal from being received from within its own signal handler. SA_NOMASK is an obsolete, non-standard synonym for this flag.
SA_SIGINFO
The signal handler takes 3 arguments, not one. In this case, sa_sigaction should be set instead of sa_handler. (The sa_sigaction field was added in Linux 2.1.86.)

The siginfo_t parameter to sa_sigaction is a struct with the following elements

siginfo_t {
    int      si_signo;    /* Signal number */
    int      si_errno;    /* An errno value */
    int      si_code;     /* Signal code */
    pid_t    si_pid;      /* Sending process ID */
    uid_t    si_uid;      /* Real user ID of sending process */
    int      si_status;   /* Exit value or signal */
    clock_t  si_utime;    /* User time consumed */
    clock_t  si_stime;    /* System time consumed */
    sigval_t si_value;    /* Signal value */
    int      si_int;      /* POSIX.1b signal */
    void    *si_ptr;      /* POSIX.1b signal */
    void    *si_addr;     /* Memory location which caused fault */
    int      si_band;     /* Band event */
    int      si_fd;       /* File descriptor */
}

si_signo, si_errno and si_code are defined for all signals. (si_signo is unused on Linux.) The rest of the struct may be a union, so that one should only read the fields that are meaningful for the given signal:

*
POSIX.1b signals and SIGCHLD fill in si_pid and si_uid. .IP* SIGCHLD also fills in si_status, si_utime and si_stime.
*
si_int and si_ptr are specified by the sender of the POSIX.1b signal. See sigqueue(2) for more details.
*
SIGILL, SIGFPE, SIGSEGV, and SIGBUS fill in si_addr with the address of the fault. SIGPOLL fills in si_band and si_fd.

si_code indicates why this signal was sent. It is a value, not a bitmask. The values which are possible for any signal are listed in this table:
si_code
Value | Signal origin
SI_USER | kill(2) or raise(3)
SI_KERNEL | The kernel
SI_QUEUE | sigqueue(2)
SI_TIMER | POSIX timer expired
SI_MESGQ | POSIX message queue state changed (since Linux 2.6.6)
SI_ASYNCIO | AIO completed
SI_SIGIO | queued SIGIO
SI_TKILL | tkill(2) or tgkill(2) (since Linux 2.4.19)

SIGILL
ILL_ILLOPC | illegal opcode
ILL_ILLOPN | illegal operand
ILL_ILLADR | illegal addressing mode
ILL_ILLTRP | illegal trap
ILL_PRVOPC | privileged opcode
ILL_PRVREG | privileged register
ILL_COPROC | coprocessor error
ILL_BADSTK | internal stack error

SIGFPE
FPE_INTDIV | integer divide by zero
FPE_INTOVF | integer overflow
FPE_FLTDIV | floating point divide by zero
FPE_FLTOVF | floating point overflow
FPE_FLTUND | floating point underflow
FPE_FLTRES | floating point inexact result
FPE_FLTINV | floating point invalid operation
FPE_FLTSUB | subscript out of range

SIGSEGV
SEGV_MAPERR | address not mapped to object
SEGV_ACCERR | invalid permissions for mapped object

SIGBUS
BUS_ADRALN | invalid address alignment
BUS_ADRERR | non-existent physical address
BUS_OBJERR | object specific hardware error

SIGTRAP
TRAP_BRKPT | process breakpoint
TRAP_TRACE | process trace trap

SIGCHLD
CLD_EXITED | child has exited
CLD_KILLED | child was killed
CLD_DUMPED | child terminated abnormally
CLD_TRAPPED | traced child has trapped
CLD_STOPPED | child has stopped
CLD_CONTINUED | stopped child has continued (since Linux 2.6.9)

SIGPOLL
POLL_IN | data input available
POLL_OUT | output buffers available
POLL_MSG | input message available
POLL_ERR | i/o error
POLL_PRI | high priority input available
POLL_HUP | device disconnected

RETURN VALUE

sigaction() returns 0 on success and -1 on error.

ERRORS

EFAULT
act or oldact points to memory which is not a valid part of the process address space.
EINVAL
An invalid signal was specified. This will also be generated if an attempt is made to change the action for SIGKILL or SIGSTOP, which cannot be caught or ignored.

CONFORMING TO

POSIX.1-2001, SVr4.

NOTES

According to POSIX, the behavior of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(2) or raise(3). Integer division by zero has undefined result. On some architectures it will generate a SIGFPE signal. (Also dividing the most negative integer by -1 may generate SIGFPE.) Ignoring this signal might lead to an endless loop.

POSIX.1-1990 disallowed setting the action for SIGCHLD to SIG_IGN. POSIX.1-2001 allows this possibility, so that ignoring SIGCHLD can be used to prevent the creation of zombies (see wait(2)). Nevertheless, the historical BSD and System V behaviors for ignoring SIGCHLD differ, so that the only completely portable method of ensuring that terminated children do not become zombies is to catch the SIGCHLD signal and perform a wait(2) or similar.

POSIX.1-1990 only specified SA_NOCLDSTOP. POSIX.1-2001 added SA_NOCLDWAIT, SA_RESETHAND, SA_NODEFER, and SA_SIGINFO. Use of these latter values in sa_flags may be less portable in applications intended for older Unix implementations.

Support for SA_SIGINFO was added in Linux 2.2.

The SA_RESETHAND flag is compatible with the SVr4 flag of the same name.

The SA_NODEFER flag is compatible with the SVr4 flag of the same name under kernels 1.3.9 and newer. On older kernels the Linux implementation allowed the receipt of any signal, not just the one we are installing (effectively overriding any sa_mask settings).

sigaction() can be called with a null second argument to query the current signal handler. It can also be used to check whether a given signal is valid for the current machine by calling it with null second and third arguments.

It is not possible to block SIGKILL or SIGSTOP (by specifying them in sa_mask). Attempts to do so are silently ignored.

See sigsetops(3) for details on manipulating signal sets.

See signal(7) for a list of the async-signal-safe functions that can be safely called inside from inside a signal handler.

Undocumented

Before the introduction of SA_SIGINFO it was also possible to get some additional information, namely by using a sa_handler with second argument of type struct sigcontext. See the relevant kernel sources for details. This use is obsolete now.

BUGS

In kernels up to and including 2.6.13, specifying SA_NODEFER in sa_flags preventing not only the delivered signal from being masked during execution of the handler, but also the signals specified in sa_mask. This bug is was fixed in kernel 2.6.14.

EXAMPLE

See mprotect(2).

SEE ALSO

kill(1), kill(2), pause(2), sigaltstack(2), signal(2), sigpending(2), sigprocmask(2), sigqueue(2), sigsuspend(2), wait(2), killpg(3), raise(3), siginterrupt(3), sigsetops(3), sigvec(3), core(5), signal(7)


acct(2)

ACCT

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

acct - switch process accounting on or off

SYNOPSIS

#include <unistd.h>

int acct(const char *filename);

DESCRIPTION

When called with the name of an existing file as argument, accounting is turned on, records for each terminating process are appended to filename as it terminates. An argument of NULL causes accounting to be turned off.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Write permission is denied for the specified file, or search permission is denied for one of the directories in the path prefix of filename (see also path_resolution(7)), or filename is not a regular file.
EFAULT
filename points outside your accessible address space.
EIO
Error writing to the file filename.
EISDIR
filename is a directory.
ELOOP
Too many symbolic links were encountered in resolving filename.
ENAMETOOLONG
filename was too long.
ENFILE
The system limit on the total number of open files has been reached.
ENOENT
The specified filename does not exist.
ENOMEM
Out of memory.
ENOSYS
BSD process accounting has not been enabled when the operating system kernel was compiled. The kernel configuration parameter controlling this feature is CONFIG_BSD_PROCESS_ACCT.
ENOTDIR
A component used as a directory in filename is not in fact a directory.
EPERM
The calling process has insufficient privilege to enable process accounting. On Linux the CAP_SYS_PACCT capability is required.
EROFS
filename refers to a file on a read-only file system.
EUSERS
There are no more free file structures or we ran out of memory.

CONFORMING TO

SVr4, 4.3BSD (but not POSIX).

NOTES

No accounting is produced for programs running when a crash occurs. In particular, nonterminating processes are never accounted for.

SEE ALSO

acct(5)


sigblock(2)

SIGBLOCK

Section: Linux Programmer's Manual (2)
Updated: 1995-08-31 Return to Main Contents

NAME

sigblock, siggetmask, sigsetmask, sigmask - manipulate the signal mask

SYNOPSIS

#include <signal.h>

int sigblock(int mask);

int siggetmask(void);

int sigsetmask(int mask);

int sigmask(int signum);

DESCRIPTION

This interface is made obsolete by sigprocmask(2).

The sigblock system call adds the signals specified in mask to the set of signals currently being blocked from delivery.

The sigsetmask system call replaces the set of blocked signals totally with a new set specified in mask. Signals are blocked if the corresponding bit in mask is a 1.

The current set of blocked signals can be obtained using siggetmask.

The sigmask macro is provided to construct the mask for a given signum.

RETURN VALUE

siggetmask returns the current set of masked signals.

sigsetmask and sigblock return the previous set of masked signals.

NOTES

Prototypes for these functions are only available if _BSD_SOURCE is defined before the inclusion of any system header file.

It is not possible to block SIGKILL or SIGSTOP - this restriction is silently imposed by the system.

CONFORMING TO

4.4BSD. These function calls appeared in BSD 4.3 and are deprecated. Use the POSIX signal facilities for new programs.

SEE ALSO

kill(2), sigprocmask(2), signal(7)


chmod(2)

CHMOD

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

chmod, fchmod - change permissions of a file

SYNOPSIS

#include <sys/types.h>
#include <sys/stat.h>

int chmod(const char *path, mode_t mode);
int fchmod(int fildes, mode_t mode);

DESCRIPTION

The mode of the file given by path or referenced by fildes is changed.

Modes are specified by or'ing the following:

S_ISUID
04000 set user ID on execution
S_ISGID
02000 set group ID on execution
S_ISVTX
01000 sticky bit
S_IRUSR
00400 read by owner
S_IWUSR
00200 write by owner
S_IXUSR
00100 execute/search by owner
S_IRGRP
00040 read by group
S_IWGRP
00020 write by group
S_IXGRP
00010 execute/search by group
S_IROTH
00004 read by others
S_IWOTH
00002 write by others
S_IXOTH
00001 execute/search by others

The effective UID of the calling process must match the owner of the file, or the process must be privileged (Linux: it must have the CAP_FOWNER capability).

If the calling process is not privileged (Linux: does not have the CAP_FSETID capability), and the group of the file does not match the effective group ID of the process or one of its supplementary group IDs, the S_ISGID bit will be turned off, but this will not cause an error to be returned.

As a security measure, depending on the file system, the set-user-ID and set-group-ID execution bits may be turned off if a file is written. (On Linux this occurs if the writing process does not have the CAP_FSETID capability.) On some file systems, only the superuser can set the sticky bit, which may have a special meaning. For the sticky bit, and for set-user-ID and set-group-ID bits on directories, see stat(2).

On NFS file systems, restricting the permissions will immediately influence already open files, because the access control is done on the server, but open files are maintained by the client. Widening the permissions may be delayed for other clients if attribute caching is enabled on them.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

Depending on the file system, other errors can be returned. The more general errors for chmod() are listed below:
EACCES
Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
EFAULT
path points outside your accessible address space.
EIO
An I/O error occurred.
ELOOP
Too many symbolic links were encountered in resolving path.
ENAMETOOLONG
path is too long.
ENOENT
The file does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The effective UID does not match the owner of the file, and the process is not privileged (Linux: it does not have the CAP_FOWNER capability).
EROFS
The named file resides on a read-only file system.

The general errors for fchmod() are listed below:

EBADF
The file descriptor fildes is not valid.
EIO
See above.
EPERM
See above.
EROFS
See above.

CONFORMING TO

4.4BSD, SVr4, POSIX.1-2001.

SEE ALSO

chown(2), execve(2), fchmodat(2), open(2), stat(2), path_resolution(7)


syscalls(2)

SYSCALLS

Section: Linux Programmer's Manual (2)
Updated: 2002-01-07 Return to Main Contents

NAME

none - list of all system calls

SYNOPSIS

Linux 2.4 system calls.

DESCRIPTION

The system call is the fundamental interface between an application and the Linux kernel. As of Linux 2.4.17, there are 1100 system calls listed in /usr/src/linux/include/asm-*/unistd.h. This man page lists those that are common to most platforms.

_llseek(2),
_newselect(2),
_sysctl(2),
accept(2),
access(2),
acct(2),
adjtimex(2),
afs_syscall,
alarm(2),
bdflush(2),
bind(2),
break,
brk(2),
cacheflush(2),
capget(2),
capset(2),
chdir(2),
chmod(2),
chown(2), chown32,
chroot(2),
clone(2),
close(2),
connect(2),
creat(2),
create_module(2),
delete_module(2),
dup(2),
dup2(2),
execve(2),
exit(2),
fchdir(2),
fchmod(2),
fchown(2), fchown32,
fcntl(2), fcntl64,
fdatasync(2),
flock(2),
fork(2),
fstat(2), fstat64,
fstatfs(2),
fsync(2),
ftime,
ftruncate(2), ftruncate64,
get_kernel_syms(2),
getcwd(2),
getdents(2), getdents64,
getegid(2), getegid32,
geteuid(2), geteuid32,
getgid(2), getgid32,
getgroups(2), getgroups32,
getitimer(2),
getpagesize(2),
getpeername(2),
getpmsg,
getpgid(2),
getpgrp(2),
getpid(2),
getppid(2),
getpriority(2),
getresgid(2), getresgid32,
getresuid(2), getresuid32,
getrlimit(2),
getrusage(2),
getsid(2),
getsockname(2),
getsockopt(2),
gettid,
gettimeofday(2),
getuid(2), getuid32,
gtty,
idle,
init_module(2),
ioctl(2),
ioperm(2),
iopl(2),
ipc(2),
kill(2),
lchown(2), lchown32,
link(2),
listen(2),
lock,
lseek(2),
lstat(2), lstat64,
madvise(2),
mincore(2),
mkdir(2),
mknod(2),
mlock(2),
mlockall(2),
mmap(2),
modify_ldt(2),
mount(2),
mprotect(2),
mpx,
mremap(2),
msync(2),
munlock(2),
munlockall(2),
munmap(2),
nanosleep(2),
nfsservctl(2),
nice(2),
oldfstat, oldlstat, oldolduname, oldstat, oldumount, olduname,
open(2),
pause(2),
personality(2),
phys,
pipe(2),
pivot_root(2),
poll(2),
prctl(2),
pread(2),
prof, profil,
ptrace(2),
putpmsg,
pwrite(2),
query_module(2),
quotactl(2),
read(2),
readahead,
readdir(2),
readlink(2),
readv(2),
reboot(2),
recv(2), recvfrom(2), recvmsg(2),
rename(2),
rmdir(2),
rt_sigaction,
rt_sigpending,
rt_sigprocmask,
rt_sigqueueinfo,
rt_sigreturn,
rt_sigsuspend,
rt_sigtimedwait,
sched_get_priority_max(2),
sched_get_priority_min(2),
sched_getparam(2),
sched_getscheduler(2),
sched_rr_get_interval(2),
sched_setparam(2),
sched_setscheduler(2),
sched_yield(2),
security,
select(2),
sendfile(2),
send(2), sendmsg(2), sendto(2),
setdomainname(2),
setfsgid(2), setfsgid32,
setfsuid(2), setfsuid32,
setgid(2), setgid32,
setgroups(2), setgroups32,
sethostname(2),
setitimer(2),
setpgid(2),
setpriority(2),
setregid(2), setregid32,
setresgid(2), setresgid32,
setresuid(2), setresuid32,
setreuid(2), setreuid32,
setrlimit(2),
setsid(2),
setsockopt(2),
settimeofday(2),
setuid(2), setuid32,
setup(2),
sgetmask(2),
shutdown(2),
sigaction(2),
sigaltstack(2),
signal(2),
sigpending(2),
sigprocmask(2),
sigreturn(2),
sigsuspend(2),
socket(2),
socketcall(2),
socketpair(2),
ssetmask(2),
stat(2), stat64,
statfs(2),
stime(2),
stty,
swapoff(2),
swapon(2),
symlink(2),
sync(2),
sysfs(2),
sysinfo(2),
syslog(2),
time(2),
times(2),
truncate(2), truncate64,
ulimit,
umask(2),
umount(2),
uname(2),
unlink(2),
uselib(2),
ustat(2),
utime(2),
vfork(2),
vhangup(2),
vm86(2),
vm86old,
wait4(2),
waitpid(2),
write(2),
writev(2).

Of the above, 9 are obsolete, namely getrlimit, oldfstat, oldlstat, oldolduname, oldstat, olduname, readdir, select and vm86old (see also obsolete(2)), and 15 are unimplemented in the standard kernel, namely afs_syscall, break, ftime, getpmsg, gtty, idle, lock, mpx, phys, prof, profil, putpmsg, security, stty and ulimit (see also unimplemented(2)). However, ftime(3), profil(3) and ulimit(3) exist as library routines. The slot for phys is in use since 2.1.116 for umount; phys will never be implemented. The getpmsg and putpmsg calls are for kernels patched to support streams, and may never be in the standard kernel. The security call is for future use.

Roughly speaking, the code belonging to the system call with number __NR_xxx defined in /usr/include/asm/unistd.h can be found in the kernel source in the routine sys_xxx(). (The dispatch table for i386 can be found in /usr/src/linux/arch/i386/kernel/entry.S.) There are many exceptions, however, mostly because older system calls were superseded by newer ones, and this has been treated somewhat unsystematically. On platforms with proprietary OS emulation, such as parisc, sparc, sparc64 and alpha, there are many additional system calls; mips64 also contains a full set of 32-bit system calls. Below the details for Linux 2.4.17.

The defines __NR_oldstat and __NR_stat refer to the routines sys_stat() and sys_newstat(), and similarly for fstat and lstat. Similarly, the defines __NR_oldolduname, __NR_olduname and __NR_uname refer to the routines sys_olduname(), sys_uname() and sys_newuname(). Thus, __NR_stat and __NR_uname have always referred to the latest version of the system call, and the older ones are for backward compatibility.

It is different with select and mmap. These use five or more parameters, and caused problems the way parameter passing on the i386 used to be set up. Thus, while other architectures have sys_select() and sys_mmap() corresponding to __NR_select and __NR_mmap, on i386 one finds old_select() and old_mmap() (routines that use a pointer to a parameter block) instead. These days passing five parameters is not a problem any more, and there is a __NR__newselect (used by libc 6) that corresponds directly to sys_select() and similarly __NR_mmap2.

Two other system call numbers, __NR__llseek and __NR__sysctl have an additional underscore absent in sys_llseek() and sys_sysctl().

Then there is __NR_readdir corresponding to old_readdir(), which will read at most one directory entry at a time, and is superseded by sys_getdents().

On many platforms, including i386, socket calls are all multiplexed through socketcall() and System V IPC calls through ipc().

On newer platforms that only have 64-bit file access and 32-bit uids (e.g., alpha, ia64, s390x) there are no *64 or *32 calls. Where the *64 and *32 calls exist, the other versions are obsolete.

The chown and lchown system calls were swapped in 2.1.81. The *64 and *32 calls were added for kernel 2.4, as were the new versions of getrlimit and mmap, and the new calls pivot_root, mincore, madvise, security, gettid and readahead.


syslog(2)

SYSLOG

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

syslog, klogctl - read and/or clear kernel message ring buffer; set console_loglevel

SYNOPSIS

int syslog(int type, char *bufp, int len);
                /* No wrapper provided in glibc */

/* The glibc interface */

#include <sys/klog.h>

int klogctl(int type, char *bufp, int len);

DESCRIPTION

If you need the libc function syslog() (which talks to syslogd(8)), then look at syslog(3). The system call of this name is about controlling the kernel printk() buffer, and the glibc version is called klogctl().

The type argument determines the action taken by this function.

Quoting from kernel/printk.c:

/*
 * Commands to sys_syslog:
 *
 *      0 -- Close the log.  Currently a NOP.
 *      1 -- Open the log. Currently a NOP.
 *      2 -- Read from the log.
 *      3 -- Read up to the last 4k of messages in the ring buffer.
 *      4 -- Read and clear last 4k of messages in the ring buffer
 *      5 -- Clear ring buffer.
 *      6 -- Disable printk's to console
 *      7 -- Enable printk's to console
 *      8 -- Set level of messages printed to console
 *      9 -- Return number of unread characters in the log buffer
 */

Only function 3 is allowed to non-root processes. (Function 9 was added in 2.4.10.)

The kernel log buffer
The kernel has a cyclic buffer of length LOG_BUF_LEN (4096, since 1.3.54: 8192, since 2.1.113: 16384; in recent kernels the size can be set at compile time) in which messages given as argument to the kernel function printk() are stored (regardless of their loglevel).

The call syslog() (2,buf,len) waits until this kernel log buffer is nonempty, and then reads at most len bytes into the buffer buf. It returns the number of bytes read. Bytes read from the log disappear from the log buffer: the information can only be read once. This is the function executed by the kernel when a user program reads /proc/kmsg.

The call syslog() (3,buf,len) will read the last len bytes from the log buffer (nondestructively), but will not read more than was written into the buffer since the last `clear ring buffer' command (which does not clear the buffer at all). It returns the number of bytes read.

The call syslog() (4,buf,len) does precisely the same, but also executes the `clear ring buffer' command.

The call syslog() (5,dummy,idummy) only executes the `clear ring buffer' command.

The loglevel
The kernel routine printk() will only print a message on the console, if it has a loglevel less than the value of the variable console_loglevel. This variable initially has the value DEFAULT_CONSOLE_LOGLEVEL (7), but is set to 10 if the kernel command line contains the word `debug', and to 15 in case of a kernel fault (the 10 and 15 are just silly, and equivalent to 8). This variable is set (to a value in the range 1-8) by the call syslog() (8,dummy,value). The calls syslog() (type,dummy,idummy) with type equal to 6 or 7, set it to 1 (kernel panics only) or 7 (all except debugging messages), respectively.

Every text line in a message has its own loglevel. This level is DEFAULT_MESSAGE_LOGLEVEL - 1 (6) unless the line starts with <d> where d is a digit in the range 1-7, in which case the level is d. The conventional meaning of the loglevel is defined in <linux/kernel.h> as follows:

#define KERN_EMERG    "<0>"  /* system is unusable               */
#define KERN_ALERT    "<1>"  /* action must be taken immediately */
#define KERN_CRIT     "<2>"  /* critical conditions              */
#define KERN_ERR      "<3>"  /* error conditions                 */
#define KERN_WARNING  "<4>"  /* warning conditions               */
#define KERN_NOTICE   "<5>"  /* normal but significant condition */
#define KERN_INFO     "<6>"  /* informational                    */
#define KERN_DEBUG    "<7>"  /* debug-level messages             */

RETURN VALUE

In case of error, -1 is returned, and errno is set. Otherwise, for type equal to 2, 3 or 4, syslog() returns the number of bytes read, and otherwise 0.

ERRORS

EINVAL
Bad parameters.
EPERM
An attempt was made to change console_loglevel or clear the kernel message ring buffer by a process without root permissions.
ERESTARTSYS
System call was interrupted by a signal; nothing was read. (This can be seen only during a trace.)

CONFORMING TO

This system call is Linux specific and should not be used in programs intended to be portable.

NOTES

From the very start people noted that it is unfortunate that kernel call and library routine of the same name are entirely different animals. In libc4 and libc5 the number of this call was defined by SYS_klog. In glibc 2.0 the syscall is baptized klogctl().

SEE ALSO

syslog(3)


times(2)

TIMES

Section: Linux Programmer's Manual (2)
Updated: 2002-06-14 Return to Main Contents

NAME

times - get process times

SYNOPSIS

#include <sys/times.h>

clock_t times(struct tms *buf);

DESCRIPTION

times() stores the current process times in the struct tms that buf points to. The struct tms is as defined in <sys/times.h>:

struct tms {
    clock_t tms_utime;  /* user time */
    clock_t tms_stime;  /* system time */
    clock_t tms_cutime; /* user time of children */
    clock_t tms_cstime; /* system time of children */
};

The tms_utime field contains the CPU time spent executing instructions of the calling process. The tms_stime field contains the CPU time spent in the system while executing tasks on behalf of the calling process. The tms_cutime field contains the sum of the tms_utime and tms_cutime values for all waited-for terminated children. The tms_cstime field contains the sum of the tms_stime and tms_cstime values for all waited-for terminated children.

Times for terminated children (and their descendants) is added in at the moment wait(2) or waitpid(2) returns their process ID. In particular, times of grandchildren that the children did not wait for are never seen.

All times reported are in clock ticks.

RETURN VALUE

times() returns the number of clock ticks that have elapsed since an arbitrary point in the past. For Linux 2.4 and earlier this point is the moment the system was booted. Since Linux 2.6, this point is (2^32/HZ) - 300 (i.e., about 429 million) seconds before system boot time. The return value may overflow the possible range of type clock_t. On error, (clock_t) -1 is returned, and errno is set appropriately.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

The number of clock ticks per second can be obtained using
sysconf(_SC_CLK_TCK);
In POSIX-1996 the symbol CLK_TCK (defined in <time.h>) is mentioned as obsolescent. It is obsolete now.

In Linux kernel versions before 2.6.9, if the disposition of SIGCHLD is set to SIG_IGN then the times of terminated children are automatically included in the tms_cstime and tms_cutime fields, although POSIX.1-2001 says that this should only happen if the calling process wait(2)s on its children. This non-conformance is rectified in Linux 2.6.9 and later.

On Linux, the buf argument can be specified as NULL, with the result that times() just returns a function result. However, POSIX does not specify this behavior, and most other Unix implementations require a non-NULL value for buf.

Note that clock(3) returns values of type clock_t that are not measured in clock ticks but in CLOCKS_PER_SEC.

On older systems the number of clock ticks per second is given by the variable HZ.

Historical

SVr1-3 returns long and the struct members are of type time_t although they store clock ticks, not seconds since the epoch. V7 used long for the struct members, because it had no type time_t yet.

SEE ALSO

time(1), getrusage(2), wait(2), clock(3), sysconf(3), time(7)


unlink(2)

UNLINK

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

unlink - delete a name and possibly the file it refers to

SYNOPSIS

#include <unistd.h>

int unlink(const char *pathname);

DESCRIPTION

unlink() deletes a name from the filesystem. If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.

If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.

If the name referred to a symbolic link the link is removed.

If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Write access to the directory containing pathname is not allowed for the process's effective UID, or one of the directories in pathname did not allow search permission. (See also path_resolution(7).)
EBUSY (not on Linux)
The file pathname cannot be unlinked because it is being used by the system or another process and the implementation considers this an error.
EFAULT
pathname points outside your accessible address space.
EIO
An I/O error occurred.
EISDIR
pathname refers to a directory. (This is the non-POSIX value returned by Linux since 2.1.132.)
ELOOP
Too many symbolic links were encountered in translating pathname.
ENAMETOOLONG
pathname was too long.
ENOENT
A component in pathname does not exist or is a dangling symbolic link, or pathname is empty.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component used as a directory in pathname is not, in fact, a directory.
EPERM
The system does not allow unlinking of directories, or unlinking of directories requires privileges that the current process doesn't have. (This is the POSIX prescribed error return; as noted above, Linux returns EISDIR for this case.)
EPERM (Linux only)
The filesystem does not allow unlinking of files.
EPERM or EACCES
The directory containing pathname has the sticky bit (S_ISVTX) set and the process's effective UID is neither the UID of the file to be deleted nor that of the directory containing it, and the process is not privileged (Linux: does not have the CAP_FOWNER capability).
EROFS
pathname refers to a file on a read-only filesystem.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

BUGS

Infelicities in the protocol underlying NFS can cause the unexpected disappearance of files which are still being used.

SEE ALSO

rm(1), chmod(2), link(2), mknod(2), open(2), rename(2), rmdir(2), unlinkat(2), mkfifo(3), remove(3), path_resolution(7)


uselib(2)

USELIB

Section: Linux Programmer's Manual (2)
Updated: 2005-01-09 Return to Main Contents

NAME

uselib - load shared library

SYNOPSIS

#include <unistd.h>

int uselib(const char *library);

DESCRIPTION

The system call uselib() serves to load a shared library to be used by the calling process. It is given a pathname. The address where to load is found in the library itself. The library can have any recognized binary format.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

In addition to all of the error codes returned by open(2) and mmap(2), the following may also be returned:
EACCES
The library specified by library does not have read or execute permission, or the caller does not have search permission for one of the directories in the path prefix. (See also path_resolution(7).)
ENFILE
The system limit on the total number of open files has been reached.
ENOEXEC
The file specified by library is not an executable of known type, e.g., does not have the correct magic numbers.

CONFORMING TO

uselib() is Linux specific, and should not be used in programs intended to be portable.

NOTES

uselib() was used by early libc startup code to load the shared libraries with names found in an array of names in the binary.

Since libc 4.3.2, startup code tries to prefix these names with "/usr/lib", "/lib" and "" before giving up. In libc 4.3.4 and later these names are looked for in the directories found in LD_LIBRARY_PATH, and if not found there, prefixes "/usr/lib", "/lib" and "/" are tried.

From libc 4.4.4 on only the library "/lib/ld.so" is loaded, so that this dynamic library can load the remaining libraries needed (again using this call). This is also the state of affairs in libc5.

glibc2 does not use this call.

SEE ALSO

ar(1), gcc(1), ld(1), ldd(1), mmap(2), open(2), dlopen(3), capability(7), ld.so(8)


utime(2)

UTIME

Section: Linux Programmer's Manual (2)
Updated: 2004-10-10 Return to Main Contents

NAME

utime, utimes - change access and/or modification times of an inode

SYNOPSIS

#include <sys/types.h>

#include <utime.h>

int utime(const char *filename, const struct utimbuf *buf);

#include <sys/time.h>

int utimes(const char *filename, const struct timeval times[2]);

DESCRIPTION

utime() changes the access and modification times of the inode specified by filename to the actime and modtime fields of buf respectively.

If buf is NULL, then the access and modification times of the file are set to the current time.

Changing time stamps is permitted when: either the process has appropriate privileges (Linux: has the CAP_FOWNER capability), or the effective user ID equals the user ID of the file, or buf must is NULL and the process has write permission to the file.

The utimbuf structure is:

struct utimbuf {
    time_t actime;       /* access time */
    time_t modtime;      /* modification time */
};

The function utime() allows specification of time stamps with a resolution of 1 second. The function utimes() is similar, but allows a resolution of 1 microsecond. Here times[0] refers to access time, and times[1] to modification time.

The timeval structure is:

struct timeval {
    long tv_sec;        /* seconds */
    long tv_usec;       /* microseconds */
};

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Search permission is denied for one of the directories in the path prefix of path (see also path_resolution(7)), or buf is NULL and the process does not have permission to change the time stamps (see above).
ENOENT
filename does not exist.
EPERM
buf is not NULL and the process does not have permission to change the time stamps.
EROFS
path resides on a read-only file system.

CONFORMING TO

utime(): SVr4, POSIX.1-2001.
utimes(): 4.3BSD

NOTES

Linux does not allow changing the time stamps on an immutable file, or setting the time stamps to something other than the current time on an append-only file.

In libc4 and libc5, utimes() is just a wrapper for utime() and hence does not allow a subsecond resolution.

POSIX.1-2001 marks utimes() legacy, which is strange since it provides more functionality than utime().

BUGS

Linux is not careful to distinguish between the EACCES and EPERM error returns. On the other hand, POSIX.1-2001 is buggy in its error description for utimes().

SEE ALSO

chattr(1), futimesat(2), stat(2), futimes(3)


wait3 (2)

 Continue to this page.


bind(2)

BIND

Section: Linux Programmer's Manual (2)
Updated: 2007-06-08 Return to Main Contents

NAME

bind - bind a name to a socket

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>

int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen);

DESCRIPTION

bind() gives the socket sockfd the local address my_addr. my_addr is addrlen bytes long. Traditionally, this is called "assigning a name to a socket." When a socket is created with socket(2), it exists in a name space (address family) but has no name assigned.

It is normally necessary to assign a local address using bind() before a SOCK_STREAM socket may receive connections (see accept(2)).

The rules used in name binding vary between address families. Consult the manual entries in Section 7 for detailed information. For AF_INET see ip(7), for AF_INET6 see ipv6(7), for AF_UNIX see unix(7), for AF_APPLETALK see ddp(7), for AF_PACKET see packet(7), for AF_X25 see x25(7) and for AF_NETLINK see netlink(7).

The actual structure passed for the my_addr argument will depend on the address family. The sockaddr structure is defined as something like:

struct sockaddr {
    sa_family_t sa_family;
    char        sa_data[14];
}
The only purpose of this structure is to cast the structure pointer passed in my_addr in order to avoid compiler warnings. See EXAMPLE below.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
The address is protected, and the user is not the superuser.
EADDRINUSE
The given address is already in use.
EBADF
sockfd is not a valid descriptor.
EINVAL
The socket is already bound to an address.
ENOTSOCK
sockfd is a descriptor for a file, not a socket.

The following errors are specific to UNIX domain (AF_UNIX) sockets:

EACCES
Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
EADDRNOTAVAIL
A non-existent interface was requested or the requested address was not local.
EFAULT
my_addr points outside the user's accessible address space.
EINVAL
The addrlen is wrong, or the socket was not in the AF_UNIX family.
ELOOP
Too many symbolic links were encountered in resolving my_addr.
ENAMETOOLONG
my_addr is too long.
ENOENT
The file does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix is not a directory.
EROFS
The socket inode would reside on a read-only file system.

CONFORMING TO

SVr4, 4.4BSD, POSIX.1-2001 (the bind() function first appeared in 4.2BSD).

NOTES

The third argument of bind() is in reality an int (and this is what 4.x BSD and libc4 and libc5 have). Some POSIX confusion resulted in the present socklen_t, also used by glibc. See also accept(2).

EXAMPLE

An example of the use of bind() with Internet domain sockets can be found in getaddrinfo(3).

The following example shows how to bind a stream socket in the Unix (AF_UNIX) domain, and accept connections:

#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MY_SOCK_PATH "/somepath"
#define LISTEN_BACKLOG 50

#define die(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)

int
main(int argc, char *argv[])
{
    int sfd, cfd;
    struct sockaddr_un my_addr, peer_addr;
    socklen_t peer_addr_size;

    sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sfd == -1)
        die("socket");

    memset(&my_addr, 0, sizeof(struct sockaddr_un));
                        /* Clear structure */
    my_addr.sun_family = AF_UNIX;
    strncpy(my_addr.sun_path, MY_SOCK_PATH,
            sizeof(my_addr.sun_path) - 1);

    if (bind(sfd, (struct sockaddr *) &my_addr,
            sizeof(struct sockaddr_un)) == -1)
        die("bind");

    if (listen(sfd, LISTEN_BACKLOG) == -1)
        die("listen");

    /* Now we can accept incoming connections one
       at a time using accept(2) */

    peer_addr_size = sizeof(struct sockaddr_un);
    cfd = accept(sfd, (struct sockaddr *) &peer_addr,
                 &peer_addr_size)
    if (cfd == -1)
        die("accept");

    /* Code to deal with incoming connection(s)... */

    /* When no longer required, the socket pathname, MY_SOCK_PATH
       should be deleted using unlink(2) or remove(3) */
}

BUGS

The transparent proxy options are not described.

SEE ALSO

accept(2), connect(2), getsockname(2), listen(2), socket(2), getaddrinfo(3), ip(7), ipv6(7), path_resolution(7), socket(7), unix(7)


getpeername(2)

GETPEERNAME

Section: Linux Programmer's Manual (2)
Updated: 1993-07-30 Return to Main Contents

NAME

getpeername - get name of connected peer socket

SYNOPSIS

#include <sys/socket.h>

int getpeername(int s, struct sockaddr *name, socklen_t *namelen);

DESCRIPTION

getpeername() returns the name of the peer connected to socket s. The namelen parameter should be initialized to indicate the amount of space pointed to by name. On return it contains the actual size of the name returned (in bytes). The name is truncated if the buffer provided is too small.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
The argument s is not a valid descriptor.
EFAULT
The name parameter points to memory not in a valid part of the process address space.
EINVAL
namelen is invalid (e.g., is negative).
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOTCONN
The socket is not connected.
ENOTSOCK
The argument s is a file, not a socket.

CONFORMING TO

SVr4, 4.4BSD (the getpeername() function call first appeared in 4.2BSD), POSIX.1-2001.

NOTES

The third argument of getpeername() is in reality an int * (and this is what 4.x BSD and libc4 and libc5 have). Some POSIX confusion resulted in the present socklen_t, also used by glibc. See also accept(2).

SEE ALSO

accept(2), bind(2), getsockname(2)


waitpid (2)

 Continue to this page.


write(2)

WRITE

Section: Linux Programmer's Manual (2)
Updated: 2001-12-13 Return to Main Contents

NAME

write - write to a file descriptor

SYNOPSIS

#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t count);

DESCRIPTION

write() writes up to count bytes to the file referenced by the file descriptor fd from the buffer starting at buf. POSIX requires that a read(2) which can be proved to occur after a write() has returned returns the new data. Note that not all file systems are POSIX conforming.

RETURN VALUE

On success, the number of bytes written are returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.

If count is zero and fd refers to a regular file, then write () may return a failure status if one of the errors below is detected. If no errors are detected, 0 will be returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not specified.

ERRORS

EAGAIN
Non-blocking I/O has been selected using O_NONBLOCK and the write would block.
EBADF
fd is not a valid file descriptor or is not open for writing.
EFAULT
buf is outside your accessible address space.
EFBIG
An attempt was made to write a file that exceeds the implementation-defined maximum file size or the process' file size limit, or to write at a position past the maximum allowed offset.
EINTR
The call was interrupted by a signal before any data was written.
EINVAL
fd is attached to an object which is unsuitable for writing; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the current file offset is not suitably aligned.
EIO
A low-level I/O error occurred while modifying the inode.
ENOSPC
The device containing the file referred to by fd has no room for the data.
EPIPE
fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIGPIPE signal. (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.)

Other errors may occur, depending on the object connected to fd.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

Under SVr4 a write may be interrupted and return EINTR at any point, not just before any data is written.

NOTES

A successful return from write() does not make any guarantee that data has been committed to disk. In fact, on some buggy implementations, it does not even guarantee that space has successfully been reserved for the data. The only way to be sure is to call fsync(2) after you are done writing all your data.

SEE ALSO

close(2), fcntl(2), fsync(2), ioctl(2), lseek(2), open(2), pwrite(2), read(2), select(2), writev(2), fwrite(3)


writev (2)

 Continue to this page.


sched_get_priority_max(2)

SCHED_GET_PRIORITY_MAX

Section: Linux Programmer's Manual (2)
Updated: 2006-03-23 Return to Main Contents

NAME

sched_get_priority_max, sched_get_priority_min - get static priority range

SYNOPSIS

#include <sched.h>

int sched_get_priority_max(int policy);

int sched_get_priority_min(int policy);

DESCRIPTION

sched_get_priority_max() returns the maximum priority value that can be used with the scheduling algorithm identified by policy. sched_get_priority_min() returns the minimum priority value that can be used with the scheduling algorithm identified by policy. Supported policy values are SCHED_FIFO, SCHED_RR, SCHED_OTHER, and SCHED_BATCH. Further details about these policies can be found in sched_setscheduler(2).

Processes with numerically higher priority values are scheduled before processes with numerically lower priority values. Thus, the value returned by sched_get_priority_max() will be greater than the value returned by sched_get_priority_min().

Linux allows the static priority value range 1 to 99 for SCHED_FIFO and SCHED_RR and the priority 0 for SCHED_OTHER and SCHED_BATCH. Scheduling priority ranges for the various policies are not alterable.

The range of scheduling priorities may vary on other POSIX systems, thus it is a good idea for portable applications to use a virtual priority range and map it to the interval given by sched_get_priority_max() and sched_get_priority_min(). POSIX.1-2001 requires a spread of at least 32 between the maximum and the minimum values for SCHED_FIFO and SCHED_RR.

POSIX systems on which sched_get_priority_max() and sched_get_priority_min() are available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

RETURN VALUE

On success, sched_get_priority_max() and sched_get_priority_min() return the maximum/minimum priority value for the named scheduling policy. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
The parameter policy does not identify a defined scheduling policy.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

sched_getaffinity(2), sched_getparam(2), sched_getscheduler(2), sched_setaffinity(2), sched_setparam(2), sched_setscheduler(2)

Programming for the real world - POSIX.4 by Bill O. Gallmeister, O'Reilly & Associates, Inc., ISBN 1-56592-074-0


_llseek (2)

 Continue to this page.


sendfile(2)

SENDFILE

Section: Linux Programmer's Manual (2)
Updated: 2004-12-17 Return to Main Contents

NAME

sendfile - transfer data between file descriptors

SYNOPSIS

#include <sys/sendfile.h>

ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);

DESCRIPTION

sendfile() copies data between one file descriptor and another. Because this copying is done within the kernel, sendfile() is more efficient than the combination of read(2) and write(2), which would require transferring data to and from user space.

in_fd should be a file descriptor opened for reading and out_fd should be a descriptor opened for writing.

If offset is not NULL, then it points to a variable holding the file offset from which sendfile() will start reading data from in_fd. When sendfile() returns, this variable will be set to the offset of the byte following the last byte that was read. If offset is not NULL, then sendfile() does not modify the current file offset of in_fd; otherwise the current file offset is adjusted to reflect the number of bytes read from in_fd.

count is the number of bytes to copy between the file descriptors.

Presently (Linux 2.6.9): in_fd, must correspond to a file which supports mmap(2)-like operations (i.e., it cannot be a socket); and out_fd must refer to a socket.

Applications may wish to fall back to read(2)/write(2) in the case where sendfile() fails with EINVAL or ENOSYS.

RETURN VALUE

If the transfer was successful, the number of bytes written to out_fd is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EAGAIN
Non-blocking I/O has been selected using O_NONBLOCK and the write would block.
EBADF
The input file was not opened for reading or the output file was not opened for writing.
EFAULT
Bad address.
EINVAL
Descriptor is not valid or locked, or an mmap(2)-like operation is not available for in_fd.
EIO
Unspecified error while reading from in_fd.
ENOMEM
Insufficient memory to read from in_fd.

VERSIONS

sendfile() is a new feature in Linux 2.2. The include file <sys/sendfile.h> is present since glibc 2.1.

CONFORMING TO

Not specified in POSIX.1-2001, or other standards.

Other Unix systems implement sendfile() with different semantics and prototypes. It should not be used in portable programs.

NOTES

If you plan to use sendfile() for sending files to a TCP socket, but need to send some header data in front of the file contents, you will find it useful to employ the TCP_CORK option, described in tcp(7), to minimize the number of packets and to tune performance.

In Linux 2.4 and earlier, out_fd could refer to a regular file, and sendfile() changed the current offset of that file.

SEE ALSO

open(2), mmap(2), socket(2), splice(2)


stime(2)

STIME

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

stime - set time

SYNOPSIS

#define _SVID_SOURCE /* glibc2 needs this */
#include <time.h>

int stime(time_t *t);

DESCRIPTION

stime() sets the system's idea of the time and date. Time, pointed to by t, is measured in seconds from 00:00:00 GMT January 1, 1970. stime() may only be executed by the superuser.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
Error in getting information from user space.
EPERM
The calling process has insufficient privilege. Under Linux the CAP_SYS_TIME privilege is required.

CONFORMING TO

SVr4.

NOTES

Under glibc2, <time.h> only provides a prototype when _SVID_SOURCE is defined.

SEE ALSO

date(1), settimeofday(2), capabilities(7), feature_test_macros(7)


chown(2)

CHOWN

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

chown, fchown, lchown - change ownership of a file

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int chown(const char *path, uid_t owner, gid_t group);
int fchown(int fd, uid_t owner, gid_t group);
int lchown(const char *path, uid_t owner, gid_t group);

DESCRIPTION

These system calls change the owner and group of the file specified by path or by fd. Only a privileged process (Linux: one with the CAP_CHOWN capability) may change the owner of a file. The owner of a file may change the group of the file to any group of which that owner is a member. A privileged process (Linux: with CAP_CHOWN) may change the group arbitrarily.

If the owner or group is specified as -1, then that ID is not changed.

When the owner or group of an executable file are changed by a non-superuser, the S_ISUID and S_ISGID mode bits are cleared. POSIX does not specify whether this also should happen when root does the chown(); the Linux behavior depends on the kernel version. In case of a non-group-executable file (with clear S_IXGRP bit) the S_ISGID bit indicates mandatory locking, and is not cleared by a chown().

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

Depending on the file system, other errors can be returned. The more general errors for chown() are listed below.
EACCES
Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
EFAULT
path points outside your accessible address space.
ELOOP
Too many symbolic links were encountered in resolving path.
ENAMETOOLONG
path is too long.
ENOENT
The file does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The calling process did not have the required permissions (see above) to change owner and/or group.
EROFS
The named file resides on a read-only file system.

The general errors for fchown() are listed below:

EBADF
The descriptor is not valid.
EIO
A low-level I/O error occurred while modifying the inode.
ENOENT
See above.
EPERM
See above.
EROFS
See above.

CONFORMING TO

4.4BSD, SVr4, POSIX.1-2001.

The 4.4BSD version can only be used by the superuser (that is, ordinary users cannot give away files).

NOTES

The chown() semantics are deliberately violated on NFS file systems which have UID mapping enabled. Additionally, the semantics of all system calls which access the file contents are violated, because chown() may cause immediate access revocation on already open files. Client side caching may lead to a delay between the time where ownership have been changed to allow access for a user and the time where the file can actually be accessed by the user on other clients.

In versions of Linux prior to 2.1.81 (and distinct from 2.1.46), chown() did not follow symbolic links. Since Linux 2.1.81, chown() does follow symbolic links, and there is a new system call lchown() that does not follow symbolic links. Since Linux 2.1.86, this new call (that has the same semantics as the old chown()) has got the same syscall number, and chown() got the newly introduced number.

The prototype for fchown() is only available if _BSD_SOURCE is defined.

SEE ALSO

chmod(2), fchownat(2), flock(2), path_resolution(7)


chroot(2)

CHROOT

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

chroot - change root directory

SYNOPSIS

#include <unistd.h>

int chroot(const char *path);

DESCRIPTION

chroot() changes the root directory to that specified in path. This directory will be used for pathnames beginning with /. The root directory is inherited by all children of the current process.

Only a privileged process (Linux: one with the CAP_SYS_CHROOT capability) may call chroot(2).

This call changes an ingredient in the pathname resolution process and does nothing else.

This call does not change the current working directory, so that after the call `.' can be outside the tree rooted at `/'. In particular, the superuser can escape from a `chroot jail' by doing `mkdir foo; chroot foo; cd ..'.

This call does not close open file descriptors, and such file descriptors may allow access to files outside the chroot tree.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

Depending on the file system, other errors can be returned. The more general errors are listed below:
EACCES
Search permission is denied on a component of the path prefix. (See also path_resolution(7).)
EFAULT
path points outside your accessible address space.
EIO
An I/O error occurred.
ELOOP
Too many symbolic links were encountered in resolving path.
ENAMETOOLONG
path is too long.
ENOENT
The file does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
A component of path is not a directory.
EPERM
The caller has insufficient privilege.

CONFORMING TO

SVr4, 4.4BSD, SUSv2 (marked LEGACY). This function is not part of POSIX.1-2001.

NOTES

A child process created via fork(2) inherits its parent's root directory. The root directory is left unchanged by execve(2).

FreeBSD has a stronger jail() system call.

SEE ALSO

chdir(2), path_resolution(7)


clone(2)

CLONE

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

clone - create a child process

SYNOPSIS

#include <sched.h>

int clone(int (*fn)(void *), void *child_stack,
          int flags, void *arg, ...
          /* pid_t *pid, struct user_desc *tls, pid_t *ctid */ );

DESCRIPTION

clone() creates a new process, in a manner similar to fork(2). It is actually a library function layered on top of the underlying clone() system call, hereinafter referred to as sys_clone. A description of sys_clone is given towards the end of this page.

Unlike fork(2), these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. (Note that on this manual page, "calling process" normally corresponds to "parent process". But see the description of CLONE_PARENT below.)

The main use of clone() is to implement threads: multiple threads of control in a program that run concurrently in a shared memory space.

When the child process is created with clone(), it executes the function application fn(arg). (This differs from fork(2), where execution continues in the child from the point of the fork(2) call.) The fn argument is a pointer to a function that is called by the child process at the beginning of its execution. The arg argument is passed to the fn function.

When the fn(arg) function application returns, the child process terminates. The integer returned by fn is the exit code for the child process. The child process may also terminate explicitly by calling exit(2) or after receiving a fatal signal.

The child_stack argument specifies the location of the stack used by the child process. Since the child and calling process may share memory, it is not possible for the child process to execute in the same stack as the calling process. The calling process must therefore set up memory space for the child stack and pass a pointer to this space to clone(). Stacks grow downwards on all processors that run Linux (except the HP PA processors), so child_stack usually points to the topmost address of the memory space set up for the child stack.

The low byte of flags contains the number of the termination signal sent to the parent when the child dies. If this signal is specified as anything other than SIGCHLD, then the parent process must specify the __WALL or __WCLONE options when waiting for the child with wait(2). If no signal is specified, then the parent process is not signaled when the child terminates.

flags may also be bitwise-or'ed with zero or more of the following constants, in order to specify what is shared between the calling process and the child process:

CLONE_PARENT (since Linux 2.3.12)
If CLONE_PARENT is set, then the parent of the new child (as returned by getppid(2)) will be the same as that of the calling process.

If CLONE_PARENT is not set, then (as with fork(2)) the child's parent is the calling process.

Note that it is the parent process, as returned by getppid(2), which is signaled when the child terminates, so that if CLONE_PARENT is set, then the parent of the calling process, rather than the calling process itself, will be signaled.

CLONE_FS
If CLONE_FS is set, the caller and the child processes share the same file system information. This includes the root of the file system, the current working directory, and the umask. Any call to chroot(2), chdir(2), or umask(2) performed by the calling process or the child process also affects the other process.

If CLONE_FS is not set, the child process works on a copy of the file system information of the calling process at the time of the clone() call. Calls to chroot(2), chdir(2), umask(2) performed later by one of the processes do not affect the other process.

CLONE_FILES
If CLONE_FILES is set, the calling process and the child processes share the same file descriptor table. Any file descriptor created by the calling process or by the child process is also valid in the other process. Similarly, if one of the processes closes a file descriptor, or changes its associated flags (using the fcntl(2) F_SETFD operation), the other process is also affected.

If CLONE_FILES is not set, the child process inherits a copy of all file descriptors opened in the calling process at the time of clone(). (The duplicated file descriptors in the child refer to the same open file descriptions (see open(2)) as the corresponding file descriptors in the calling process.) Subsequent operations that open or close file descriptors, or change file descriptor flags, performed by either the calling process or the child process do not affect the other process.

CLONE_NEWNS (since Linux 2.4.19)
Start the child in a new namespace.

Every process lives in a namespace. The namespace of a process is the data (the set of mounts) describing the file hierarchy as seen by that process. After a fork(2) or clone(2) where the CLONE_NEWNS flag is not set, the child lives in the same namespace as the parent. The system calls mount(2) and umount(2) change the namespace of the calling process, and hence affect all processes that live in the same namespace, but do not affect processes in a different namespace.

After a clone(2) where the CLONE_NEWNS flag is set, the cloned child is started in a new namespace, initialized with a copy of the namespace of the parent.

Only a privileged process (one having the CAP_SYS_ADMIN capability) may specify the CLONE_NEWNS flag. It is not permitted to specify both CLONE_NEWNS and CLONE_FS in the same clone() call.

CLONE_SIGHAND
If CLONE_SIGHAND is set, the calling process and the child processes share the same table of signal handlers. If the calling process or child process calls sigaction(2) to change the behavior associated with a signal, the behavior is changed in the other process as well. However, the calling process and child processes still have distinct signal masks and sets of pending signals. So, one of them may block or unblock some signals using sigprocmask(2) without affecting the other process.

If CLONE_SIGHAND is not set, the child process inherits a copy of the signal handlers of the calling process at the time clone() is called. Calls to sigaction(2) performed later by one of the processes have no effect on the other process.

Since Linux 2.6.0-test6, flags must also include CLONE_VM if CLONE_SIGHAND is specified

CLONE_PTRACE
If CLONE_PTRACE is specified, and the calling process is being traced, then trace the child also (see ptrace(2)).
CLONE_UNTRACED (since Linux 2.5.46)
If CLONE_UNTRACED is specified, then a tracing process cannot force CLONE_PTRACE on this child process.
CLONE_STOPPED (since Linux 2.6.0-test2)
If CLONE_STOPPED is set, then the child is initially stopped (as though it was sent a SIGSTOP signal), and must be resumed by sending it a SIGCONT signal.
CLONE_VFORK
If CLONE_VFORK is set, the execution of the calling process is suspended until the child releases its virtual memory resources via a call to execve(2) or _exit(2) (as with vfork(2)).

If CLONE_VFORK is not set then both the calling process and the child are schedulable after the call, and an application should not rely on execution occurring in any particular order.

CLONE_VM
If CLONE_VM is set, the calling process and the child processes run in the same memory space. In particular, memory writes performed by the calling process or by the child process are also visible in the other process. Moreover, any memory mapping or unmapping performed with mmap(2) or munmap(2) by the child or calling process also affects the other process.

If CLONE_VM is not set, the child process runs in a separate copy of the memory space of the calling process at the time of clone(). Memory writes or file mappings/unmappings performed by one of the processes do not affect the other, as with fork(2).

CLONE_PID (obsolete)
If CLONE_PID is set, the child process is created with the same process ID as the calling process. This is good for hacking the system, but otherwise of not much use. Since 2.3.21 this flag can be specified only by the system boot process (PID 0). It disappeared in Linux 2.5.16.
CLONE_THREAD (since Linux 2.4.0-test8)
If CLONE_THREAD is set, the child is placed in the same thread group as the calling process. To make the remainder of the discussion of CLONE_THREAD more readable, the term "thread" is used to refer to the processes within a thread group.

Thread groups were a feature added in Linux 2.4 to support the POSIX threads notion of a set of threads that share a single PID. Internally, this shared PID is the so-called thread group identifier (TGID) for the thread group. Since Linux 2.4, calls to getpid(2) return the TGID of the caller.

The threads within a group can be distinguished by their (system-wide) unique thread IDs (TID). A new thread's TID is available as the function result returned to the caller of clone(), and a thread can obtain its own TID using gettid(2).

When a call is made to clone() without specifying CLONE_THREAD, then the resulting thread is placed in a new thread group whose TGID is the same as the thread's TID. This thread is the leader of the new thread group.

A new thread created with CLONE_THREAD has the same parent process as the caller of clone() (i.e., like CLONE_PARENT), so that calls to getppid(2) return the same value for all of the threads in a thread group. When a CLONE_THREAD thread terminates, the thread that created it using clone() is not sent a SIGCHLD (or other termination) signal; nor can the status of such a thread be obtained using wait(2). (The thread is said to be detached.)

After all of the threads in a thread group terminate the parent process of the thread group is sent a SIGCHLD (or other termination) signal.

If any of the threads in a thread group performs an execve(2), then all threads other than the thread group leader are terminated, and the new program is executed in the thread group leader.

If one of the threads in a thread group creates a child using fork(2), then any thread in the group can wait(2) for that child.

Since Linux 2.5.35, flags must also include CLONE_SIGHAND if CLONE_THREAD is specified.

Signals may be sent to a thread group as a whole (i.e., a TGID) using kill(2), or to a specific thread (i.e., TID) using tgkill(2).

Signal dispositions and actions are process-wide: if an unhandled signal is delivered to a thread, then it will affect (terminate, stop, continue, be ignored in) all members of the thread group.

Each thread has its own signal mask, as set by sigprocmask(2), but signals can be pending either: for the whole process (i.e., deliverable to any member of the thread group), when sent with kill(2); or for an individual thread, when sent with tgkill(2). A call to sigpending(2) returns a signal set that is the union of the signals pending for the whole process and the signals that are pending for the calling thread.

If kill(2) is used to send a signal to a thread group, and the thread group has installed a handler for the signal, then the handler will be invoked in exactly one, arbitrarily selected member of the thread group that has not blocked the signal. If multiple threads in a group are waiting to accept the same signal using sigwaitinfo(2), the kernel will arbitrarily select one of these threads to receive a signal sent using kill(2).

CLONE_SYSVSEM (since Linux 2.5.10)
If CLONE_SYSVSEM is set, then the child and the calling process share a single list of System V semaphore undo values (see semop(2)). If this flag is not set, then the child has a separate undo list, which is initially empty.
CLONE_SETTLS (since Linux 2.5.32)
The newtls parameter is the new TLS (Thread Local Storage) descriptor. (See set_thread_area(2).)
CLONE_PARENT_SETTID (since Linux 2.5.49)
Store child thread ID at location parent_tidptr in parent and child memory. (In Linux 2.5.32-2.5.48 there was a flag CLONE_SETTID that did this.)
CLONE_CHILD_SETTID (since Linux 2.5.49)
Store child thread ID at location child_tidptr in child memory.
CLONE_CHILD_CLEARTID (since Linux 2.5.49)
Erase child thread ID at location child_tidptr in child memory when the child exits, and do a wakeup on the futex at that address. The address involved may be changed by the set_tid_address(2) system call. This is used by threading libraries.

sys_clone

The sys_clone system call corresponds more closely to fork(2) in that execution in the child continues from the point of the call. Thus, sys_clone only requires the flags and child_stack arguments, which have the same meaning as for clone(). (Note that the order of these arguments differs from clone().)

Another difference for sys_clone is that the child_stack argument may be zero, in which case copy-on-write semantics ensure that the child gets separate copies of stack pages when either process modifies the stack. In this case, for correct operation, the CLONE_VM option should not be specified.

Since Linux 2.5.49 the system call has five parameters. The two new parameters are parent_tidptr which points to the location (in parent and child memory) where the child thread ID will be written in case CLONE_PARENT_SETTID was specified, and child_tidptr which points to the location (in child memory) where the child thread ID will be written in case CLONE_CHILD_SETTID was specified.

RETURN VALUE

On success, the thread ID of the child process is returned in the caller's thread of execution. On failure, a -1 will be returned in the caller's context, no child process will be created, and errno will be set appropriately.

ERRORS

EAGAIN
Too many processes are already running.
EINVAL
CLONE_SIGHAND was specified, but CLONE_VM was not. (Since Linux 2.6.0-test6.)
EINVAL
CLONE_THREAD was specified, but CLONE_SIGHAND was not. (Since Linux 2.5.35.)
EINVAL
Both CLONE_FS and CLONE_NEWNS were specified in flags.
EINVAL
Returned by clone() when a zero value is specified for child_stack.
ENOMEM
Cannot allocate sufficient memory to allocate a task structure for the child, or to copy those parts of the caller's context that need to be copied.
EPERM
CLONE_NEWNS was specified by a non-root process (process without CAP_SYS_ADMIN).
EPERM
CLONE_PID was specified by a process other than process 0.

VERSIONS

There is no entry for clone() in libc5. glibc2 provides clone() as described in this manual page.

CONFORMING TO

The clone() and sys_clone calls are Linux specific and should not be used in programs intended to be portable.

NOTES

In the kernel 2.4.x series, CLONE_THREAD generally does not make the parent of the new thread the same as the parent of the calling process. However, for kernel versions 2.4.7 to 2.4.18 the CLONE_THREAD flag implied the CLONE_PARENT flag (as in kernel 2.6).

For a while there was CLONE_DETACHED (introduced in 2.5.32): parent wants no child-exit signal. In 2.6.2 the need to give this together with CLONE_THREAD disappeared. This flag is still defined, but has no effect.

On x86, clone() should not be called through vsyscall, but directly through int $0x80.

On IA-64, a different system call is used:

int clone2(int (*fn)(void *),
           void *child_stack_base, size_t stack_size,
           int flags, void *arg, ...
           /* pid_t *pid, struct user_desc *tls, pid_t *ctid */ );

The clone2() system call operates in the same way as clone(), except that child_stack_base points to the lowest address of the child's stack area, and stack_size specifies the size of the stack pointed to by child_stack_base.

BUGS

Versions of the GNU C library that include the NPTL threading library contain a wrapper function for getpid(2) that performs caching of PIDs. In programs linked against such libraries, calls to getpid(2) may return the same value, even when the threads were not created using CLONE_THREAD (and thus are not in the same thread group). To get the truth, it may be necessary to use code such as the following

    #include <syscall.h>

    pid_t mypid;

    mypid = syscall(SYS_getpid);

SEE ALSO

fork(2), futex(2), getpid(2), gettid(2), set_thread_area(2), set_tid_address(2), tkill(2), unshare(2), wait(2), capabilities(7), pthreads(7)


getresgid (2)

 Continue to this page.


getresuid(2)

GETRESUID

Section: Linux Programmer's Manual (2)
Updated: 2003-05-26 Return to Main Contents

NAME

getresuid, getresgid - get real, effective and saved user or group ID

SYNOPSIS

#define _GNU_SOURCE
#include <unistd.h>

int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);

DESCRIPTION

getresuid() and getresgid() (both introduced in Linux 2.1.44) get the real UID, effective UID, and saved set-user-ID (resp. group ID's) of the current process.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
One of the arguments specified an address outside the calling program's address space.

CONFORMING TO

These calls are non-standard; they also appear on HP-UX and some of the BSDs.

The prototype is given by glibc since version 2.3.2 provided _GNU_SOURCE is defined.

SEE ALSO

getuid(2), setresuid(2), setreuid(2), setuid(2), feature_test_macros(7)


idle(2)

IDLE

Section: Linux Programmer's Manual (2)
Updated: 1994-08-21 Return to Main Contents

NAME

idle - make process 0 idle

SYNOPSIS

#include <unistd.h>

int idle(void);

DESCRIPTION

idle() is an internal system call used during bootstrap. It marks the process's pages as swappable, lowers its priority, and enters the main scheduling loop. idle() never returns.

Only process 0 may call idle(). Any user process, even a process with superuser permission, will receive EPERM.

RETURN VALUE

idle() never returns for process 0, and always returns -1 for a user process.

ERRORS

EPERM
Always, for a user process.

CONFORMING TO

This function is Linux specific, and should not be used in programs intended to be portable.

NOTES

Since 2.3.13 this system call does not exist anymore.


mkdir(2)

MKDIR

Section: Linux Programmer's Manual (2)
Updated: 2003-12-09 Return to Main Contents

NAME

mkdir - create a directory

SYNOPSIS

#include <sys/stat.h>
#include <sys/types.h>

int mkdir(const char *pathname, mode_t mode);

DESCRIPTION

mkdir() attempts to create a directory named pathname.

The parameter mode specifies the permissions to use. It is modified by the process's umask in the usual way: the permissions of the created directory are (mode & ~umask & 0777). Other mode bits of the created directory depend on the operating system. For Linux, see below.

The newly created directory will be owned by the effective user ID of the process. If the directory containing the file has the set-group-ID bit set, or if the filesystem is mounted with BSD group semantics, the new directory will inherit the group ownership from its parent; otherwise it will be owned by the effective group ID of the process.

If the parent directory has the set-group-ID bit set then so will the newly created directory.

RETURN VALUE

mkdir() returns zero on success, or -1 if an error occurred (in which case, errno is set appropriately).

ERRORS

EACCES
The parent directory does not allow write permission to the process, or one of the directories in pathname did not allow search permission. (See also path_resolution(7).)
EEXIST
pathname already exists (not necessarily as a directory). This includes the case where pathname is a symbolic link, dangling or not.
EFAULT
pathname points outside your accessible address space.
ELOOP
Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname was too long.
ENOENT
A directory component in pathname does not exist or is a dangling symbolic link.
ENOMEM
Insufficient kernel memory was available.
ENOSPC
The device containing pathname has no room for the new directory.
ENOSPC
The new directory cannot be created because the user's disk quota is exhausted.
ENOTDIR
A component used as a directory in pathname is not, in fact, a directory.
EPERM
The filesystem containing pathname does not support the creation of directories.
EROFS
pathname refers to a file on a read-only filesystem.

CONFORMING TO

SVr4, BSD, POSIX.1-2001.

NOTES

Under Linux apart from the permission bits, only the S_ISVTX mode bit is honored. That is, under Linux the created directory actually gets mode (mode & ~umask & 01777). See also stat(2).

There are many infelicities in the protocol underlying NFS. Some of these affect mkdir().

SEE ALSO

mkdir(1), chmod(2), mkdirat(2), mknod(2), mount(2), rmdir(2), stat(2), umask(2), unlink(2), path_resolution(7)


mknod(2)

MKNOD

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

mknod - create a special or ordinary file

SYNOPSIS

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int mknod(const char *pathname, mode_t mode, dev_t dev);

DESCRIPTION

The system call mknod() creates a filesystem node (file, device special file or named pipe) named pathname, with attributes specified by mode and dev.

The mode argument specifies both the permissions to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and the permissions for the new node.

The permissions are modified by the process's umask in the usual way: the permissions of the created node are (mode & ~umask).

The file type must be one of S_IFREG, S_IFCHR, S_IFBLK, S_IFIFO or S_IFSOCK to specify a normal file (which will be created empty), character special file, block special file, FIFO (named pipe), or Unix domain socket, respectively. (Zero file type is equivalent to type S_IFREG.)

If the file type is S_IFCHR or S_IFBLK then dev specifies the major and minor numbers of the newly created device special file; otherwise it is ignored.

If pathname already exists, or is a symbolic link, this call fails with an EEXIST error.

The newly created node will be owned by the effective user ID of the process. If the directory containing the node has the set-group-ID bit set, or if the filesystem is mounted with BSD group semantics, the new node will inherit the group ownership from its parent directory; otherwise it will be owned by the effective group ID of the process.

RETURN VALUE

mknod() returns zero on success, or -1 if an error occurred (in which case, errno is set appropriately).

ERRORS

EACCES
The parent directory does not allow write permission to the process, or one of the directories in the path prefix of pathname did not allow search permission. (See also path_resolution(7).)
EEXIST
pathname already exists.
EFAULT
pathname points outside your accessible address space.
EINVAL
mode requested creation of something other than a normal file, device special file, FIFO or socket.
ELOOP
Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname was too long.
ENOENT
A directory component in pathname does not exist or is a dangling symbolic link.
ENOMEM
Insufficient kernel memory was available.
ENOSPC
The device containing pathname has no room for the new node.
ENOTDIR
A component used as a directory in pathname is not, in fact, a directory.
EPERM
mode requested creation of something other than a regular file, FIFO (named pipe), or Unix domain socket, and the caller is not privileged (Linux: does not have the CAP_MKNOD capability); also returned if the filesystem containing pathname does not support the type of node requested.
EROFS
pathname refers to a file on a read-only filesystem.

CONFORMING TO

SVr4, 4.4BSD, POSIX.1-2001 (but see below).

NOTES

POSIX.1-2001 says: "The only portable use of mknod() is to create a FIFO-special file. If mode is not S_IFIFO or dev is not 0, the behavior of mknod() is unspecified."

Under Linux, this call cannot be used to create directories. One should make directories with mkdir(2), and FIFOs with mkfifo(3).

There are many infelicities in the protocol underlying NFS. Some of these affect mknod().

SEE ALSO

fcntl(2), mkdir(2), mknodat(2), mount(2), socket(2), stat(2), umask(2), unlink(2), mkfifo(3), path_resolution(7)


stat(2)

STAT

Section: Linux Programmer's Manual (2)
Updated: 2007-06-08 Return to Main Contents

NAME

stat, fstat, lstat - get file status

SYNOPSIS

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int stat(const char *path, struct stat *buf);
int fstat(int filedes, struct stat *buf);
int lstat(const char *path, struct stat *buf);

DESCRIPTION

These functions return information about a file. No permissions are required on the file itself, but --- in the case of stat() and lstat() --- execute (search) permission is required on all of the directories in path that lead to the file.

stat() stats the file pointed to by path and fills in buf.

lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.

fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor filedes.

All of these system calls return a stat structure, which contains the following fields:

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for filesystem I/O */
    blkcnt_t  st_blocks;  /* number of blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

The st_dev field describes the device on which this file resides.

The st_rdev field describes the device that this file (inode) represents.

The st_size field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symlink is the length of the pathname it contains, without a trailing null byte.

The st_blocks field indicates the number of blocks allocated to the file, 512-byte units. (This may be smaller than st_size/512, for example, when the file has holes.)

The st_blksize field gives the "preferred" blocksize for efficient file system I/O. (Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.)

Not all of the Linux filesystems implement all of the time fields. Some file system types allow mounting in such a way that file accesses do not cause an update of the st_atime field. (See `noatime' in mount(8).)

The field st_atime is changed by file accesses, for example, by execve(2), mknod(2), pipe(2), utime(2) and read(2) (of more than zero bytes). Other routines, like mmap(2), may or may not update st_atime.

The field st_mtime is changed by file modifications, for example, by mknod(2), truncate(2), utime(2) and write(2) (of more than zero bytes). Moreover, st_mtime of a directory is changed by the creation or deletion of files in that directory. The st_mtime field is not changed for changes in owner, group, hard link count, or mode.

The field st_ctime is changed by writing or by setting inode information (i.e., owner, group, link count, mode, etc.).

The following POSIX macros are defined to check the file type using the st_mode field:

S_ISREG(m)
is it a regular file?
S_ISDIR(m)
directory?
S_ISCHR(m)
character device?
S_ISBLK(m)
block device?
S_ISFIFO(m)
FIFO (named pipe)?
S_ISLNK(m)
symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m)
socket? (Not in POSIX.1-1996.)

The following flags are defined for the st_mode field:
S_IFMT | 0170000 | bitmask for the file type bitfields
S_IFSOCK | 0140000 | socket
S_IFLNK | 0120000 | symbolic link
S_IFREG | 0100000 | regular file
S_IFBLK | 0060000 | block device
S_IFDIR | 0040000 | directory
S_IFCHR | 0020000 | character device
S_IFIFO | 0010000 | FIFO
S_ISUID | 0004000 | set UID bit
S_ISGID | 0002000 | set-group-ID bit (see below)
S_ISVTX | 0001000 | sticky bit (see below)
S_IRWXU | 00700 | mask for file owner permissions
S_IRUSR | 00400 | owner has read permission
S_IWUSR | 00200 | owner has write permission
S_IXUSR | 00100 | owner has execute permission
S_IRWXG | 00070 | mask for group permissions
S_IRGRP | 00040 | group has read permission
S_IWGRP | 00020 | group has write permission
S_IXGRP | 00010 | group has execute permission
S_IRWXO | 00007 | mask for permissions for others (not in group)
S_IROTH | 00004 | others have read permission
S_IWOTH | 00002 | others have write permission
S_IXOTH | 00001 | others have execute permission
The set-group-ID bit (S_ISGID) has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking. The `sticky' bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, and by a privileged process.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Search permission is denied for one of the directories in the path prefix of path. (See also path_resolution(7).)
EBADF
filedes is bad.
EFAULT
Bad address.
ELOOP
Too many symbolic links encountered while traversing the path.
ENAMETOOLONG
File name too long.
ENOENT
A component of the path path does not exist, or the path is an empty string.
ENOMEM
Out of memory (i.e., kernel memory).
ENOTDIR
A component of the path is not a directory.

CONFORMING TO

These system calls conform to SVr4, 4.3BSD, POSIX.1-2001.

Use of the st_blocks and st_blksize fields may be less portable. (They were introduced in BSD. The interpretation differs between systems, and possibly on a single system when NFS mounts are involved.)

POSIX does not describe the S_IFMT, S_IFSOCK, S_IFLNK, S_IFREG, S_IFBLK, S_IFDIR, S_IFCHR, S_IFIFO, S_ISVTX bits, but instead demands the use of the macros S_ISDIR(), etc. The S_ISLNK and S_ISSOCK macros are not in POSIX.1-1996, but both are present in POSIX.1-2001; the former is from SVID 4, the latter from SUSv2.

Unix V7 (and later systems) had S_IREAD, S_IWRITE, S_IEXEC, where POSIX prescribes the synonyms S_IRUSR, S_IWUSR, S_IXUSR.

Other Systems

Values that have been (or are) in use on various systems:
hex | name | ls | octal | description
f000 | S_IFMT |  | 170000 | mask for file type
0000 |  |  | 000000 | SCO out-of-service inode, BSD unknown type
 |  |  |  | SVID-v2 and XPG2 have both 0 and 0100000 for ordinary file
1000 | S_IFIFO | p| | 010000 | FIFO (named pipe)
2000 | S_IFCHR | c | 020000 | character special (V7)
3000 | S_IFMPC |  | 030000 | multiplexed character special (V7)
4000 | S_IFDIR | d/ | 040000 | directory (V7)
5000 | S_IFNAM |  | 050000 | XENIX named special file
 |  |  |  | with two subtypes, distinguished by st_rdev values 1, 2:
0001 | S_INSEM | s | 000001 | XENIX semaphore subtype of IFNAM
0002 | S_INSHD | m | 000002 | XENIX shared data subtype of IFNAM
6000 | S_IFBLK | b | 060000 | block special (V7)
7000 | S_IFMPB |  | 070000 | multiplexed block special (V7)
8000 | S_IFREG | - | 100000 | regular (V7)
9000 | S_IFCMP |  | 110000 | VxFS compressed
9000 | S_IFNWK | n | 110000 | network special (HP-UX)
a000 | S_IFLNK | l@ | 120000 | symbolic link (BSD)
b000 | S_IFSHAD |  | 130000 | Solaris shadow inode for ACL (not seen by userspace)
c000 | S_IFSOCK | s= | 140000 | socket (BSD; also "S_IFSOC" on VxFS)
d000 | S_IFDOOR | D> | 150000 | Solaris door
e000 | S_IFWHT | w% | 160000 | BSD whiteout (not used for inode)
0200 | S_ISVTX |  | 001000 | `sticky bit': save swapped text even after use (V7)
 |  |  |  | reserved (SVID-v2)
 |  |  |  | On non-directories: don't cache this file (SunOS)
 |  |  |  | On directories: restricted deletion flag (SVID-v4.2)
0400 | S_ISGID |  | 002000 | set-group-ID on execution (V7)
 |  |  |  | for directories: use BSD semantics for propagation of GID
0400 | S_ENFMT |  | 002000 | SysV file locking enforcement (shared with S_ISGID)
0800 | S_ISUID |  | 004000 | set-user-ID on execution (V7)
0800 | S_CDF |  | 004000 | directory is a context dependent file (HP-UX)

A sticky command appeared in Version 32V AT&T UNIX.

NOTES

Linux Notes

Since kernel 2.5.48, the stat structure supports nanosecond resolution for the three file timestamp fields. Glibc exposes the nanosecond component of each field using names either of the form st_atim.tv_nsec, if the _BSD_SOURCE or _SVID_SOURCE feature test macro is defined, or of the form st_atimensec, if neither of these macros is defined. On file systems that do not support sub-second timestamps, these nanosecond fields are returned with the value 0.

For most files under the /proc directory, stat() does not return the file size in the st_size field; instead the field is returned with the value 0.

EXAMPLE

The following program calls stat(2) and displays selected fields in the returned stat structure.

#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    struct stat sb;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (stat(argv[1], &sb) == -1) {
        perror("stat");
        exit(EXIT_SUCCESS);
    }

    printf("File type:                ");
    switch (sb.st_mode & S_IFMT) {
    case S_IFBLK:  printf("block device\n");            break;
    case S_IFCHR:  printf("character device\n");        break;
    case S_IFDIR:  printf("directory\n");               break;
    case S_IFIFO:  printf("FIFO/pipe\n");               break;
    case S_IFLNK:  printf("symlink\n");                 break;
    case S_IFREG:  printf("regular file\n");            break;
    case S_IFSOCK: printf("socket\n");                  break;
    default:       printf("unknown?\n");                break;
    }

    printf("I-node number:            %ld\n", (long) sb.st_ino);

    printf("Mode:                     %lo (octal)\n",
            (unsigned long) sb.st_mode);

    printf("Link count:               %ld\n", (long) sb.st_nlink);
    printf("Ownership:                UID=%ld   GID=%ld\n",
            (long) sb.st_uid, (long) sb.st_gid);

    printf("Preferred I/O block size: %ld bytes\n",
            (long) sb.st_blksize);
    printf("File size:                %lld bytes\n",
            (long long) sb.st_size);
    printf("Blocks allocated:         %lld\n",
            (long long) sb.st_blocks);

    printf("Last i-node change:       %s", ctime(&sb.st_ctime));
    printf("Last file access:         %s", ctime(&sb.st_atime));
    printf("Last file modification:   %s", ctime(&sb.st_mtime));

    exit(EXIT_SUCCESS);
}

SEE ALSO

access(2), chmod(2), chown(2), fstatat(2), readlink(2), utime(2), capabilities(7)


swapoff (2)

 Continue to this page.


getsockname(2)

GETSOCKNAME

Section: Linux Programmer's Manual (2)
Updated: 1993-07-24 Return to Main Contents

NAME

getsockname - get socket name

SYNOPSIS

#include <sys/socket.h>

int getsockname(int s, struct sockaddr *name, socklen_t *namelen);

DESCRIPTION

getsockname() returns the current name for the specified socket. The namelen parameter should be initialized to indicate the amount of space pointed to by name. On return it contains the actual size of the name returned (in bytes).

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
The argument s is not a valid descriptor.
EFAULT
The name parameter points to memory not in a valid part of the process address space.
EINVAL
namelen is invalid (e.g., is negative).
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOTSOCK
The argument s is a file, not a socket.

CONFORMING TO

SVr4, 4.4BSD (the getsockname() function call appeared in 4.2BSD), POSIX.1-2001.

NOTES

The third argument of getsockname() is in reality an `int *' (and this is what 4.x BSD and libc4 and libc5 have). Some POSIX confusion resulted in the present socklen_t, also used by glibc. See also accept(2).

SEE ALSO

bind(2), socket(2)


alarm(2)

ALARM

Section: Linux Programmer's Manual (2)
Updated: 1993-07-21 Return to Main Contents

NAME

alarm - set an alarm clock for delivery of a signal

SYNOPSIS

#include <unistd.h>

unsigned int alarm(unsigned int seconds);

DESCRIPTION

alarm() arranges for a SIGALRM signal to be delivered to the process in seconds seconds.

If seconds is zero, no new alarm() is scheduled.

In any event any previously set alarm() is canceled.

RETURN VALUE

alarm() returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD

NOTES

alarm() and setitimer(2) share the same timer; calls to one will interfere with use of the other.

sleep(3) may be implemented using SIGALRM; mixing calls to alarm() and sleep(3) is a bad idea.

Scheduling delays can, as ever, cause the execution of the process to be delayed by an arbitrary amount of time.

SEE ALSO

gettimeofday(2), pause(2), select(2), setitimer(2), sigaction(2), signal(2), sleep(3), time(7)


sigreturn(2)

SIGRETURN

Section: Linux Programmer's Manual (2)
Updated: 1995-08-21 Return to Main Contents

NAME

sigreturn - return from signal handler and cleanup stack frame

SYNOPSIS

int sigreturn(unsigned long __unused);

DESCRIPTION

When the Linux kernel creates the stack frame for a signal handler, a call to sigreturn() is inserted into the stack frame so that the signal handler will call sigreturn() upon return. This inserted call to sigreturn() cleans up the stack so that the process can restart from where it was interrupted by the signal.

RETURN VALUE

sigreturn() never returns.

FILES

/usr/src/linux/arch/i386/kernel/signal.c
/usr/src/linux/arch/alpha/kernel/entry.S

CONFORMING TO

sigreturn() is specific to Linux and should not be used in programs intended to be portable.

NOTES

The sigreturn() call is used by the kernel to implement signal handlers. It should never be called directly. Better yet, the specific use of the __unused argument varies depending on the architecture.

SEE ALSO

kill(2), signal(2), signal(7)


sigsetmask (2)

 Continue to this page.


getgid(2)

GETGID

Section: Linux Programmer's Manual (2)
Updated: 1993-07-23 Return to Main Contents

NAME

getgid, getegid - get group identity

SYNOPSIS

#include <unistd.h>
#include <sys/types.h>

gid_t getgid(void);
gid_t getegid(void);

DESCRIPTION

getgid() returns the real group ID of the current process.

getegid() returns the effective group ID of the current process.

ERRORS

These functions are always successful.

CONFORMING TO

POSIX.1-2001, 4.3BSD

SEE ALSO

setgid(2), setregid(2)


statfs(2)

STATFS

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

statfs, fstatfs - get file system statistics

SYNOPSIS

#include <sys/vfs.h> /* or <sys/statfs.h> */

int statfs(const char *path, struct statfs *buf);
int fstatfs(int fd, struct statfs *buf);

DESCRIPTION

The function statfs() returns information about a mounted file system. path is the pathname of any file within the mounted filesystem. buf is a pointer to a statfs structure defined approximately as follows:

struct statfs {
   long    f_type;     /* type of filesystem (see below) */
   long    f_bsize;    /* optimal transfer block size */
   long    f_blocks;   /* total data blocks in file system */
   long    f_bfree;    /* free blocks in fs */
   long    f_bavail;   /* free blocks avail to non-superuser */
   long    f_files;    /* total file nodes in file system */
   long    f_ffree;    /* free file nodes in fs */
   fsid_t  f_fsid;     /* file system id */
   long    f_namelen;  /* maximum length of filenames */
};

File system types:

   ADFS_SUPER_MAGIC      0xadf5
   AFFS_SUPER_MAGIC      0xADFF
   BEFS_SUPER_MAGIC      0x42465331
   BFS_MAGIC             0x1BADFACE
   CIFS_MAGIC_NUMBER     0xFF534D42
   CODA_SUPER_MAGIC      0x73757245
   COH_SUPER_MAGIC       0x012FF7B7
   CRAMFS_MAGIC          0x28cd3d45
   DEVFS_SUPER_MAGIC     0x1373
   EFS_SUPER_MAGIC       0x00414A53
   EXT_SUPER_MAGIC       0x137D
   EXT2_OLD_SUPER_MAGIC  0xEF51
   EXT2_SUPER_MAGIC      0xEF53
   EXT3_SUPER_MAGIC      0xEF53
   HFS_SUPER_MAGIC       0x4244
   HPFS_SUPER_MAGIC      0xF995E849
   HUGETLBFS_MAGIC       0x958458f6
   ISOFS_SUPER_MAGIC     0x9660
   JFFS2_SUPER_MAGIC     0x72b6
   JFS_SUPER_MAGIC       0x3153464a
   MINIX_SUPER_MAGIC     0x137F /* orig. minix */
   MINIX_SUPER_MAGIC2    0x138F /* 30 char minix */
   MINIX2_SUPER_MAGIC    0x2468 /* minix V2 */
   MINIX2_SUPER_MAGIC2   0x2478 /* minix V2, 30 char names */
   MSDOS_SUPER_MAGIC     0x4d44
   NCP_SUPER_MAGIC       0x564c
   NFS_SUPER_MAGIC       0x6969
   NTFS_SB_MAGIC         0x5346544e
   OPENPROM_SUPER_MAGIC  0x9fa1
   PROC_SUPER_MAGIC      0x9fa0
   QNX4_SUPER_MAGIC      0x002f
   REISERFS_SUPER_MAGIC  0x52654973
   ROMFS_MAGIC           0x7275
   SMB_SUPER_MAGIC       0x517B
   SYSV2_SUPER_MAGIC     0x012FF7B6
   SYSV4_SUPER_MAGIC     0x012FF7B5
   TMPFS_MAGIC           0x01021994
   UDF_SUPER_MAGIC       0x15013346
   UFS_MAGIC             0x00011954
   USBDEVICE_SUPER_MAGIC 0x9fa2
   VXFS_SUPER_MAGIC      0xa501FCF5
   XENIX_SUPER_MAGIC     0x012FF7B4
   XFS_SUPER_MAGIC       0x58465342
   _XIAFS_SUPER_MAGIC    0x012FD16D

Nobody knows what f_fsid is supposed to contain (but see below).

Fields that are undefined for a particular file system are set to 0. fstatfs() returns the same information about an open file referenced by descriptor fd.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
(statfs()) Search permission is denied for a component of the path prefix of path. (See also path_resolution(7).)
EBADF
(fstatfs()) fd is not a valid open file descriptor.
EFAULT
buf or path points to an invalid address.
EINTR
This call was interrupted by a signal.
EIO
An I/O error occurred while reading from the file system.
ELOOP
(statfs()) Too many symbolic links were encountered in translating path.
ENAMETOOLONG
(statfs()) path is too long.
ENOENT
(statfs()) The file referred to by path does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOSYS
The file system does not support this call.
ENOTDIR
(statfs()) A component of the path prefix of path is not a directory.
EOVERFLOW
Some values were too large to be represented in the returned struct.

CONFORMING TO

Linux specific. The Linux statfs() was inspired by the 4.4BSD one (but they do not use the same structure).

NOTES

The kernel has system calls statfs(), fstatfs(), statfs64(), and fstatfs64() to support this library call.

Some systems only have <sys/vfs.h>, other systems also have <sys/statfs.h>, where the former includes the latter. So it seems including the former is the best choice.

LSB has deprecated the library calls statfs() and fstatfs() and tells us to use statvfs(2) and fstatvfs(2) instead.

The f_fsid field

Solaris, Irix and POSIX have a system call statvfs(2) that returns a struct statvfs (defined in <sys/statvfs.h>) containing an unsigned long f_fsid. Linux, SunOS, HP-UX, 4.4BSD have a system call statfs() that returns a struct statfs (defined in <sys/vfs.h>) containing a fsid_t f_fsid, where fsid_t is defined as struct { int val[2]; }. The same holds for FreeBSD, except that it uses the include file <sys/mount.h>.

The general idea is that f_fsid contains some random stuff such that the pair (f_fsid,ino) uniquely determines a file. Some OSes use (a variation on) the device number, or the device number combined with the filesystem type. Several OSes restrict giving out the f_fsid field to the superuser only (and zero it for unprivileged users), because this field is used in the filehandle of the filesystem when NFS-exported, and giving it out is a security concern.

Under some OSes the fsid can be used as second parameter to the sysfs() system call.

SEE ALSO

stat(2), statvfs(2), path_resolution(7)


truncate(2)

TRUNCATE

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

truncate, ftruncate - truncate a file to a specified length

SYNOPSIS

#include <unistd.h>
#include <sys/types.h>

int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);

DESCRIPTION

The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').

The file offset is not changed.

If the size changed, then the st_ctime and st_mtime fields (respectively, time of last status change and time of last modification; see stat(2)) for the file are updated, and the set-user-ID and set-group-ID permission bits may be cleared.

With ftruncate(), the file must be open for writing; with truncate(), the file must be writable.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

For truncate():
EACCES
Search permission is denied for a component of the path prefix, or the named file is not writable by the user. (See also path_resolution(7).)
EFAULT
Path points outside the process's allocated address space.
EFBIG
The argument length is larger than the maximum file size. (XSI)
EINTR
A signal was caught during execution.
EINVAL
The argument length is negative or larger than the maximum file size.
EIO
An I/O error occurred updating the inode.
EISDIR
The named file is a directory.
ELOOP
Too many symbolic links were encountered in translating the pathname.
ENAMETOOLONG
A component of a pathname exceeded 255 characters, or an entire pathname exceeded 1023 characters.
ENOENT
The named file does not exist.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The underlying file system does not support extending a file beyond its current size.
EROFS
The named file resides on a read-only file system.
ETXTBSY
The file is a pure procedure (shared text) file that is being executed.

For ftruncate() the same errors apply, but instead of things that can be wrong with path, we now have things that can be wrong with fd:

EBADF
The fd is not a valid descriptor.
EBADF or EINVAL
The fd is not open for writing.
EINVAL
The fd does not reference a regular file.

CONFORMING TO

4.4BSD, SVr4, POSIX.1-2001 (these calls first appeared in 4.2BSD).

NOTES

The above description is for XSI-compliant systems. For non-XSI-compliant systems, the POSIX standard allows two behaviors for ftruncate() when length exceeds the file length (note that truncate() is not specified at all in such an environment): either returning an error, or extending the file. Like most Unix implementations, Linux follows the XSI requirement when dealing with native file systems. However, some non-native file systems do not permit truncate() and ftruncate() to be used to extend a file beyond its current length: a notable example on Linux is VFAT.

SEE ALSO

open(2), stat(2), path_resolution(7)


wait(2)

WAIT

Section: Linux Programmer's Manual (2)
Updated: 2004-11-11 Return to Main Contents

NAME

wait, waitpid, waitid - wait for process to change state

SYNOPSIS

#include <sys/types.h>
#include <sys/wait.h>

pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);

DESCRIPTION

All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal. In the case of a terminated child, performing a wait allows the system to release the resources associated with the child; if a wait is not performed, then terminated the child remains in a "zombie" state (see NOTES below).

If a child has already changed state, then these calls return immediately. Otherwise they block until either a child changes state or a signal handler interrupts the call (assuming that system calls are not automatically restarted using the SA_RESTART flag of sigaction(2)). In the remainder of this page, a child whose state has changed and which has not yet been waited upon by one of these system calls is termed waitable.

wait() and waitpid()

The wait() system call suspends execution of the current process until one of its children terminates. The call wait(&status) is equivalent to:

    waitpid(-1, &status, 0);

The waitpid() system call suspends execution of the current process until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument, as described below.

The value of pid can be:

< -1
meaning wait for any child process whose process group ID is equal to the absolute value of pid.
-1
meaning wait for any child process.
0
meaning wait for any child process whose process group ID is equal to that of the calling process.
> 0
meaning wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

WNOHANG
return immediately if no child has exited.
WUNTRACED
also return if a child has stopped (but not traced via ptrace(2)). Status for traced children which have stopped is provided even if this option is not specified.
WCONTINUED
(Since Linux 2.6.10) also return if a stopped child has been resumed by delivery of SIGCONT.

(For Linux-only options, see below.)

The WUNTRACED and WCONTINUED options are only effective if the SA_NOCLDSTOP flag has not been set for the SIGCHLD signal (see sigaction(2)).

If status is not NULL, wait() and waitpid() store status information in the int to which it points. This integer can be inspected with the following macros (which take the integer itself as an argument, not a pointer to it, as is done in wait() and waitpid()!):

WIFEXITED(status)
returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should only be employed if WIFEXITED returned true.
WIFSIGNALED(status)
returns true if the child process was terminated by a signal.
WTERMSIG(status)
returns the number of the signal that caused the child process to terminate. This macro should only be employed if WIFSIGNALED returned true.
WCOREDUMP(status)
returns true if the child produced a core dump. This macro should only be employed if WIFSIGNALED returned true. This macro is not specified in POSIX.1-2001 and is not available on some Unix implementations (e.g., AIX, SunOS). Only use this enclosed in #ifdef WCOREDUMP ... #endif.
WIFSTOPPED(status)
returns true if the child process was stopped by delivery of a signal; this is only possible if the call was done using WUNTRACED or when the child is being traced (see ptrace(2)).
WSTOPSIG(status)
returns the number of the signal which caused the child to stop. This macro should only be employed if WIFSTOPPED returned true.
WIFCONTINUED(status)
(Since Linux 2.6.10) returns true if the child process was resumed by delivery of SIGCONT.

waitid()

The waitid() system call (available since Linux 2.6.9) provides more precise control over which child state changes to wait for.

The idtype and id arguments select the child(ren) to wait for, as follows:

idtype == P_PID
Wait for the child whose process ID matches id.
idtype == P_PGID
Wait for any child whose process group ID matches id.
idtype == P_ALL
Wait for any child; id is ignored.

The child state changes to wait for are specified by ORing one or more of the following flags in options:

WEXITED
Wait for children that have terminated.
WSTOPPED
Wait for children that have been stopped by delivery of a signal.
WCONTINUED
Wait for (previously stopped) children that have been resumed by delivery of SIGCONT.

The following flags may additionally be ORed in options:

WNOHANG
As for waitpid().
WNOWAIT
Leave the child in a waitable state; a later wait call can be used to again retrieve the child status information.

Upon successful return, waitid() fills in the following fields of the siginfo_t structure pointed to by infop:

si_pid
The process ID of the child.
si_uid
The real user ID of the child. (This field is not set on most other implementations.)
si_signo
Always set to SIGCHLD.
si_status
Either the exit status of the child, as given to _exit(2) (or exit(3)), or the signal that caused the child to terminate, stop, or continue. The si_code field can be used to determine how to interpret this field.
si_code
Set to one of: CLD_EXITED (child called _exit(2)); CLD_KILLED (child killed by signal); CLD_STOPPED (child stopped by signal); or CLD_CONTINUED (child continued by SIGCONT).

If WNOHANG was specified in options and there were no children in a waitable state, then waitid() returns 0 immediately and the state of the siginfo_t structure pointed to by infop is unspecified. To distinguish this case from that where a child was in a waitable state, zero out the si_pid field before the call and check for a non-zero value in this field after the call returns.

RETURN VALUE

wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.

waitpid(): on success, returns the process ID of the child whose state has changed; on error, -1 is returned; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned.

waitid(): returns 0 on success or if WNOHANG was specified and no child(ren) specified by id has yet changed state; on error, -1 is returned.

Each of these calls sets errno to an appropriate value in the case of an error.

ERRORS

ECHILD
(for wait()) The calling process does not have any unwaited-for children.
ECHILD
(for waitpid() or waitid()) The process specified by pid (waitpid()) or idtype and id (waitid()) does not exist or is not a child of the calling process. (This can happen for one's own child if the action for SIGCHLD is set to SIG_IGN. See also the Linux Notes section about threads.)
EINTR
WNOHANG was not set and an unblocked signal or a SIGCHLD was caught.
EINVAL
The options argument was invalid.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

A child that terminates, but has not been waited for becomes a "zombie". The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait to obtain information about the child. As long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table, and if this table fills, it will not be possible to create further processes. If a parent process terminates, then its "zombie" children (if any) are adopted by init(8), which automatically performs a wait to remove the zombies.

POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN or the SA_NOCLDWAIT flag is set for SIGCHLD (see sigaction(2)), then children that terminate do not become zombies and a call to wait() or waitpid() will block until all children have terminated, and then fail with errno set to ECHILD. (The original POSIX standard left the behavior of setting SIGCHLD to SIG_IGN unspecified.) Linux 2.6 conforms to this specification. However, Linux 2.4 (and earlier) does not: if a wait() or waitpid() call is made while SIGCHLD is being ignored, the call behaves just as though SIGCHLD were not being ignored, that is, the call blocks until the next child terminates and then returns the process ID and status of that child.

Linux Notes

In the Linux kernel, a kernel-scheduled thread is not a distinct construct from a process. Instead, a thread is simply a process that is created using the Linux-unique clone(2) system call; other routines such as the portable pthread_create(3) call are implemented using clone(2). Before Linux 2.4, a thread was just a special case of a process, and as a consequence one thread could not wait on the children of another thread, even when the latter belongs to the same thread group. However, POSIX prescribes such functionality, and since Linux 2.4 a thread can, and by default will, wait on children of other threads in the same thread group.

The following Linux specific options are for use with children created using clone(2); they cannot be used with waitid():

__WCLONE
Wait for "clone" children only. If omitted then wait for "non-clone" children only. (A "clone" child is one which delivers no signal, or a signal other than SIGCHLD to its parent upon termination.) This option is ignored if __WALL is also specified.
__WALL
(Since Linux 2.4) Wait for all children, regardless of type ("clone" or "non-clone").
__WNOTHREAD
(Since Linux 2.4) Do not wait for children of other threads in the same thread group. This was the default before Linux 2.4.

EXAMPLE

The following program demonstrates the use of fork(2) and waitpid(2). The program creates a child process. If no command-line argument is supplied to the program, then the child suspends its execution using pause(2), to allow the user to send signals to the child. Otherwise, if a command-line argument is supplied, then the child exits immediately, using the integer supplied on the command line as the exit status. The parent process executes a loop that monitors the child using waitpid(2), and uses the W*() macros described above to analyze the wait status value.

The following shell session demonstrates the use of the program:

$ ./a.out &
Child PID is 32360
[1] 32359
$ kill -STOP 32360
stopped by signal 19
$ kill -CONT 32360
continued
$ kill -TERM 32360
killed by signal 15
[1]+  Done                    ./a.out
$

#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
    pid_t cpid, w;
    int status;

    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (cpid == 0) {            /* Code executed by child */
        printf("Child PID is %ld\n", (long) getpid());
        if (argc == 1)
            pause();                    /* Wait for signals */
        _exit(atoi(argv[1]));

    } else {                    /* Code executed by parent */
        do {
            w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
            if (w == -1) {
                perror("waitpid");
                exit(EXIT_FAILURE);
            }

            if (WIFEXITED(status)) {
                printf("exited, status=%d\n", WEXITSTATUS(status));
            } else if (WIFSIGNALED(status)) {
                printf("killed by signal %d\n", WTERMSIG(status));
            } else if (WIFSTOPPED(status)) {
                printf("stopped by signal %d\n", WSTOPSIG(status));
            } else if (WIFCONTINUED(status)) {
                printf("continued\n");
            }
        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        exit(EXIT_SUCCESS);
    }
}

SEE ALSO

_exit(2), clone(2), fork(2), kill(2), ptrace(2), sigaction(2), signal(2), wait4(2), pthread_create(3), credentials(7), signal(7)


vhangup(2)

VHANGUP

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

vhangup - virtually hangup the current tty

SYNOPSIS

#include <unistd.h>

int vhangup(void);

DESCRIPTION

vhangup() simulates a hangup on the current terminal. This call arranges for other users to have a ``clean'' tty at login time.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EPERM
The calling process has insufficient privilege to call vhangup(); the CAP_SYS_TTY_CONFIG capability is required.

CONFORMING TO

This call is Linux specific, and should not be used in programs intended to be portable.

SEE ALSO

capabilities(7), init(8)


getgroups(2)

GETGROUPS

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

getgroups, setgroups - get/set list of supplementary group IDs

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int getgroups(int size, gid_t list[]);

#include <grp.h>

int setgroups(size_t size, const gid_t *list);

DESCRIPTION

getgroups()
Up to size supplementary group IDs (of the calling process) are returned in list. It is unspecified whether the effective group ID of the calling process is included in the returned list. (Thus, an application should also call getegid(2) and add or remove the resulting value.) If size is zero, list is not modified, but the total number of supplementary group IDs for the process is returned.
setgroups()
Sets the supplementary group IDs for the process. Appropriate privileges (Linux: the CAP_SETGID capability) are required.

RETURN VALUE

getgroups()
On success, the number of supplementary group IDs is returned. On error, -1 is returned, and errno is set appropriately.
setgroups()
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
list has an invalid address.
EINVAL
For setgroups(), size is greater than NGROUPS (32 for Linux 2.0.32). For getgroups(), size is less than the number of supplementary group IDs, but is not zero.
EPERM
The calling process has insufficient privilege to call setgroups().

CONFORMING TO

SVr4, 4.3BSD. The getgroups() function is in POSIX.1-2001. Since setgroups() requires privilege, it is not covered by POSIX.1-2001.

NOTES

A process can have up to at least NGROUPS_MAX supplementary group IDs in addition to the effective group ID. The set of supplementary group IDs is inherited from the parent process and may be changed using setgroups(). The maximum number of supplementary group IDs can be found using sysconf(3):

    long ngroups_max;
    ngroups_max = sysconf(_SC_NGROUPS_MAX);
The maximal return value of getgroups() cannot be larger than one more than the value obtained this way.

The prototype for setgroups() is only available if _BSD_SOURCE is defined.

SEE ALSO

getgid(2), setgid(2), initgroups(3), capabilities(7)


gethostname(2)

GETHOSTNAME

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

gethostname, sethostname - get/set host name

SYNOPSIS

#include <unistd.h>

int gethostname(char *name, size_t len);
int sethostname(const char *name, size_t len);

DESCRIPTION

These system calls are used to access or to change the host name of the current processor. The gethostname() system call returns a null-terminated hostname (set earlier by sethostname()) in the array name that has a length of len bytes. In case the null-terminated hostname does not fit, no error is returned, but the hostname is truncated. It is unspecified whether the truncated hostname will be null-terminated.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
name is an invalid address.
EINVAL
len is negative or, for sethostname(), len is larger than the maximum allowed size, or, for gethostname() on Linux/i386, len is smaller than the actual size. (In this last case glibc 2.1 uses ENAMETOOLONG.)
EPERM
For sethostname(), the caller did not have the CAP_SYS_ADMIN capability.

CONFORMING TO

SVr4, 4.4BSD (these interfaces first appeared in 4.2BSD). POSIX.1-2001 specifies gethostname() but not sethostname().

NOTES

SUSv2 guarantees that `Host names are limited to 255 bytes'. POSIX.1-2001 guarantees that `Host names (not including the terminating null byte) are limited to HOST_NAME_MAX bytes'.

Glibc Notes

The GNU C library implements gethostname() as a library function that calls uname(2) and copies up to len bytes from the returned nodename field into name. Having performed the copy, the function then checks if the length of the nodename was greater than or equal to len, and if it is, then the function returns -1 with errno set to ENAMETOOLONG. Versions of glibc before 2.2 handle the case where the length of the nodename was greater than or equal to len differently: nothing is copied into name and the function returns -1 with errno set to ENAMETOOLONG.

SEE ALSO

getdomainname(2), setdomainname(2), uname(2)


setfsuid(2)

SETFSUID

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

setfsuid - set user identity used for file system checks

SYNOPSIS

#include <unistd.h> /* glibc uses <sys/fsuid.h> */

int setfsuid(uid_t fsuid);

DESCRIPTION

The system call setfsuid() sets the user ID that the Linux kernel uses to check for all accesses to the file system. Normally, the value of fsuid will shadow the value of the effective user ID. In fact, whenever the effective user ID is changed, fsuid will also be changed to the new value of the effective user ID.

Explicit calls to setfsuid() and setfsgid(2) are usually only used by programs such as the Linux NFS server that need to change what user and group ID is used for file access without a corresponding change in the real and effective user and group IDs. A change in the normal user IDs for a program such as the NFS server is a security hole that can expose it to unwanted signals. (But see below.)

setfsuid() will only succeed if the caller is the superuser or if fsuid matches either the real user ID, effective user ID, saved set-user-ID, or the current value of fsuid.

RETURN VALUE

On success, the previous value of fsuid is returned. On error, the current value of fsuid is returned.

CONFORMING TO

setfsuid() is Linux specific and should not be used in programs intended to be portable. It is present since Linux 1.1.44 and in libc since libc 4.7.6.

NOTES

When glibc determines that the argument is not a valid user ID, it will return -1 and set errno to EINVAL without attempting the system call.

Note that at the time this system call was introduced, a process could send a signal to a process with the same effective user ID. Today signal permission handling is slightly different.

BUGS

No error messages of any kind are returned to the caller. At the very least, EPERM should be returned when the call fails (because the caller lacks the CAP_SETUID capability).

SEE ALSO

kill(2), setfsgid(2), capabilities(7), credentials(7)


setgid(2)

SETGID

Section: Linux Programmer's Manual (2)
Updated: 2002-03-09 Return to Main Contents

NAME

setgid - set group identity

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int setgid(gid_t gid);

DESCRIPTION

setgid() sets the effective group ID of the current process. If the caller is the superuser, the real GID and saved set-group-ID are also set.

Under Linux, setgid() is implemented like the POSIX version with the _POSIX_SAVED_IDS feature. This allows a set-group-ID program that is not set-user-ID-root to drop all of its group privileges, do some un-privileged work, and then re-engage the original effective group ID in a secure manner.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EPERM
The calling process is not privileged (does not have the CAP_SETGID capability), and gid does not match the effective group ID or saved set-group-ID of the calling process.

CONFORMING TO

SVr4, POSIX.1-2001.

SEE ALSO

getgid(2), setegid(2), setregid(2), capabilities(7), credentials(7)


unimplemented(2)

UNIMPLEMENTED

Section: Linux Programmer's Manual (2)
Updated: 2003-02-28 Return to Main Contents

NAME

afs_syscall, break, ftime, getpmsg, gtty, lock, mpx, prof, profil, putpmsg, security, stty, ulimit - unimplemented system calls

SYNOPSIS

Unimplemented system calls.

DESCRIPTION

These system calls are not implemented in the Linux 2.4 kernel.

RETURN VALUE

These system calls always return -1 and set errno to ENOSYS.

NOTES

Note that ftime(3), profil(3) and ulimit(3) are implemented as library functions.

Some system calls, like
alloc_hugepages(2),

free_hugepages(2),

ioperm(2),

iopl(2),

and
vm86(2)

only exist on certain architectures.

Some system calls, like ipc(2), create_module(2), init_module(2), and delete_module(2) only exist when the Linux kernel was built with support for them.

SEE ALSO

obsolete(2)


readdir(2)

READDIR

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

readdir - read directory entry

SYNOPSIS

#include <linux/types.h>
#include <linux/dirent.h>

int readdir(unsigned int fd, struct dirent *dirp,
            unsigned int count);

DESCRIPTION

This is not the function you are interested in. Look at readdir(3) for the POSIX conforming C library interface. This page documents the bare kernel system call interface, which can change, and which is superseded by getdents(2).

readdir() reads one dirent structure from the directory pointed at by fd into the memory area pointed to by dirp. The parameter count is ignored; at most one dirent structure is read.

The dirent structure is declared as follows:

struct dirent
{
    long d_ino;                 /* inode number */
    off_t d_off;                /* offset to this dirent */
    unsigned short d_reclen;    /* length of this d_name */
    char d_name [NAME_MAX+1];   /* filename (null-terminated) */
}

d_ino is an inode number. d_off is the distance from the start of the directory to this dirent. d_reclen is the size of d_name, not counting the null terminator. d_name is a null-terminated filename.

RETURN VALUE

On success, 1 is returned. On end of directory, 0 is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
Invalid file descriptor fd.
EFAULT
Argument points outside the calling process's address space.
EINVAL
Result buffer is too small.
ENOENT
No such directory.
ENOTDIR
File descriptor does not refer to a directory.

CONFORMING TO

This system call is Linux specific.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

SEE ALSO

getdents(2), readdir(3)


readv(2)

READV

Section: Linux Programmer's Manual (2)
Updated: 2002-10-17 Return to Main Contents

NAME

readv, writev - read or write data into multiple buffers

SYNOPSIS

#include <sys/uio.h>

ssize_t readv(int fd, const struct iovec *iov, int iovcnt);

ssize_t writev(int fd, const struct iovec *iov, int iovcnt);

DESCRIPTION

The readv() function reads iovcnt buffers from the file associated with the file descriptor fd into the buffers described by iov ("scatter input").

The writev() function writes iovcnt buffers of data described by iov to the file associated with the file descriptor fd ("gather output").

The pointer iov points to an array of iovec structures, defined in <sys/uio.h> as:

struct iovec {
    void  *iov_base;    /* Starting address */
    size_t iov_len;     /* Number of bytes to transfer */
};

The readv() function works just like read(2) except that multiple buffers are filled.

The writev() function works just like write(2) except that multiple buffers are written out.

Buffers are processed in array order. This means that readv() completely fills iov[0] before proceeding to iov[1], and so on. (If there is insufficient data, then not all buffers pointed to by iov may be filled.) Similarly, writev() writes out the entire contents of iov[0] before proceeding to iov[1], and so on.

The data transfers performed by readv() and writev() are atomic: the data written by writev() is written as a single block that is not intermingled with output from writes in other processes (but see pipe(7) for an exception); analogously, readv() is guaranteed to read a contiguous block of data from the file, regardless of read operations performed in other threads or processes that have file descriptors referring to the same open file description (see open(2)).

RETURN VALUE

On success, the readv() function returns the number of bytes read; the writev() function returns the number of bytes written. On error, -1 is returned, and errno is set appropriately.

ERRORS

The errors are as given for read(2) and write(2). Additionally the following error is defined:
EINVAL
The sum of the iov_len values overflows an ssize_t value. Or, the vector count iovcnt is less than zero or greater than the permitted maximum.

CONFORMING TO

4.4BSD (the readv() and writev() functions first appeared in 4.2BSD), POSIX.1-2001. Linux libc5 used size_t as the type of the iovcnt parameter, and int as return type for these functions.

NOTES

Linux Notes

POSIX.1-2001 allows an implementation to place a limit on the number of items that can be passed in iov. An implementation can advertise its limit by defining IOV_MAX in <limits.h> or at run time via the return value from sysconf(_SC_IOV_MAX). On Linux, the limit advertised by these mechanisms is 1024, which is the true kernel limit. However, the glibc wrapper functions do some extra work if they detect that the underlying kernel system call failed because this limit was exceeded. In the case of readv() the wrapper function allocates a temporary buffer large enough for all of the items specified by iov, passes that buffer in a call to read(2), copies data from the buffer to the locations specified by the iov_base fields of the elements of iov, and then frees the buffer. The wrapper function for writev() performs the analogous task using a temporary buffer and a call to write(2).

BUGS

It is not advisable to mix calls to functions like readv() or writev(), which operate on file descriptors, with the functions from the stdio library; the results will be undefined and probably not what you want.

EXAMPLE

The following code sample demonstrates the use of writev():

char *str0 = "hello ";
char *str1 = "world\n";
struct iovec iov[2];
ssize_t nwritten;

iov[0].iov_base = str0;
iov[0].iov_len = strlen(str0);
iov[1].iov_base = str1;
iov[1].iov_len = strlen(str1);

nwritten = writev(STDOUT_FILENO, iov, 2);

SEE ALSO

read(2), write(2)


siggetmask (2)

 Continue to this page.


sigpause(2)

SIGPAUSE

Section: Linux Programmer's Manual (2)
Updated: 2004-05-10 Return to Main Contents

NAME

sigpause - atomically release blocked signals and wait for interrupt

SYNOPSIS

#include <signal.h>

int sigpause(int sigmask);  /* BSD */

int sigpause(int sig);      /* Unix95 */

DESCRIPTION

Don't use this function. Use sigsuspend(2) instead.

The function sigpause is designed to wait for some signal. It changes the process' signal mask (set of blocked signals), and then waits for a signal to arrive. Upon arrival of a signal, the original signal mask is restored.

RETURN VALUE

If sigpause returns, it was interrupted by a signal and the return value is -1 with errno set to EINTR.

HISTORY

The classical BSD version of this function appeared in 4.2BSD. It sets the process' signal mask to sigmask. When the number of signals was increased above 32, this version was replaced by the incompatible Unix95 one, which removes only the specified signal sig from the process' signal mask. The unfortunate situation with two incompatible functions with the same name was solved by the sigsuspend(2) function, that takes a sigset_t * parameter (instead of an int).

On Linux, this routine is a system call only on the Sparc (sparc64) architecture. Libc4 and libc5 only know about the BSD version. Glibc uses the BSD version unless _XOPEN_SOURCE is defined.

SEE ALSO

kill(2), sigaction(2), sigblock(2), sigprocmask(2), sigsuspend(2), sigvec(2)


getpgid (2)

 Continue to this page.


sched_getscheduler (2)

 Continue to this page.


intro(2)

INTRO

Section: Linux Programmer's Manual (2)
Updated: 1996-05-22 Return to Main Contents

NAME

intro, _syscall - Introduction to system calls

DESCRIPTION

This chapter describes the Linux system calls. For a list of the 164 syscalls present in Linux 2.0, see syscalls(2).

Calling Directly

In most cases, it is unnecessary to invoke a system call directly, but there are times when the Standard C library does not implement a nice function call for you. In this case, the programmer must manually invoke the system call using either one of the _syscall macros, or syscall(). The latter technique is described in syscall(2). This page describes the _syscall macros, and includes some notes on when to use one or other mechanism.

Synopsis

#include <linux/unistd.h>

A _syscall macro

desired system call

Setup

The important thing to know about a system call is its prototype. You need to know how many arguments, their types, and the function return type. There are six macros that make the actual call into the system easier. They have the form:

_syscallX(type,name,type1,arg1,type2,arg2,...)
where X is 0-5, which are the number of arguments taken by the system call
type is the return type of the system call
name is the name of the system call
typeN is the Nth argument's type
argN is the name of the Nth argument

These macros create a function called name with the arguments you specify. Once you include the _syscall() in your source file, you call the system call by name.

FILES

/usr/include/linux/unistd.h

CONFORMING TO

Certain codes are used to indicate Unix variants and standards to which calls in the section conform. See standards(7).

NOTES

The _syscall() macros DO NOT produce a prototype. You may have to create one, especially for C++ users.

System calls are not required to return only positive or negative error codes. You need to read the source to be sure how it will return errors. Usually, it is the negative of a standard error code, for example, -EPERM. The _syscall() macros will return the result r of the system call when r is non-negative, but will return -1 and set the variable errno to -r when r is negative. For the error codes, see errno(3).

Some system calls, such as mmap(2), require more than five arguments. These are handled by pushing the arguments on the stack and passing a pointer to the block of arguments.

When defining a system call, the argument types MUST be passed by-value or by-pointer (for aggregates like structs).

The preferred way to invoke system calls that glibc does not know about yet is via syscall(2). However, this mechanism can only be used if using a libc (such as glibc) that supports syscall(2), and if the <sys/syscall.h> header file contains the required SYS_foo definition. Otherwise, the use of a _syscall macro is required.

Some architectures, notably ia64, do not provide the _syscall macros. On these architectures, syscall(2) must be used.

EXAMPLE

#include <stdio.h>
#include <errno.h>
#include <linux/unistd.h>       /* for _syscallX macros/related stuff */
#include <linux/kernel.h>       /* for struct sysinfo */

_syscall1(int, sysinfo, struct sysinfo *, info);

/* Note: if you copy directly from the nroff source, remember to
REMOVE the extra backslashes in the printf statement. */

int
main(void)
{
    struct sysinfo s_info;
    int error;

    error = sysinfo(&s_info);
    printf("code error = %d\n", error);
    printf("Uptime = %lds\nLoad: 1 min %lu / 5 min %lu / 15 min %lu\n"
           "RAM: total %lu / free %lu / shared %lu\n"
           "Memory in buffers = %lu\nSwap: total %lu / free %lu\n"
           "Number of processes = %d\n",
           s_info.uptime, s_info.loads[0],
           s_info.loads[1], s_info.loads[2],
           s_info.totalram, s_info.freeram,
           s_info.sharedram, s_info.bufferram,
           s_info.totalswap, s_info.freeswap,
           s_info.procs);
    exit(EXIT_SUCCESS);
}

Sample Output

code error = 0
uptime = 502034s
Load: 1 min 13376 / 5 min 5504 / 15 min 1152
RAM: total 15343616 / free 827392 / shared 8237056
Memory in buffers = 5066752
Swap: total 27881472 / free 24698880
Number of processes = 40

SEE ALSO

syscall(2), errno(3), feature_test_macros(7), standards(7)


seteuid(2)

SETEGID

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

seteuid, setegid - set effective user or group ID

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int seteuid(uid_t euid);
int setegid(gid_t egid);

DESCRIPTION

seteuid() sets the effective user ID of the current process. Unprivileged user processes may only set the effective user ID to the real user ID, the effective user ID or the saved set-user-ID.

Precisely the same holds for setegid() with "group" instead of "user".

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EPERM
The current process is not privileged (Linux: does not have the CAP_SETUID capability in the case of seteuid(), or the CAP_SETGID capability in the case of setegid()) and euid (resp. egid) is not the real user (group) ID, the effective user (group) ID, or the saved set-user-ID (saved set-group-ID).

CONFORMING TO

4.3BSD, POSIX.1-2001.

NOTES

Setting the effective user (group) ID to the saved set-user-ID (saved set-group-ID) is possible since Linux 1.1.37 (1.1.38). On an arbitrary system one should check _POSIX_SAVED_IDS.

Under libc4, libc5 and glibc 2.0 seteuid(euid) is equivalent to setreuid(-1, euid) and hence may change the saved set-user-ID. Under glibc2.1 it is equivalent to setresuid(-1, euid,-1) and hence does not change the saved set-user-ID. Similar remarks hold for setegid().

SEE ALSO

geteuid(2), setresuid(2), setreuid(2), setuid(2), capabilities(7), credentials(7)


setfsgid(2)

SETFSGID

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

setfsgid - set group identity used for file system checks

SYNOPSIS

#include <unistd.h> /* glibc uses <sys/fsuid.h> */

int setfsgid(uid_t fsgid);

DESCRIPTION

The system call setfsgid() sets the group ID that the Linux kernel uses to check for all accesses to the file system. Normally, the value of fsgid will shadow the value of the effective group ID. In fact, whenever the effective group ID is changed, fsgid will also be changed to the new value of the effective group ID.

Explicit calls to setfsuid(2) and setfsgid() are usually only used by programs such as the Linux NFS server that need to change what user and group ID is used for file access without a corresponding change in the real and effective user and group IDs. A change in the normal user IDs for a program such as the NFS server is a security hole that can expose it to unwanted signals. (But see below.)

setfsgid() will only succeed if the caller is the superuser or if fsgid matches either the real group ID, effective group ID, saved set-group-ID, or the current value of fsgid.

RETURN VALUE

On success, the previous value of fsgid is returned. On error, the current value of fsgid is returned.

CONFORMING TO

setfsgid() is Linux specific and should not be used in programs intended to be portable. It is present since Linux 1.1.44 and in libc since libc 4.7.6.

NOTES

When glibc determines that the argument is not a valid group ID, it will return -1 and set errno to EINVAL without attempting the system call.

Note that at the time this system call was introduced, a process could send a signal to a process with the same effective user ID. Today signal permission handling is slightly different.

BUGS

No error messages of any kind are returned to the caller. At the very least, EPERM should be returned when the call fails (because the caller lacks the CAP_SETGID capability).

SEE ALSO

kill(2), setfsuid(2), capabilities(7), credentials(7)


sigmask (2)

 Continue to this page.


modify_ldt(2)

MODIFY_LDT

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

modify_ldt - get or set ldt

SYNOPSIS

#include <sys/types.h>

int modify_ldt(int func, void *ptr, unsigned long bytecount);

DESCRIPTION

modify_ldt() reads or writes the local descriptor table (ldt) for a process. The ldt is a per-process memory management table used by the i386 processor. For more information on this table, see an Intel 386 processor handbook.

When func is 0, modify_ldt() reads the ldt into the memory pointed to by ptr. The number of bytes read is the smaller of bytecount and the actual size of the ldt.

When func is 1, modify_ldt() modifies one ldt entry. ptr points to a user_desc structure and bytecount must equal the size of this structure.

The user_desc structure is defined in <asm/ldt.h> as:

struct user_desc {
    unsigned int  entry_number;
    unsigned long base_addr;
    unsigned int  limit;
    unsigned int  seg_32bit:1;
    unsigned int  contents:2;
    unsigned int  read_exec_only:1;
    unsigned int  limit_in_pages:1;
    unsigned int  seg_not_present:1;
    unsigned int  useable:1;
};

In Linux 2.4 and earlier, this structure was named modify_ldt_ldt_s.

RETURN VALUE

On success, modify_ldt() returns either the actual number of bytes read (for reading) or 0 (for writing). On failure, modify_ldt() returns -1 and sets errno to indicate the error.

ERRORS

EFAULT
ptr points outside the address space.
EINVAL
ptr is 0, or func is 1 and bytecount is not equal to the size of the structure modify_ldt_ldt_s, or func is 1 and the new ldt entry has invalid values.
ENOSYS
func is neither 0 nor 1.

CONFORMING TO

This call is Linux specific and should not be used in programs intended to be portable.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

SEE ALSO

vm86(2)


wait4(2)

WAIT4

Section: Linux Programmer's Manual (2)
Updated: 2004-11-11 Return to Main Contents

NAME

wait3, wait4 - wait for process to change state, BSD style

SYNOPSIS

#define _BSD_SOURCE
                /* Or #define _XOPEN_SOURCE 500 for wait3() */
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>

pid_t wait3(int *status, int options,
            struct rusage *rusage);

pid_t wait4(pid_t pid, int *status, int options,
            struct rusage *rusage);

DESCRIPTION

The wait3() and wait4() system calls are similar to waitpid(2), but additionally return resource usage information about the child in the structure pointed to by rusage.

Other than the use of the rusage argument, the following wait3() call:

    wait3(status, options, rusage);
is equivalent to:

    waitpid(-1, status, options);
Similarly, the following wait4() call:

    wait4(pid, status, options, rusage);
is equivalent to:

    waitpid(pid, status, options);
In other words, wait3() waits of any child, while wait4() can be used to select a specific child, or children, on which to wait. See wait(2) for further details.

If rusage is not NULL, the struct rusage to which it points will be filled with accounting information about the child. See getrusage(2) for details.

RETURN VALUE

As for waitpid(2).

ERRORS

As for waitpid(2).

CONFORMING TO

4.3BSD

NOTES

Including <sys/time.h> is not required these days, but increases portability. (Indeed, <sys/resource.h> defines the rusage structure with fields of type struct timeval defined in <sys/time.h>.)

SEE ALSO

fork(2), getrusage(2), sigaction(2), signal(2), wait(2), feature_test_macros(7), signal(7)


sigvec(2)

SIGVEC

Section: Linux Programmer's Manual (2)
Updated: 1995-08-31 Return to Main Contents

NAME

sigvec - BSD software signal facilities

SYNOPSIS

#include <bsd/signal.h>

int sigvec(int sig, struct sigvec *vec, struct sigvec *ovec);

DESCRIPTION

This interface is made obsolete by sigaction(2).

Under Linux sigvec is #define'd to sigaction, and provides at best a rough approximation of the BSD sigvec interface.

CONFORMING TO

BSD, SVr4

SEE ALSO

sigaction(2), signal(2)


break (2)

 Continue to this page.


sigpending(2)

SIGPENDING

Section: Linux Programmer's Manual (2)
Updated: 2005-09-15 Return to Main Contents

NAME

sigpending - examine pending signals

SYNOPSIS

#include <signal.h>

int sigpending(sigset_t *set);

DESCRIPTION

sigpending() returns the set of signals that are pending for delivery to the calling thread (i.e., the signals which have been raised while blocked). The mask of pending signals is returned in set.

RETURN VALUE

sigpending() returns 0 on success and -1 on error.

ERRORS

EFAULT
set points to memory which is not a valid part of the process address space.

CONFORMING TO

POSIX.1-2001.

NOTES

See sigsetops(3) for details on manipulating signal sets.

BUGS

In versions of glibc up to and including 2.2.1, there is a bug in the wrapper function for sigpending() which means that information about pending real-time signals is not correctly returned.

SEE ALSO

kill(2), sigaction(2), signal(2), sigprocmask(2), sigsuspend(2), sigsetops(3), signal(7)


sigsuspend(2)

SIGSUSPEND

Section: Linux Programmer's Manual (2)
Updated: 2005-09-15 Return to Main Contents

NAME

sigsuspend - wait for a signal

SYNOPSIS

#include <signal.h>

int sigsuspend(const sigset_t *mask);

DESCRIPTION

sigsuspend() temporarily replaces the signal mask of the calling process with the mask given by mask and then suspends the process until delivery of a signal whose action is to invoke a signal handler or to terminate a process.

If the signal terminates the process, then sigsuspend() does not return. If the signal is caught, then sigsuspend() returns after the signal handler returns, and the signal mask is restored to the state before the call to sigsuspend().

It is not possible to block SIGKILL or SIGSTOP; specifying these signals in mask, has no effect on the process's signal mask.

RETURN VALUE

sigsuspend() always returns -1, normally with the error EINTR.

ERRORS

EFAULT
mask points to memory which is not a valid part of the process address space.
EINTR
The call was interrupted by a signal.

CONFORMING TO

POSIX.1-2001.

NOTES

Normally, sigsuspend() is used in conjunction with sigprocmask(2) in order to prevent delivery of a signal during the execution of a critical code section. The caller first blocks the signals with sigprocmask(2). When the critical code has completed, the caller then waits for the signals by calling sigsuspend() with the signal mask that was returned by sigprocmask(2) (in the oldset argument).

See sigsetops(3) for details on manipulating signal sets.

SEE ALSO

kill(2), pause(2), sigaction(2), signal(2), sigprocmask(2), sigwaitinfo(2), sigsetops(3), signal(7)


open(2)

OPEN

Section: Linux Programmer's Manual (2)
Updated: 2005-06-22 Return to Main Contents

NAME

open, creat - open and possibly create a file or device

SYNOPSIS

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);

DESCRIPTION

Given a pathname for a file, open() returns a file descriptor, a small, non-negative integer for use in subsequent system calls (read(2), write(2), lseek(2), fcntl(2), etc.). The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

The new file descriptor is set to remain open across an execve(2) (i.e., the FD_CLOEXEC file descriptor flag described in fcntl(2) is initially disabled). The file offset is set to the beginning of the file (see lseek(2)).

A call to open() creates a new open file description, an entry in the system-wide table of open files. This entry records the file offset and the file status flags (modifiable via the fcntl(2) F_SETFL operation). A file descriptor is a reference to one of these entries; this reference is unaffected if pathname is subsequently removed or modified to refer to a different file. The new open file description is initially not shared with any other process, but sharing may arise via fork(2).

The parameter flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively.

In addition, zero or more file creation flags and file status flags can be bitwise-or'd in flags. The file creation flags are O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC. The file status flags are all of the remaining flags listed below. The distinction between these two groups of flags is that the file status flags can be retrieved and (in some cases) modified using fcntl(2). The full list of file creation flags and file status flags is as follows:

O_APPEND
The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2). O_APPEND may lead to corrupted files on NFS file systems if more than one process appends data to a file at once. This is because NFS does not support appending to a file, so the client kernel has to simulate it, which can't be done without a race condition.
O_ASYNC
Enable signal-driven I/O: generate a signal (SIGIO by default, but this can be changed via fcntl(2)) when input or output becomes possible on this file descriptor. This feature is only available for terminals, pseudo-terminals, sockets, and (since Linux 2.6) pipes and FIFOs. See fcntl(2) for further details.
O_CREAT
If the file does not exist it will be created. The owner (user ID) of the file is set to the effective user ID of the process. The group ownership (group ID) is set either to the effective group ID of the process or to the group ID of the parent directory (depending on filesystem type and mount options, and the mode of the parent directory, see, for example, the mount options bsdgroups and sysvgroups of the ext2 filesystem, as described in mount(8)).
O_DIRECT
Try to minimize cache effects of the I/O to and from this file. In general this will degrade performance, but it is useful in special situations, such as when applications do their own caching. File I/O is done directly to/from user space buffers. The I/O is synchronous, that is, at the completion of a read(2) or write(2), data is guaranteed to have been transferred. Under Linux 2.4 transfer sizes, and the alignment of user buffer and file offset must all be multiples of the logical block size of the file system. Under Linux 2.6 alignment to 512-byte boundaries suffices.

A semantically similar (but deprecated) interface for block devices is described in raw(8).

O_DIRECTORY
If pathname is not a directory, cause the open to fail. This flag is Linux-specific, and was added in kernel version 2.1.126, to avoid denial-of-service problems if opendir(3) is called on a FIFO or tape device, but should not be used outside of the implementation of opendir(3).
O_EXCL
When used with O_CREAT, if the file already exists it is an error and the open() will fail. In this context, a symbolic link exists, regardless of where it points to. O_EXCL is broken on NFS file systems; programs which rely on it for performing locking tasks will contain a race condition. The solution for performing atomic file locking using a lockfile is to create a unique file on the same file system (e.g., incorporating hostname and pid), use link(2) to make a link to the lockfile. If link(2) returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful.
O_LARGEFILE
(LFS) Allow files whose sizes cannot be represented in an off_t (but can be represented in an off64_t) to be opened. The _LARGEFILE64_SOURCE macro must be defined in order to obtain this definition. Setting the _FILE_OFFSET_BITS feature test macro to 64 (rather than using O_LARGEFILE) is the preferred method of obtaining method of accessing large files on 32-bit systems (see feature_test_macros(7)).
O_NOATIME
(Since Linux 2.6.8) Do not update the file last access time (st_atime in the inode) when the file is read(2). This flag is intended for use by indexing or backup programs, where its use can significantly reduce the amount of disk activity. This flag may not be effective on all filesystems. One example is NFS, where the server maintains the access time.
O_NOCTTY
If pathname refers to a terminal device --- see tty(4) --- it will not become the process's controlling terminal even if the process does not have one.
O_NOFOLLOW
If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will still be followed.
O_NONBLOCK or O_NDELAY
When possible, the file is opened in non-blocking mode. Neither the open() nor any subsequent operations on the file descriptor which is returned will cause the calling process to wait. For the handling of FIFOs (named pipes), see also fifo(7). For a discussion of the effect of O_NONBLOCK in conjunction with mandatory file locks and with file leases, see fcntl(2).
O_SYNC
The file is opened for synchronous I/O. Any write(2)s on the resulting file descriptor will block the calling process until the data has been physically written to the underlying hardware. But see NOTES below.
O_TRUNC
If the file already exists and is a regular file and the open mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length 0. If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored. Otherwise the effect of O_TRUNC is unspecified.

Some of these optional flags can be altered using fcntl(2) after the file has been opened.

The argument mode specifies the permissions to use in case a new file is created. It is modified by the process's umask in the usual way: the permissions of the created file are (mode & ~umask). Note that this mode only applies to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor.

The following symbolic constants are provided for mode:

S_IRWXU
00700 user (file owner) has read, write and execute permission
S_IRUSR
00400 user has read permission
S_IWUSR
00200 user has write permission
S_IXUSR
00100 user has execute permission
S_IRWXG
00070 group has read, write and execute permission
S_IRGRP
00040 group has read permission
S_IWGRP
00020 group has write permission
S_IXGRP
00010 group has execute permission
S_IRWXO
00007 others have read, write and execute permission
S_IROTH
00004 others have read permission
S_IWOTH
00002 others have write permission
S_IXOTH
00001 others have execute permission

mode must be specified when O_CREAT is in the flags, and is ignored otherwise.

creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.

RETURN VALUE

open() and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).

ERRORS

EACCES
The requested access to the file is not allowed, or search permission is denied for one of the directories in the path prefix of pathname, or the file did not exist yet and write access to the parent directory is not allowed. (See also path_resolution(7).)
EEXIST
pathname already exists and O_CREAT and O_EXCL were used.
EFAULT
pathname points outside your accessible address space.
EFBIG
pathname refers to a regular file, too large to be opened; see O_LARGEFILE above. (POSIX.1-2001 specifies the error EOVERFLOW for this case.)
EISDIR
pathname refers to a directory and the access requested involved writing (that is, O_WRONLY or O_RDWR is set).
ELOOP
Too many symbolic links were encountered in resolving pathname, or O_NOFOLLOW was specified but pathname was a symbolic link.
EMFILE
The process already has the maximum number of files open.
ENAMETOOLONG
pathname was too long.
ENFILE
The system limit on the total number of open files has been reached.
ENODEV
pathname refers to a device special file and no corresponding device exists. (This is a Linux kernel bug; in this situation ENXIO must be returned.)
ENOENT
O_CREAT is not set and the named file does not exist. Or, a directory component in pathname does not exist or is a dangling symbolic link.
ENOMEM
Insufficient kernel memory was available.
ENOSPC
pathname was to be created but the device containing pathname has no room for the new file.
ENOTDIR
A component used as a directory in pathname is not, in fact, a directory, or O_DIRECTORY was specified and pathname was not a directory.
ENXIO
O_NONBLOCK | O_WRONLY is set, the named file is a FIFO and no process has the file open for reading. Or, the file is a device special file and no corresponding device exists.
EPERM
The O_NOATIME flag was specified, but the effective user ID of the caller did not match the owner of the file and the caller was not privileged (CAP_FOWNER).
EROFS
pathname refers to a file on a read-only filesystem and write access was requested.
ETXTBSY
pathname refers to an executable image which is currently being executed and write access was requested.
EWOULDBLOCK
The O_NONBLOCK flag was specified, and an incompatible lease was held on the file (see fcntl(2)).

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001. The O_NOATIME, O_NOFOLLOW, and O_DIRECTORY flags are Linux specific. One may have to define the _GNU_SOURCE macro to get their definitions.

NOTES

Under Linux, the O_NONBLOCK flag indicates that one wants to open but does not necessarily have the intention to read or write. This is typically used to open devices in order to get a file descriptor for use with ioctl(2).

The (undefined) effect of O_RDONLY | O_TRUNC varies among implementations. On many systems the file is actually truncated.

The O_DIRECT flag was introduced in SGI IRIX, where it has alignment restrictions similar to those of Linux 2.4. IRIX has also a fcntl(2) call to query appropriate alignments, and sizes. FreeBSD 4.x introduced a flag of same name, but without alignment restrictions. Support was added under Linux in kernel version 2.4.10. Older Linux kernels simply ignore this flag. One may have to define the _GNU_SOURCE macro to get its definition.

There are many infelicities in the protocol underlying NFS, affecting amongst others O_SYNC and O_NDELAY.

POSIX provides for three different variants of synchronized I/O, corresponding to the flags O_SYNC, O_DSYNC and O_RSYNC. Currently (2.1.130) these are all synonymous under Linux.

Note that open() can open device special files, but creat() cannot create them; use mknod(2) instead.

On NFS file systems with UID mapping enabled, open() may return a file descriptor but, for example, read(2) requests are denied with EACCES. This is because the client performs open() by checking the permissions, but UID mapping is performed by the server upon read and write requests.

If the file is newly created, its st_atime, st_ctime, st_mtime fields (respectively, time of last access, time of last status change, and time of last modification; see stat(2)) are set to the current time, and so are the st_ctime and st_mtime fields of the parent directory. Otherwise, if the file is modified because of the O_TRUNC flag, its st_ctime and st_mtime fields are set to the current time.

BUGS

"The thing that has always disturbed me about O_DIRECT is that the whole interface is just stupid, and was probably designed by a deranged monkey on some serious mind-controlling substances." --- Linus

Currently, it is not possible to enable signal-driven I/O by specifying O_ASYNC when calling open(); use fcntl(2) to enable this flag.

SEE ALSO

close(2), dup(2), fcntl(2), link(2), lseek(2), mknod(2), mount(2), mmap(2), openat(2), read(2), socket(2), stat(2), umask(2), unlink(2), write(2), fopen(3), fifo(7), feature_test_macros(7), path_resolution(7)


munlock (2)

 Continue to this page.


nfsservctl(2)

NFSSERVCTL

Section: Linux Programmer's Manual (2)
Updated: 1997-07-16 Return to Main Contents

NAME

nfsservctl - syscall interface to kernel nfs daemon

SYNOPSIS

#include <linux/nfsd/syscall.h>

nfsservctl(int cmd, struct nfsctl_arg *argp, union nfsctl_res *resp);

DESCRIPTION

/*
 * These are the commands understood by nfsctl().
 */
#define NFSCTL_SVC          0    /* This is a server process. */
#define NFSCTL_ADDCLIENT    1    /* Add an NFS client. */
#define NFSCTL_DELCLIENT    2    /* Remove an NFS client. */
#define NFSCTL_EXPORT       3    /* export a file system. */
#define NFSCTL_UNEXPORT     4    /* unexport a file system. */
#define NFSCTL_UGIDUPDATE   5    /* update a client's UID/GID map. */
#define NFSCTL_GETFH        6    /* get an fh (used by mountd) */

struct nfsctl_arg {
    int                       ca_version;     /* safeguard */
    union {
        struct nfsctl_svc     u_svc;
        struct nfsctl_client  u_client;
        struct nfsctl_export  u_export;
        struct nfsctl_uidmap  u_umap;
        struct nfsctl_fhparm  u_getfh;
        unsigned int          u_debug;
    } u;
}

union nfsctl_res {
        struct knfs_fh          cr_getfh;
        unsigned int            cr_debug;
};

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

CONFORMING TO

This call is Linux specific.


oldlstat (2)

 Continue to this page.


sendmsg (2)

 Continue to this page.


sendto (2)

 Continue to this page.


setegid (2)

 Continue to this page.


adjtimex(2)

ADJTIMEX

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

adjtimex - tune kernel clock

SYNOPSIS

#include <sys/timex.h>

int adjtimex(struct timex *buf);

DESCRIPTION

Linux uses David L. Mills' clock adjustment algorithm (see RFC 1305). The system call adjtimex() reads and optionally sets adjustment parameters for this algorithm. It takes a pointer to a timex structure, updates kernel parameters from field values, and returns the same structure with current kernel values. This structure is declared as follows:

struct timex {
    int modes;           /* mode selector */
    long offset;         /* time offset (usec) */
    long freq;           /* frequency offset (scaled ppm) */
    long maxerror;       /* maximum error (usec) */
    long esterror;       /* estimated error (usec) */
    int status;          /* clock command/status */
    long constant;       /* pll time constant */
    long precision;      /* clock precision (usec) (read only) */
    long tolerance;      /* clock frequency tolerance (ppm)
                            (read only) */
    struct timeval time; /* current time (read only) */
    long tick;           /* usecs between clock ticks */
};

The modes field determines which parameters, if any, to set. It may contain a bitwise-or combination of zero or more of the following bits:

#define ADJ_OFFSET            0x0001 /* time offset */
#define ADJ_FREQUENCY         0x0002 /* frequency offset */
#define ADJ_MAXERROR          0x0004 /* maximum time error */
#define ADJ_ESTERROR          0x0008 /* estimated time error */
#define ADJ_STATUS            0x0010 /* clock status */
#define ADJ_TIMECONST         0x0020 /* pll time constant */
#define ADJ_TICK              0x4000 /* tick value */
#define ADJ_OFFSET_SINGLESHOT 0x8001 /* old-fashioned adjtime() */

Ordinary users are restricted to a zero value for mode. Only the superuser may set any parameters.

RETURN VALUE

On success, adjtimex() returns the clock state:

#define TIME_OK   0 /* clock synchronized */
#define TIME_INS  1 /* insert leap second */
#define TIME_DEL  2 /* delete leap second */
#define TIME_OOP  3 /* leap second in progress */
#define TIME_WAIT 4 /* leap second has occurred */
#define TIME_BAD  5 /* clock not synchronized */

On failure, adjtimex() returns -1 and sets errno.

ERRORS

EFAULT
buf does not point to writable memory.
EINVAL
An attempt is made to set buf.offset to a value outside the range -131071 to +131071, or to set buf.status to a value other than those listed above, or to set buf.tick to a value outside the range 900000/HZ to 1100000/HZ, where HZ is the system timer interrupt frequency.
EPERM
buf.mode is non-zero and the caller does not have sufficient privilege. Under Linux the CAP_SYS_TIME capability is required.

CONFORMING TO

adjtimex() is Linux specific and should not be used in programs intended to be portable. See adjtime(3) for a more portable, but less flexible, method of adjusting the system clock.

SEE ALSO

settimeofday(2), adjtime(3), capabilities(7)


sethostname (2)

 Continue to this page.


ioctl(2)

IOCTL

Section: Linux Programmer's Manual (2)
Updated: 2000-09-21 Return to Main Contents

NAME

ioctl - control device

SYNOPSIS

#include <sys/ioctl.h>

int ioctl(int d, int request, ...);

DESCRIPTION

The ioctl() function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g., terminals) may be controlled with ioctl() requests. The argument d must be an open file descriptor.

The second argument is a device-dependent request code. The third argument is an untyped pointer to memory. It's traditionally char *argp (from the days before void * was valid C), and will be so named for this discussion.

An ioctl() request has encoded in it whether the argument is an in parameter or out parameter, and the size of the argument argp in bytes. Macros and defines used in specifying an ioctl() request are located in the file <sys/ioctl.h>.

RETURN VALUE

Usually, on success zero is returned. A few ioctl() requests use the return value as an output parameter and return a non-negative value on success. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
d is not a valid descriptor.
EFAULT
argp references an inaccessible memory area.
EINVAL
Request or argp is not valid.
ENOTTY
d is not associated with a character special device.
ENOTTY
The specified request does not apply to the kind of object that the descriptor d references.

CONFORMING TO

No single standard. Arguments, returns, and semantics of ioctl(2) vary according to the device driver in question (the call is used as a catch-all for operations that don't cleanly fit the Unix stream I/O model). See ioctl_list(2) for a list of many of the known ioctl() calls. The ioctl() function call appeared in Version 7 AT&T Unix.

NOTES

In order to use this call, one needs an open file descriptor. Often the open(2) call has unwanted side effects, that can be avoided under Linux by giving it the O_NONBLOCK flag.

SEE ALSO

execve(2), fcntl(2), ioctl_list(2), open(2), sd(4), tty(4)


munmap (2)

 Continue to this page.


nice(2)

NICE

Section: Linux Programmer's Manual (2)
Updated: 2005-09-20 Return to Main Contents

NAME

nice - change process priority

SYNOPSIS

#include <unistd.h>

int nice(int inc);

DESCRIPTION

nice() adds inc to the nice value for the calling process. (A higher nice value means a low priority.) Only the superuser may specify a negative increment, or priority increase. The range for nice values is described in getpriority(2).

RETURN VALUE

On success, the new nice value is returned (but see NOTES below). On error, -1 is returned, and errno is set appropriately.

ERRORS

EPERM
The calling process attempted to increase its priority by supplying a negative inc but has insufficient privileges. Under Linux the CAP_SYS_NICE capability is required. (But see the discussion of the RLIMIT_NICE resource limit in setrlimit(2).)

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001. However, the Linux and (g)libc (earlier than glibc 2.2.4) return value is nonstandard, see below. SVr4 documents an additional EINVAL error code.

NOTES

SUSv2 and POSIX.1-2001 specify that nice() should return the new nice value. However, the Linux syscall and the nice() library function provided in older versions of (g)libc (earlier than glibc 2.2.4) return 0 on success. The new nice value can be found using getpriority(2).

Since glibc 2.2.4, nice() is implemented as a library function that calls getpriority(2) to obtain the new nice value to be returned to the caller. With this implementation, a successful call can legitimately return -1. To reliably detect an error, set errno to 0 before the call, and check its value when nice() returns -1.

SEE ALSO

nice(1), fork(2), getpriority(2), setpriority(2), capabilities(7), renice(8)


mpx (2)

 Continue to this page.


msgctl(2)

MSGCTL

Section: Linux Programmer's Manual (2)
Updated: 2004-11-10 Return to Main Contents

NAME

msgctl - message control operations

SYNOPSIS

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int msgctl(int msqid, int cmd, struct msqid_ds *buf);

DESCRIPTION

msgctl() performs the control operation specified by cmd on the message queue with identifier msqid.

The msqid_ds data structure is defined in <sys/msg.h> as follows:

struct msqid_ds {
    struct ipc_perm msg_perm;    /* Ownership and permissions */
    time_t         msg_stime;    /* Time of last msgsnd(2) */
    time_t         msg_rtime;    /* Time of last msgrcv(2) */
    time_t         msg_ctime;    /* Time of last change */
    unsigned long  __msg_cbytes; /* Current number of bytes in
                                    queue (non-standard) */
    msgqnum_t      msg_qnum;     /* Current number of messages
                                    in queue */
    msglen_t       msg_qbytes;   /* Maximum number of bytes
                                    allowed in queue */
    pid_t          msg_lspid;    /* PID of last msgsnd(2) */
    pid_t          msg_lrpid;    /* PID of last msgrcv(2) */
};

The ipc_perm structure is defined in <sys/ipc.h> as follows (the highlighted fields are settable using IPC_SET):

struct ipc_perm {
    key_t key;            /* Key supplied to msgget(2) */
    uid_t uid;            /* Effective UID of owner */
    gid_t gid;            /* Effective GID of owner */
    uid_t cuid;           /* Effective UID of creator */
    gid_t cgid;           /* Effective GID of creator */
    unsigned short mode;  /* Permissions */
    unsigned short seq;   /* Sequence number */
};

Valid values for cmd are:

IPC_STAT
Copy information from the kernel data structure associated with msqid into the msqid_ds structure pointed to by buf. The caller must have read permission on the message queue.
IPC_SET
Write the values of some members of the msqid_ds structure pointed to by buf to the kernel data structure associated with this message queue, updating also its msg_ctime member. The following members of the structure are updated: msg_qbytes, msg_perm.uid, msg_perm.gid, and (the least significant 9 bits of) msg_perm.mode. The effective UID of the calling process must match the owner (msg_perm.uid) or creator (msg_perm.cuid) of the message queue, or the caller must be privileged. Appropriate privilege (Linux: the CAP_IPC_RESOURCE capability) is required to raise the msg_qbytes value beyond the system parameter MSGMNB.
IPC_RMID
Immediately remove the message queue, awakening all waiting reader and writer processes (with an error return and errno set to EIDRM). The calling process must have appropriate privileges or its effective user ID must be either that of the creator or owner of the message queue.
IPC_INFO (Linux specific)
Returns information about system-wide message queue limits and parameters in the structure pointed to by buf. This structure is of type msginfo (thus, a cast is required), defined in <sys/msg.h> if the _GNU_SOURCE feature test macro is defined:

struct msginfo {
    int msgpool; /* Size in bytes of buffer pool used
                    to hold message data; unused */
    int msgmap;  /* Max. # of entries in message
                    map; unused */
    int msgmax;  /* Max. # of bytes that can be
                    written in a single message */
    int msgmnb;  /* Max. # of bytes that can be written to
                    queue; used to initialize msg_qbytes
                    during queue creation (msgget(2)) */
    int msgmni;  /* Max. # of message queues */
    int msgssz;  /* Message segment size; unused */
    int msgtql;  /* Max. # of messages on all queues
                    in system; unused */
    unsigned short int msgseg;
                 /* Max. # of segments; unused */
};
The msgmni, msgmax, and msgmnb settings can be changed via /proc files of the same name; see proc(5) for details.
MSG_INFO (Linux specific)
Returns a msginfo structure containing the same information as for IPC_INFO, except that the following fields are returned with information about system resources consumed by message queues: the msgpool field returns the number of message queues that currently exist on the system; the msgmap field returns the total number of messages in all queues on the system; and the msgtql field returns the total number of bytes in all messages in all queues on the system.
MSG_STAT (Linux specific)
Returns a msqid_ds structure as for IPC_STAT. However, the msqid argument is not a queue identifier, but instead an index into the kernel's internal array that maintains information about all message queues on the system.

RETURN VALUE

On success, IPC_STAT, IPC_SET, and IPC_RMID return 0. A successful IPC_INFO or MSG_INFO operation returns the index of the highest used entry in the kernel's internal array recording information about all message queues. (This information can be used with repeated MSG_STAT operations to obtain information about all queues on the system.) A successful MSG_STAT operation returns the identifier of the queue whose index was given in msqid.

On error, -1 is returned with errno indicating the error.

ERRORS

On failure, errno is set to one of the following:
EACCES
The argument cmd is equal to IPC_STAT or MSG_STAT, but the calling process does not have read permission on the message queue msqid, and does not have the CAP_IPC_OWNER capability.
EFAULT
The argument cmd has the value IPC_SET or IPC_STAT, but the address pointed to by buf isn't accessible.
EIDRM
The message queue was removed.
EINVAL
Invalid value for cmd or msqid. Or: for a MSG_STAT operation, the index value specified in msqid referred to an array slot that is currently unused.
EPERM
The argument cmd has the value IPC_SET or IPC_RMID, but the effective user ID of the calling process is not the creator (as found in msg_perm.cuid) or the owner (as found in msg_perm.uid) of the message queue, and the process is not privileged (Linux: it does not have the CAP_SYS_ADMIN capability).

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

The IPC_INFO, MSG_STAT and MSG_INFO operations are used by the ipcs(8) program to provide information on allocated resources. In the future these may modified or moved to a /proc file system interface.

Various fields in the struct msqid_ds were shorts under Linux 2.2 and have become longs under Linux 2.4. To take advantage of this, a recompilation under glibc-2.1.91 or later should suffice. (The kernel distinguishes old and new calls by an IPC_64 flag in cmd.)

SEE ALSO

msgget(2), msgrcv(2), msgsnd(2), capabilities(7), mq_overview(7), svipc(7)


msgrcv (2)

 Continue to this page.


brk(2)

BRK

Section: Linux Programmer's Manual (2)
Updated: 2003-11-01 Return to Main Contents

NAME

brk, sbrk - change data segment size

SYNOPSIS

#include <unistd.h>

int brk(void *end_data_segment);

void *sbrk(intptr_t increment);

DESCRIPTION

brk() sets the end of the data segment to the value specified by end_data_segment, when that value is reasonable, the system does have enough memory and the process does not exceed its max data size (see setrlimit(2)).

sbrk() increments the program's data space by increment bytes. sbrk() isn't a system call, it is just a C library wrapper. Calling sbrk() with an increment of 0 can be used to find the current location of the program break.

RETURN VALUE

On success, brk() returns zero. On error, -1 is returned, and errno is set to ENOMEM. (But see Linux Notes below.)

On success, sbrk() returns a pointer to the start of the new area. On error, -1 is returned, and errno is set to ENOMEM.

CONFORMING TO

4.3BSD; SUSv1, marked LEGACY in SUSv2, removed in POSIX.1-2001.

brk() and sbrk() are not defined in the C Standard and are deliberately excluded from the POSIX.1 standard (see paragraphs B.1.1.1.3 and B.8.3.3).

NOTES

Various systems use various types for the parameter of sbrk(). Common are int, ssize_t, ptrdiff_t, intptr_t.

Linux Notes

The return value described above for brk() is the behavior provided by the glibc wrapper function for the Linux brk() system call. (On most other implementations, the return value from brk() is the same.) However, the actual Linux system call returns the new program break on success. On failure, the system call returns the current break (thus for example, the call brk(0) can be used to obtain the current break). The glibc wrapper function does some work to provide the 0 and -1 return values described above.

On Linux, sbrk() is implemented as a library function that uses the brk() system call, and does some internal bookkeeping so that it can return the old break value.

SEE ALSO

execve(2), getrlimit(2), malloc(3)


socketcall(2)

SOCKETCALL

Section: Linux Programmer's Manual (2)
Updated: 1995-04-15 Return to Main Contents

NAME

socketcall - socket system calls

SYNOPSIS

int socketcall(int call, unsigned long *args);

DESCRIPTION

socketcall() is a common kernel entry point for the socket system calls. call determines which socket function to invoke. args points to a block containing the actual arguments, which are passed through to the appropriate call.

User programs should call the appropriate functions by their usual names. Only standard library implementors and kernel hackers need to know about socketcall().

CONFORMING TO

This call is specific to Linux, and should not be used in programs intended to be portable.

SEE ALSO

accept(2), bind(2), connect(2), getpeername(2), getsockname(2), getsockopt(2), listen(2), recv(2), recvfrom(2), send(2), sendto(2), setsockopt(2), shutdown(2), socket(2), socketpair(2)


msgget(2)

MSGGET

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

msgget - get a message queue identifier

SYNOPSIS

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int msgget(key_t key, int msgflg);

DESCRIPTION

The msgget() system call returns the message queue identifier associated with the value of the key argument. A new message queue is created if key has the value IPC_PRIVATE or key isn't IPC_PRIVATE, no message queue with the given key key exists, and IPC_CREAT is specified in msgflg.

If msgflg specifies both IPC_CREAT and IPC_EXCL and a message queue already exists for key, then msgget() fails with errno set to EEXIST. (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)

Upon creation, the least significant bits of the argument msgflg define the permissions of the message queue. These permission bits have the same format and semantics as the permissions specified for the mode argument of open(2). (The execute permissions are not used.)

If a new message queue is created, then its associated data structure msqid_ds (see msgctl(2)) is initialized as follows:

msg_perm.cuid and msg_perm.uid are set to the effective user ID of the calling process.
msg_perm.cgid and msg_perm.gid are set to the effective group ID of the calling process.
The least significant 9 bits of msg_perm.mode are set to the least significant 9 bits of msgflg.
msg_qnum, msg_lspid, msg_lrpid, msg_stime and msg_rtime are set to 0.
msg_ctime is set to the current time.
msg_qbytes is set to the system limit MSGMNB.

If the message queue already exists the permissions are verified, and a check is made to see if it is marked for destruction.

RETURN VALUE

If successful, the return value will be the message queue identifier (a non-negative integer), otherwise -1 with errno indicating the error.

ERRORS

On failure, errno is set to one of the following values:
EACCES
A message queue exists for key, but the calling process does not have permission to access the queue, and does not have the CAP_IPC_OWNER capability.
EEXIST
A message queue exists for key and msgflg specified both IPC_CREAT and IPC_EXCL.
ENOENT
No message queue exists for key and msgflg did not specify IPC_CREAT.
ENOMEM
A message queue has to be created but the system does not have enough memory for the new data structure.
ENOSPC
A message queue has to be created but the system limit for the maximum number of message queues (MSGMNI) would be exceeded.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

IPC_PRIVATE isn't a flag field but a key_t type. If this special value is used for key, the system call ignores everything but the least significant 9 bits of msgflg and creates a new message queue (on success).

The following is a system limit on message queue resources affecting a msgget() call:

MSGMNI
System wide maximum number of message queues: policy dependent (on Linux, this limit can be read and modified via /proc/sys/kernel/msgmni).

Linux Notes

Until version 2.3.20 Linux would return EIDRM for a msgget() on a message queue scheduled for deletion.

BUGS

The name choice IPC_PRIVATE was perhaps unfortunate, IPC_NEW would more clearly show its function.

SEE ALSO

msgctl(2), msgrcv(2), msgsnd(2), ftok(3), capabilities(7), mq_overview(7), svipc(7)


nanosleep(2)

NANOSLEEP

Section: Linux Programmer's Manual (2)
Updated: 2004-10-24 Return to Main Contents

NAME

nanosleep - pause execution for a specified time

SYNOPSIS

#define _POSIX_C_SOURCE 199309 #include <time.h>

int nanosleep(const struct timespec *req, struct timespec *rem);

DESCRIPTION

nanosleep() delays the execution of the program for at least the time specified in *req. The function can return earlier if a signal has been delivered to the process. In this case, it returns -1, sets errno to EINTR, and writes the remaining time into the structure pointed to by rem unless rem is NULL. The value of *rem can then be used to call nanosleep() again and complete the specified pause.

The structure timespec is used to specify intervals of time with nanosecond precision. It is specified in <time.h> and has the form

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

The value of the nanoseconds field must be in the range 0 to 999999999.

Compared to sleep(3) and usleep(3), nanosleep() has the advantage of not affecting any signals, it is standardized by POSIX, it provides higher timing resolution, and it allows to continue a sleep that has been interrupted by a signal more easily.

RETURN VALUE

On successfully sleeping for the requested interval, nanosleep() returns 0. If the call is interrupted by a signal handler or encounters an error, then it returns -1, with errno set to indicate the error.

ERRORS

EFAULT
Problem with copying information from user space.
EINTR
The pause has been interrupted by a non-blocked signal that was delivered to the process. The remaining sleep time has been written into *rem so that the process can easily call nanosleep() again and continue with the pause.
EINVAL
The value in the tv_nsec field was not in the range 0 to 999999999 or tv_sec was negative.

CONFORMING TO

POSIX.1-2001.

BUGS

The current implementation of nanosleep() is based on the normal kernel timer mechanism, which has a resolution of 1/HZ s (see time(7)). Therefore, nanosleep() pauses always for at least the specified time, however it can take up to 10 ms longer than specified until the process becomes runnable again. For the same reason, the value returned in case of a delivered signal in *rem is usually rounded to the next larger multiple of 1/HZ s.

Old behavior

In order to support applications requiring much more precise pauses (e.g., in order to control some time-critical hardware), nanosleep() would handle pauses of up to 2 ms by busy waiting with microsecond precision when called from a process scheduled under a real-time policy like SCHED_FIFO or SCHED_RR. This special extension was removed in kernel 2.5.39, hence is still present in current 2.4 kernels, but not in 2.6 kernels.

In Linux 2.4, if nanosleep() is stopped by a signal (e.g., SIGTSTP), then the call fails with the error EINTR after the process is resumed by a SIGCONT signal. If the system call is subsequently restarted, then the time that the process spent in the stopped state is not counted against the sleep interval.

SEE ALSO

sched_setscheduler(2), sleep(3), timer_create(3), usleep(3), feature_test_macros(7), time(7)


dup(2)

DUP

Section: Linux Programmer's Manual (2)
Updated: 1994-08-21 Return to Main Contents

NAME

dup, dup2 - duplicate a file descriptor

SYNOPSIS

#include <unistd.h>

int dup(int oldfd);
int dup2(int oldfd, int newfd);

DESCRIPTION

dup() and dup2() create a copy of the file descriptor oldfd.

After a successful return from dup() or dup2(), the old and new file descriptors may be used interchangeably. They refer to the same open file description (see open(2)) and thus share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other.

The two descriptors do not share file descriptor flags (the close-on-exec flag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off.

dup() uses the lowest-numbered unused descriptor for the new descriptor.

dup2() makes newfd be the copy of oldfd, closing newfd first if necessary.

RETURN VALUE

dup() and dup2() return the new descriptor, or -1 if an error occurred (in which case, errno is set appropriately).

ERRORS

EBADF
oldfd isn't an open file descriptor, or newfd is out of the allowed range for file descriptors.
EBUSY
(Linux only) This may be returned by dup2() during a race condition with open(2) and dup().
EINTR
The dup2() call was interrupted by a signal.
EMFILE
The process already has the maximum number of file descriptors open and tried to open a new one.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

The error returned by dup2() is different from that returned by fcntl(..., F_DUPFD, ...) when newfd is out of range. On some systems dup2() also sometimes returns EINVAL like F_DUPFD.

If newfd was open, any errors that would have been reported at close(2) time, are lost. A careful programmer will not use dup2() without closing newfd first.

SEE ALSO

close(2), fcntl(2), open(2)


iopl(2)

IOPL

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

iopl - change I/O privilege level

SYNOPSIS

#include <sys/io.h>

int iopl(int level);

DESCRIPTION

iopl() changes the I/O privilege level of the current process, as specified in level.

This call is necessary to allow 8514-compatible X servers to run under Linux. Since these X servers require access to all 65536 I/O ports, the ioperm(2) call is not sufficient.

In addition to granting unrestricted I/O port access, running at a higher I/O privilege level also allows the process to disable interrupts. This will probably crash the system, and is not recommended.

Permissions are inherited by fork(2) and execve(2).

The I/O privilege level for a normal process is 0.

This call is mostly for the i386 architecture. On many other architectures it does not exist or will always return an error.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
level is greater than 3.
ENOSYS
This call is unimplemented.
EPERM
The calling process has insufficient privilege to call iopl(); the CAP_SYS_RAWIO capability is required.

CONFORMING TO

iopl() is Linux specific and should not be used in processes intended to be portable.

NOTES

Libc5 treats it as a system call and has a prototype in <unistd.h>. Glibc1 does not have a prototype. Glibc2 has a prototype both in <sys/io.h> and in <sys/perm.h>. Avoid the latter, it is available on i386 only.

SEE ALSO

ioperm(2), capabilities(7)


fdatasync(2)

FDATASYNC

Section: Linux Programmer's Manual (2)
Updated: 1996-04-13 Return to Main Contents

NAME

fdatasync - synchronize a file's in-core data with that on disk

SYNOPSIS

#include <unistd.h>

int fdatasync(int fd);

DESCRIPTION

fdatasync() flushes all data buffers of a file to disk (before the system call returns). It resembles fsync(2) but is not required to update the metadata such as access time.

Applications that access databases or log files often write a tiny data fragment (e.g., one line in a log file) and then call fsync(2) immediately in order to ensure that the written data is physically stored on the harddisk. Unfortunately, fsync(2) will always initiate two write operations: one for the newly written data and another one in order to update the modification time stored in the inode. If the modification time is not a part of the transaction concept fdatasync() can be used to avoid unnecessary inode disk write operations.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
fd is not a valid file descriptor open for writing.
EIO
An error occurred during synchronization.
EROFS, EINVAL
fd is bound to a special file which does not support synchronization.

CONFORMING TO

POSIX.1-2001.

AVAILABILITY

On POSIX systems on which fdatasync() is available, _POSIX_SYNCHRONIZED_IO i defined in <unistd.h> to a value greater than 0. (See also sysconf(3).)

NOTES

In Linux 2.2 and earlier, fdatasync() is equivalent to fsync(2), and so has no performance advantage.

SEE ALSO

fsync(2), sync_file_range(2)
B.O. Gallmeister, POSIX.4, O'Reilly, pp. 220-223 and 343.


mmap(2)

MMAP

Section: Linux Programmer's Manual (2)
Updated: 2006-12-04 Return to Main Contents

NAME

mmap, munmap - map or unmap files or devices into memory

SYNOPSIS

#include <sys/mman.h>

void *mmap(void *start, size_t length, int prot, int flags,
           int fd, off_t offset);

int munmap(void *start, size_t length);

DESCRIPTION

mmap() creates a new mapping in the virtual address space of the calling process. The starting address for the new mapping is specified in start. The length argument specifies the length of the mapping.

If start is NULL, then the kernel chooses the address at which to create the mapping; this is the most portable method of creating a new mapping. If start is not NULL, then the kernel takes it as a hint about where to place the mapping; on Linux, the mapping will be created at the next higher page boundary. The address of the new mapping is returned as the result of the call.

The contents of a file mapping (as opposed to an anonymous mapping; see MAP_ANONYMOUS below), are initialized using length bytes starting at offset offset in the file (or other object) referred to by the file descriptor fd. offset must be a multiple of the page size as returned by sysconf(_SC_PAGE_SIZE).

The prot argument describes the desired memory protection of the mapping (and must not conflict with the open mode of the file). It is either PROT_NONE or the bitwise OR of one or more of the following flags:

PROT_EXEC
Pages may be executed.
PROT_READ
Pages may be read.
PROT_WRITE
Pages may be written.
PROT_NONE
Pages may not be accessed.

The flags argument determines whether updates to the mapping are visible to other processes mapping the same region, and whether updates are caried through to the underlying file. This behavior is determined by including exactly one of the following values in flags:

MAP_SHARED
Share this mapping. Updates to the mapping are visible to other processes that map this file, and are carried through to the underlying file. The file may not actually be updated until msync(2) or munmap(2) is called.
MAP_PRIVATE
Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

Both of these flags are described in POSIX.1-2001.

In addition, zero or more of the following values can be ORed in flags:

MAP_32BIT
Put the mapping into the first 2GB of the process address space. Ignored when MAP_FIXED is set. This flag is currently only supported on x86-64 for 64bit programs.
MAP_ANON
Synonym for MAP_ANONYMOUS. Deprecated.
MAP_ANONYMOUS
The mapping is not backed by any file; its contents are initialized to zero. The fd and offset arguments are ignored; however, some implementations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this. The use of MAP_ANONYMOUS in conjunction with MAP_SHARED is only supported on Linux since kernel 2.4.
MAP_DENYWRITE
This flag is ignored. (Long ago, it signaled that attempts to write to the underlying file should fail with ETXTBUSY. But this was a source of denial-of-service attacks.)
MAP_EXECUTABLE
This flag is ignored.
MAP_FILE
Compatibility flag. Ignored.
MAP_FIXED
Don't interpret start as a hint: place the mapping at exactly that address. start must be a multiple of the page size. If the memory region specified by start and len overlaps pages of any existing mapping(s), then the overlapped part of the existing mapping(s) will be discarded. If the specified address cannot be used, mmap() will fail. Because requiring a fixed address for a mapping is less portable, the use of this option is discouraged.
MAP_GROWSDOWN
Used for stacks. Indicates to the kernel virtual memory system that the mapping should extend downwards in memory.
MAP_LOCKED (since Linux 2.5.37)
Lock the pages of the mapped region into memory in the manner of mlock(2). This flag is ignored in older kernels.
MAP_NONBLOCK (since Linux 2.5.46)
Only meaningful in conjunction with MAP_POPULATE. Don't perform read-ahead: only create page tables entries for pages that are already present in RAM.
MAP_NORESERVE
Do not reserve swap space for this mapping. When swap space is reserved, one has the guarantee that it is possible to modify the mapping. When swap space is not reserved one might get SIGSEGV upon a write if no physical memory is available. See also the discussion of the file /proc/sys/vm/overcommit_memory in proc(5). In kernels before 2.6, this flag only had effect for private writable mappings.
MAP_POPULATE (since Linux 2.5.46)
Populate (prefault) page tables for a file mapping, by performing read-ahead on the file. Later accesses to the mapping will not be blocked by page faults.

Of the above flags, only MAP_FIXED is specified in POSIX.1-2001. However, most systems also support MAP_ANONYMOUS (or its synonym MAP_ANON).

Some systems document the additional flags MAP_AUTOGROW, MAP_AUTORESRV, MAP_COPY, and MAP_LOCAL.

Memory mapped by mmap() is preserved across fork(2), with the same attributes.

A file is mapped in multiples of the page size. For a file that is not a multiple of the page size, the remaining memory is zeroed when mapped, and writes to that region are not written out to the file. The effect of changing the size of the underlying file of a mapping on the pages that correspond to added or removed regions of the file is unspecified.

The munmap() system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references. The region is also automatically unmapped when the process is terminated. On the other hand, closing the file descriptor does not unmap the region.

The address start must be a multiple of the page size. All pages containing a part of the indicated range are unmapped, and subsequent references to these pages will generate SIGSEGV. It is not an error if the indicated range does not contain any mapped pages.

For file-backed mappings, the st_atime field for the mapped file may be updated at any time between the mmap() and the corresponding unmapping; the first reference to a mapped page will update the field if it has not been already.

The st_ctime and st_mtime field for a file mapped with PROT_WRITE and MAP_SHARED will be updated after a write to the mapped region, and before a subsequent msync(2) with the MS_SYNC or MS_ASYNC flag, if one occurs.

RETURN VALUE

On success, mmap() returns a pointer to the mapped area. On error, the value MAP_FAILED (that is, (void *) -1) is returned, and errno is set appropriately. On success, munmap() returns 0, on failure -1, and errno is set (probably to EINVAL).

ERRORS

EACCES
A file descriptor refers to a non-regular file. Or MAP_PRIVATE was requested, but fd is not open for reading. Or MAP_SHARED was requested and PROT_WRITE is set, but fd is not open in read/write (O_RDWR) mode. Or PROT_WRITE is set, but the file is append-only.
EAGAIN
The file has been locked, or too much memory has been locked (see setrlimit(2)).
EBADF
fd is not a valid file descriptor (and MAP_ANONYMOUS was not set).
EINVAL
We don't like start, length, or offset (e.g., they are too large, or not aligned on a page boundary).
EINVAL
(since Linux 2.6.12), length was 0.
EINVAL
flags contained neither MAP_PRIVATE or MAP_SHARED, or contained both of these values.
ENFILE
The system limit on the total number of open files has been reached.
ENODEV
The underlying filesystem of the specified file does not support memory mapping.
ENOMEM
No memory is available, or the process's maximum number of mappings would have been exceeded.
EPERM
The prot argument asks for PROT_EXEC but the mapped area belongs to a file on a filesystem that was mounted no-exec.
ETXTBSY
MAP_DENYWRITE was set but the object specified by fd is open for writing.

Use of a mapped region can result in these signals:

SIGSEGV
Attempted write into a region mapped as read-only.
SIGBUS
Attempted access to a portion of the buffer that does not correspond to the file (for example, beyond the end of the file, including the case where another process has truncated the file).

CONFORMING TO

SVr4, 4.4BSD, POSIX.1-2001.

AVAILABILITY

On POSIX systems on which mmap(), msync(2) and munmap() are available, _POSIX_MAPPED_FILES is defined in <unistd.h> to a value greater than 0. (See also sysconf(3).)

NOTES

It is architecture dependent whether PROT_READ implies PROT_EXEC or not. Portable programs should always set PROT_EXEC if they intend to execute code in the new mapping.

BUGS

On Linux there are no guarantees like those suggested above under MAP_NORESERVE. By default, any process can be killed at any moment when the system runs out of memory.

In kernels before 2.6.7, the MAP_POPULATE flag only has effect if prot is specified as PROT_NONE.

SUSv3 specifies that mmap() should fail if length is 0. However, in kernels before 2.6.12, mmap() succeeded in this case: no mapping was created and the call returned start. Since kernel 2.6.12, mmap() fails with the error EINVAL for this case.

SEE ALSO

getpagesize(2), mincore(2), mlock(2), mmap2(2), mremap(2), msync(2), remap_file_pages(2), setrlimit(2), shm_open(3)
B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128-129 and 389-391.


mount(2)

MOUNT

Section: Linux Programmer's Manual (2)
Updated: 2004-05-18 Return to Main Contents

NAME

mount, umount, umount2 - mount and unmount filesystems

SYNOPSIS

#include <sys/mount.h>

int mount(const char *source, const char *target,
          const char *filesystemtype, unsigned long mountflags,
          const void *data);

int umount(const char *target);

int umount2(const char *target, int flags);

DESCRIPTION

mount() attaches the filesystem specified by source (which is often a device name, but can also be a directory name or a dummy) to the directory specified by target.

umount() and umount2() remove the attachment of the (topmost) filesystem mounted on target.

Appropriate privilege (Linux: the CAP_SYS_ADMIN capability) is required to mount and unmount filesystems.

Since Linux 2.4 a single filesystem can be visible at multiple mount points, and multiple mounts can be stacked on the same mount point.

Values for the filesystemtype argument supported by the kernel are listed in /proc/filesystems (like "minix", "ext2", "msdos", "proc", "nfs", "iso9660" etc.). Further types may become available when the appropriate modules are loaded.

The mountflags argument may have the magic number 0xC0ED (MS_MGC_VAL) in the top 16 bits (this was required in kernel versions prior to 2.4, but is no longer required and ignored if specified), and various mount flags (as defined in <linux/fs.h> for libc4 and libc5 and in <sys/mount.h> for glibc2) in the low order 16 bits:

MS_BIND
(Linux 2.4 onwards) Perform a bind mount, making a file or a directory subtree visible at another point within a file system. Bind mounts may cross file system boundaries and span chroot(2) jails. The filesystemtype, mountflags, and data arguments are ignored.
MS_DIRSYNC (since Linux 2.5.19)
Make directory changes on this file system synchronous. (This property can be obtained for individual directories or subtrees using chattr(8).)
MS_MANDLOCK
Permit mandatory locking on files in this file system. (Mandatory locking must still be enabled on a per-file basis, as described in fcntl(2).)
MS_MOVE
Move a subtree. source specifies an existing mount point and target specifies the new location. The move is atomic: at no point is the subtree unmounted. The filesystemtype, mountflags, and data arguments are ignored.
MS_NOATIME
Do not update access times for (all types of) files on this file system.
MS_NODEV
Do not allow access to devices (special files) on this file system.
MS_NODIRATIME
Do not update access times for directories on this file system.
MS_NOEXEC
Do not allow programs to be executed from this file system.
MS_NOSUID
Do not honor set-user-ID and set-group-ID bits when executing programs from this file system.
MS_RDONLY
Mount file system read-only.
MS_RELATIME(Since Linux 2.6.20)
When a file on this file system is accessed, only update the file's last accessed time (atime) if the current value of atime is less than or equal to the file's last modified (mtime) or last status change time (ctime). This option is useful for programs, such as mutt(1), that need to know when a file has been read since it was last modified.
MS_REMOUNT
Remount an existing mount. This is allows you to change the mountflags and data of an existing mount without having to unmount and remount the file system. source and target should be the same values specified in the initial mount() call; filesystemtype is ignored.

The following mountflags can be changed: MS_RDONLY, MS_SYNCHRONOUS, MS_MANDLOCK; before kernel 2.6.16, the following could also be changed: MS_NOATIME and MS_NODIRATIME; and, additionally, before kernel 2.4, the following could also be changed: MS_NOSUID, MS_NODEV, MS_NOEXEC.

MS_SYNCHRONOUS
Make writes on this file system synchronous (as though the O_SYNC flag to open(2) was specified for all file opens to this file system).

From Linux 2.4 onwards, the MS_NODEV, MS_NOEXEC, and MS_NOSUID flags are settable on a per-mount-point basis. From kernel 2.6.16 onwards, MS_NOATIME and MS_NODIRATIME are also settable on a per-mount-point basis. The MS_RELATIME flag is also settable on a per-mount-point basis.

The data argument is interpreted by the different file systems. Typically it is a string of comma-separated options understood by this file system. See mount(8) for details of the options available for each filesystem type.

Linux 2.1.116 added the umount2() system call, which, like umount(), unmounts a target, but allows additional flags controlling the behavior of the operation:

MNT_FORCE (since Linux 2.1.116)
Force unmount even if busy. This can cause data loss. (Only for NFS mounts.)
MNT_DETACH (since Linux 2.4.11)
Perform a lazy unmount: make the mount point unavailable for new accesses, and actually perform the unmount when the mount point ceases to be busy.
MNT_EXPIRE (since Linux 2.6.8)
Mark the mount point as expired. If a mount point is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount point as expired. The mount point remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount point. This flag cannot be specified with either MNT_FORCE or MNT_DETACH.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

The error values given below result from filesystem type independent errors. Each filesystem type may have its own special errors and its own special behavior. See the kernel source code for details.
EACCES
A component of a path was not searchable. (See also path_resolution(7).) Or, mounting a read-only filesystem was attempted without giving the MS_RDONLY flag. Or, the block device source is located on a filesystem mounted with the MS_NODEV option.
EAGAIN
A call to umount2() specifying MNT_EXPIRE successfully marked an unbusy file system as expired.
EBUSY
source is already mounted. Or, it cannot be remounted read-only, because it still holds files open for writing. Or, it cannot be mounted on target because target is still busy (it is the working directory of some task, the mount point of another device, has open files, etc.). Or, it could not be unmounted because it is busy.
EFAULT
One of the pointer arguments points outside the user address space.
EINVAL
source had an invalid superblock. Or, a remount (MS_REMOUNT) was attempted, but source was not already mounted on target. Or, a move (MS_MOVE) was attempted, but source was not a mount point, or was '/'. Or, an unmount was attempted, but target was not a mount point. Or, umount2() was called with MNT_EXPIRE and either MNT_DETACH or MNT_FORCE.
ELOOP
Too many link encountered during pathname resolution. Or, a move was attempted, while target is a descendant of source.
EMFILE
(In case no block device is required:) Table of dummy devices is full.
ENAMETOOLONG
A pathname was longer than MAXPATHLEN.
ENODEV
filesystemtype not configured in the kernel.
ENOENT
A pathname was empty or had a nonexistent component.
ENOMEM
The kernel could not allocate a free page to copy filenames or data into.
ENOTBLK
source is not a block device (and a device was required).
ENOTDIR
The second argument, or a prefix of the first argument, is not a directory.
ENXIO
The major number of the block device source is out of range.
EPERM
The caller does not have the required privileges.

CONFORMING TO

These functions are Linux specific and should not be used in programs intended to be portable.

NOTES

Linux Notes

The original umount() function was called as umount(device) and would return ENOTBLK when called with something other than a block device. In Linux 0.98p4 a call umount(dir) was added, in order to support anonymous devices. In Linux 2.3.99-pre7 the call umount(device) was removed, leaving only umount(dir) (since now devices can be mounted in more than one place, so specifying the device does not suffice).

The original MS_SYNC flag was renamed MS_SYNCHRONOUS in 1.1.69 when a different MS_SYNC was added to <mman.h>.

Before Linux 2.4 an attempt to execute a set-user-ID or set-group-ID program on a filesystem mounted with MS_NOSUID would fail with EPERM. Since Linux 2.4 the set-user-ID and set-group-ID bits are just silently ignored in this case.

SEE ALSO

path_resolution(7), mount(8), umount(8)


oldstat (2)

 Continue to this page.


olduname (2)

 Continue to this page.


outb(2)

OUTB

Section: Linux Programmer's Manual (2)
Updated: 1995-11-29 Return to Main Contents

NAME

outb, outw, outl, outsb, outsw, outsl, inb, inw, inl, insb, insw, insl, outb_p, outw_p, outl_p, inb_p, inw_p, inl_p - port I/O

DESCRIPTION

This family of functions is used to do low level port input and output. The out* functions do port output, the in* functions do port input; the b-suffix functions are byte-width and the w-suffix functions word-width; the _p-suffix functions pause until the I/O completes.

They are primarily designed for internal kernel use, but can be used from user space.

You compile with -O or -O2 or similar. The functions are defined as inline macros, and will not be substituted in without optimization enabled, causing unresolved references at link time.

You use ioperm(2) or alternatively iopl(2) to tell the kernel to allow the user space application to access the I/O ports in question. Failure to do this will cause the application to receive a segmentation fault.

CONFORMING TO

outb() and friends are hardware specific. The value argument is passed first and the port argument is passed second, which is the opposite order from most DOS implementations.

SEE ALSO

ioperm(2), iopl(2)


pause(2)

PAUSE

Section: Linux Programmer's Manual (2)
Updated: 1995-08-31 Return to Main Contents

NAME

pause - wait for signal

SYNOPSIS

#include <unistd.h>

int pause(void);

DESCRIPTION

The pause() library function causes the invoking process (or thread) to sleep until a signal is received that either terminates it or causes it to call a signal-catching function.

RETURN VALUE

The pause() function only returns when a signal was caught and the signal-catching function returned. In this case pause() returns -1, and errno is set to EINTR.

ERRORS

EINTR
a signal was caught and the signal-catching function returned.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

SEE ALSO

kill(2), select(2), signal(2), sigsuspend(2)


pipe(2)

PIPE

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

pipe - create pipe

SYNOPSIS

#include <unistd.h>

int pipe(int filedes[2]);

DESCRIPTION

pipe() creates a pair of file descriptors, pointing to a pipe inode, and places them in the array pointed to by filedes. filedes[0] is for reading, filedes[1] is for writing.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
filedes is not valid.
EMFILE
Too many file descriptors are in use by the process.
ENFILE
The system limit on the total number of open files has been reached.

CONFORMING TO

POSIX.1-2001.

EXAMPLE

The following program creates a pipe, and then fork(2)s to create a child process. After the fork(2), each process closes the descriptors that it doesn't need for the pipe (see pipe(7)). The parent then writes the string contained in the program's command-line argument to the pipe, and the child reads this string a byte at a time from the pipe and echoes it on standard output.

#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int
main(int argc, char *argv[])
{
    int pfd[2];
    pid_t cpid;
    char buf;

    assert(argc == 2);

    if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }

    cpid = fork();
    if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }

    if (cpid == 0) {    /* Child reads from pipe */
        close(pfd[1]);          /* Close unused write end */

        while (read(pfd[0], &buf, 1) > 0)
            write(STDOUT_FILENO, &buf, 1);

        write(STDOUT_FILENO, "\n", 1);
        close(pfd[0]);
        _exit(EXIT_SUCCESS);

    } else {            /* Parent writes argv[1] to pipe */
        close(pfd[0]);          /* Close unused read end */
        write(pfd[1], argv[1], strlen(argv[1]));
        close(pfd[1]);          /* Reader will see EOF */
        wait(NULL);             /* Wait for child */
        exit(EXIT_SUCCESS);
    }
}

SEE ALSO

fork(2), read(2), socketpair(2), write(2), popen(3), pipe(7)


prctl(2)

PRCTL

Section: Linux Programmer's Manual (2)
Updated: 2006-08-30 Return to Main Contents

NAME

prctl - operations on a process

SYNOPSIS

#include <sys/prctl.h>

int prctl(int option, unsigned long arg2, unsigned long arg3,
          unsigned long arg4, unsigned long arg5);

DESCRIPTION

prctl() is called with a first argument describing what to do (with values defined in <linux/prctl.h>), and further parameters with a significance depending on the first one. The first argument can be:
PR_SET_PDEATHSIG
(since Linux 2.1.57) Set the parent process death signal of the calling process to arg2 (either a signal value in the range 1..maxsig, or 0 to clear). This is the signal that the calling process will get when its parent dies. This value is cleared upon a fork(2).
PR_GET_PDEATHSIG
(Since Linux 2.3.15) Read the current value of the parent process death signal into the (int *) arg2.
PR_SET_DUMPABLE
(Since Linux 2.3.20) Set the state of the flag determining whether core dumps are produced for this process upon delivery of a signal whose default behavior is to produce a core dump. (Normally this flag is set for a process by default, but it is cleared when a set-user-ID or set-group-ID program is executed and also by various system calls that manipulate process UIDs and GIDs). In kernels up to and including 2.6.12, arg2 must be either 0 (process is not dumpable) or 1 (process is dumpable). Between kernels 2.6.13 and 2.6.17, the value 2 was also permitted, which caused any binary which normally would not be dumped to be dumped readable by root only; for security reasons, this feature has been removed. (See also the description of /proc/sys/fs/suid_dumpable in proc(5).)
PR_GET_DUMPABLE
(Since Linux 2.3.20) Return (as the function result) the current state of the calling process's dumpable flag.
PR_SET_KEEPCAPS
(Since Linux 2.2.18) Set the state of the process's "keep capabilities" flag, which determines whether the process's effective and permitted capability sets are cleared when a change is made to the process's user IDs such that the process's real UID, effective UID, and saved set-user-ID all become non-zero when at least one of them previously had the value 0. (By default, these credential sets are cleared). arg2 must be either 0 (capabilities are cleared) or 1 (capabilities are kept).
PR_GET_KEEPCAPS
(Since Linux 2.2.18) Return (as the function result) the current state of the calling process's "keep capabilities" flag.
PR_SET_TIMING
(Since Linux 2.6.0-test4) Set whether to use (normal, traditional) statistical process timing or accurate timestamp based process timing, by passing PR_TIMING_STATISTICAL or PR_TIMING_TIMESTAMP to arg2.
PR_GET_TIMING
(Since Linux 2.6.0-test4) Return (as the function result) which process timing method is currently in use.
PR_SET_NAME
(Since Linux 2.6.9) Set the process name for the calling process to arg2.
PR_GET_NAME
(Since Linux 2.6.11) Get the process name for the calling process from arg2.
PR_GET_ENDIAN
(Since Linux 2.6.18, PowerPC only) Return the endian-ness of the calling process.
PR_SET_ENDIAN
(Since Linux 2.6.18, PowerPC only) Set the endian-ness of the calling process to the value given in arg2, which should be one of the following: PR_ENDIAN_BIG, PR_ENDIAN_LITTLE, or PR_ENDIAN_PPC_LITTLE (PowerPC pseudo little endian).
PR_SET_UNALIGN
(Since Linux 2.3.48, only on parisc and ia64) Set unaligned access control bits to arg2. Pass PR_UNALIGN_NOPRINT to silently fix up unaligned user accesses, or PR_UNALIGN_SIGBUS to generate SIGBUS on unaligned user access.
PR_GET_UNALIGN
(Since Linux 2.3.48, only on parisc and ia64) Get unaligned access control bits from arg2.
PR_SET_FPEMU
(Since Linux 2.4.18, 2.5.9, only on ia64) Set floating-point emulation control bits to arg2. Pass PR_FPEMU_NOPRINT to silently emulate fp operations accesses, or PR_FPEMU_SIGFPE to not emulate fp operations and send SIGFPE instead.
PR_GET_FPEMU
(Since Linux 2.4.18, 2.5.9, only on ia64) Get floating-point emulation control bits from arg2.
PR_SET_FPEXC
(Since Linux 2.4.21, 2.5.32, only on PowerPC) Set floating-point exception mode to arg2. Pass PR_FP_EXC_SW_ENABLE to use FPEXC for FP exception enables, PR_FP_EXC_DIV for floating point divide by zero, PR_FP_EXC_OVF for floating point overflow, PR_FP_EXC_UND for floating point underflow, PR_FP_EXC_RES for floating point inexact result, PR_FP_EXC_INV for floating point invalid operation, PR_FP_EXC_DISABLED for FP exceptions disabled, PR_FP_EXC_NONRECOV for async non-recoverable exception mode, PR_FP_EXC_ASYNC for async recoverable exception mode, PR_FP_EXC_PRECISE for precise exception mode.
PR_GET_FPEXC
(Since Linux 2.4.21, 2.5.32, only on PowerPC) Get floating-point exception mode from arg2.

RETURN VALUE

PR_GET_DUMPABLE and PR_GET_KEEPCAPS return 0 or 1 on success. All other option values return 0 on success. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
The value of option is not recognized, or it is PR_SET_PDEATHSIG and arg2 is not zero or a signal number.

VERSIONS

The prctl() system call was introduced in Linux 2.1.57.

CONFORMING TO

This call is Linux specific. IRIX has a prctl() system call (also introduced in Linux 2.1.44 as irix_prctl on the MIPS architecture), with prototype

ptrdiff_t prctl(int option, int arg2, int arg3);

and options to get the maximum number of processes per user, get the maximum number of processors the calling process can use, find out whether a specified process is currently blocked, get or set the maximum stack size, etc.

SEE ALSO

signal(2), core(5)


rmdir(2)

RMDIR

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

rmdir - delete a directory

SYNOPSIS

#include <unistd.h>

int rmdir(const char *pathname);

DESCRIPTION

rmdir() deletes a directory, which must be empty.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Write access to the directory containing pathname was not allowed, or one of the directories in the path prefix of pathname did not allow search permission. (See also path_resolution(7).
EBUSY
pathname is currently in use by the system or some process that prevents its removal. On Linux this means pathname is currently used as a mount point or is the root directory of the calling process.
EFAULT
pathname points outside your accessible address space.
EINVAL
pathname has . as last component.
ELOOP
Too many symbolic links were encountered in resolving pathname.
ENAMETOOLONG
pathname was too long.
ENOENT
A directory component in pathname does not exist or is a dangling symbolic link.
ENOMEM
Insufficient kernel memory was available.
ENOTDIR
pathname, or a component used as a directory in pathname, is not, in fact, a directory.
ENOTEMPTY
pathname contains entries other than . and .. ; or, pathname has .. as its final component.
EPERM
The directory containing pathname has the sticky bit (S_ISVTX) set and the process's effective user ID is neither the user ID of the file to be deleted nor that of the directory containing it, and the process is not privileged (Linux: does not have the CAP_FOWNER capability).
EPERM
The filesystem containing pathname does not support the removal of directories.
EROFS
pathname refers to a file on a read-only filesystem.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

BUGS

Infelicities in the protocol underlying NFS can cause the unexpected disappearance of directories which are still being used.

SEE ALSO

rm(1), rmdir(1), chdir(2), chmod(2), mkdir(2), rename(2), unlink(2), unlinkat(2)


sbrk (2)

 Continue to this page.


setgroups (2)

 Continue to this page.


setitimer (2)

 Continue to this page.


fstatfs (2)

 Continue to this page.


ioperm(2)

IOPERM

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

ioperm - set port input/output permissions

SYNOPSIS

#include <unistd.h> /* for libc5 */
#include <sys/io.h> /* for glibc */

int ioperm(unsigned long from, unsigned long num, int turn_on);

DESCRIPTION

ioperm() sets the port access permission bits for the process for num bytes starting from port address from to the value turn_on. If turn_on is non-zero, the calling process must be privileged (CAP_SYS_RAWIO).

Only the first 0x3ff I/O ports can be specified in this manner. For more ports, the iopl(2) system call must be used. Permissions are not inherited on fork(2), but on execve(2) they are. This is useful for giving port access permissions to non-privileged tasks.

This call is mostly for the i386 architecture. On many other architectures it does not exist or will always return an error.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
Invalid values for from or num.
EIO
(on ppc) This call is not supported.
ENOMEM
Out of memory.
EPERM
The calling process has insufficient privilege.

CONFORMING TO

ioperm() is Linux specific and should not be used in programs intended to be portable.

NOTES

Libc5 treats it as a system call and has a prototype in <unistd.h>. Glibc1 does not have a prototype. Glibc2 has a prototype both in <sys/io.h> and in <sys/perm.h>. Avoid the latter, it is available on i386 only.

SEE ALSO

iopl(2), capabilities(7)


ipc(2)

IPC

Section: Linux Programmer's Manual (2)
Updated: 1995-04-15 Return to Main Contents

NAME

ipc - System V IPC system calls

SYNOPSIS

int ipc(unsigned int call, int first, int second, int third,
        void *ptr, long fifth);

DESCRIPTION

ipc() is a common kernel entry point for the System V IPC calls for messages, semaphores, and shared memory. call determines which IPC function to invoke; the other arguments are passed through to the appropriate call.

User programs should call the appropriate functions by their usual names. Only standard library implementors and kernel hackers need to know about ipc().

CONFORMING TO

ipc() is Linux specific, and should not be used in programs intended to be portable.

SEE ALSO

msgctl(2), msgget(2), msgrcv(2), msgsnd(2), semctl(2), semget(2), semop(2), shmat(2), shmctl(2), shmdt(2), shmget(2)


gethostid(2)

GETHOSTID

Section: Linux Programmer's Manual (2)
Updated: 1993-11-29 Return to Main Contents

NAME

gethostid, sethostid - get or set the unique identifier of the current host

SYNOPSIS

#include <unistd.h>

long gethostid(void);
int sethostid(long hostid);

DESCRIPTION

Get or set a unique 32-bit identifier for the current machine. The 32-bit identifier is intended to be unique among all UNIX systems in existence. This normally resembles the Internet address for the local machine, as returned by gethostbyname(3), and thus usually never needs to be set.

The sethostid() call is restricted to the superuser.

The hostid argument is stored in the file /etc/hostid.

RETURN VALUE

gethostid() returns the 32-bit identifier for the current host as set by sethostid(2).

FILES

/etc/hostid

CONFORMING TO

4.2BSD; these functions were dropped in 4.4BSD. SVr4 includes gethostid() but not sethostid(). POSIX.1-2001 specifies gethostid() but not sethostid().

SEE ALSO

hostid(1), gethostbyname(3)


link(2)

LINK

Section: Linux Programmer's Manual (2)
Updated: 2004-06-23 Return to Main Contents

NAME

link - make a new name for a file

SYNOPSIS

#include <unistd.h>

int link(const char *oldpath, const char *newpath);

DESCRIPTION

link() creates a new link (also known as a hard link) to an existing file.

If newpath exists it will not be overwritten.

This new name may be used exactly as the old one for any operation; both names refer to the same file (and so have the same permissions and ownership) and it is impossible to tell which name was the `original'.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
Write access to the directory containing newpath is denied, or search permission is denied for one of the directories in the path prefix of oldpath or newpath. (See also path_resolution(7).)
EEXIST
newpath already exists.
EFAULT
oldpath or newpath points outside your accessible address space.
EIO
An I/O error occurred.
ELOOP
Too many symbolic links were encountered in resolving oldpath or newpath.
EMLINK
The file referred to by oldpath already has the maximum number of links to it.
ENAMETOOLONG
oldpath or newpath was too long.
ENOENT
A directory component in oldpath or newpath does not exist or is a dangling symbolic link.
ENOMEM
Insufficient kernel memory was available.
ENOSPC
The device containing the file has no room for the new directory entry.
ENOTDIR
A component used as a directory in oldpath or newpath is not, in fact, a directory.
EPERM
oldpath is a directory.
EPERM
The filesystem containing oldpath and newpath does not support the creation of hard links.
EROFS
The file is on a read-only filesystem.
EXDEV
oldpath and newpath are not on the same mounted filesystem. (Linux permits a filesystem to be mounted at multiple points, but link(2) does not work across different mount points, even if the same filesystem is mounted on both.)

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001 (except as noted above).

NOTES

Hard links, as created by link(), cannot span filesystems. Use symlink(2) if this is required.

POSIX.1-2001 says that link() should dereference oldpath if it is a symbolic link. However, Linux does not do so: if oldpath is a symbolic link, then newpath is created as a (hard) link to the same symbolic link file (i.e., newpath becomes a symbolic link to the same file that oldpath refers to). Some other implementations behave in the same manner as Linux.

BUGS

On NFS file systems, the return code may be wrong in case the NFS server performs the link creation and dies before it can say so. Use stat(2) to find out if the link got created.

SEE ALSO

ln(1), linkat(2), open(2), rename(2), stat(2), symlink(2), unlink(2) path_resolution(7)


sethostid (2)

 Continue to this page.


setpgrp (2)

 Continue to this page.


ftruncate (2)

 Continue to this page.


getitimer(2)

GETITIMER

Section: Linux Programmer's Manual (2)
Updated: 2006-04-27 Return to Main Contents

NAME

getitimer, setitimer - get or set value of an interval timer

SYNOPSIS

#include <sys/time.h>

int getitimer(int which, struct itimerval *value);

int setitimer(int which, const struct itimerval *value,
              struct itimerval *ovalue);

DESCRIPTION

The system provides each process with three interval timers, each decrementing in a distinct time domain. When any timer expires, a signal is sent to the process, and the timer (potentially) restarts.
ITIMER_REAL
decrements in real time, and delivers SIGALRM upon expiration.
ITIMER_VIRTUAL
decrements only when the process is executing, and delivers SIGVTALRM upon expiration.
ITIMER_PROF
decrements both when the process executes and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration.

Timer values are defined by the following structures:

struct itimerval {
    struct timeval it_interval; /* next value */
    struct timeval it_value;    /* current value */
};
struct timeval {
    long tv_sec;                /* seconds */
    long tv_usec;               /* microseconds */
};

The function getitimer() fills the structure indicated by value with the current setting for the timer indicated by which (one of ITIMER_REAL, ITIMER_VIRTUAL, or ITIMER_PROF). The element it_value is set to the amount of time remaining on the timer, or zero if the timer is disabled. Similarly, it_interval is set to the reset value. The function setitimer() sets the indicated timer to the value in value. If ovalue is non-zero, the old value of the timer is stored there.

Timers decrement from it_value to zero, generate a signal, and reset to it_interval. A timer which is set to zero (it_value is zero or the timer expires and it_interval is zero) stops.

Both tv_sec and tv_usec are significant in determining the duration of a timer.

Timers will never expire before the requested time, but may expire some (short) time afterwards, which depends on the system timer resolution and on the system load. (But see BUGS below.) Upon expiration, a signal will be generated and the timer reset. If the timer expires while the process is active (always true for ITIMER_VIRTUAL) the signal will be delivered immediately when generated. Otherwise the delivery will be offset by a small time dependent on the system loading.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
value or ovalue are not valid pointers.
EINVAL
which is not one of ITIMER_REAL, ITIMER_VIRTUAL, or ITIMER_PROF.

CONFORMING TO

POSIX.1-2001, SVr4, 4.4BSD (this call first appeared in 4.2BSD).

NOTES

A child created via fork(2) does not inherit its parent's interval timers. Interval timers are preserved across an execve(2).

BUGS

The generation and delivery of a signal are distinct, and only one instance of each of the signals listed above may be pending for a process. Under very heavy loading, an ITIMER_REAL timer may expire before the signal from a previous expiration has been delivered. The second signal in such an event will be lost.

On Linux, timer values are represented in jiffies. If a request is made set a timer with a value whose jiffies representation exceeds MAX_SEC_IN_JIFFIES (defined in include/linux/jiffies.h), then the timer is silently truncated to this ceiling value. On Linux/x86 (where, since kernel 2.6.13, the default jiffy is 0.004 seconds), this means that the ceiling value for a timer is approximately 99.42 days.

On certain systems (including x86), Linux kernels before version 2.6.12 have a bug which will produce premature timer expirations of up to one jiffy under some circumstances. This bug is fixed in kernel 2.6.12.

POSIX.1-2001 says that setitimer() should fail if a tv_usec value is specified that is outside of the range 0 to 999999. However, Linux does not give an error, but instead silently adjusts the corresponding seconds value for the timer. In the future (scheduled for March 2007), this non-conformance will be repaired: existing applications should be fixed now to ensure that they supply a properly formed tv_usec value.

SEE ALSO

gettimeofday(2), sigaction(2), signal(2), time(7)


getpagesize(2)

GETPAGESIZE

Section: Linux Programmer's Manual (2)
Updated: 2001-12-21 Return to Main Contents

NAME

getpagesize - get memory page size

SYNOPSIS

#include <unistd.h>

int getpagesize(void);

DESCRIPTION

The function getpagesize() returns the number of bytes in a page, where a "page" is the thing used where it says in the description of mmap(2) that files are mapped in page-sized units.

The size of the kind of pages that mmap(2) uses, is found using

#include <unistd.h>
long sz = sysconf(_SC_PAGESIZE);

(most systems allow the synonym _SC_PAGE_SIZE for _SC_PAGESIZE), or

#include <unistd.h>
int sz = getpagesize();

CONFORMING TO

SVr4, 4.4BSD, SUSv2. In SUSv2 the getpagesize() call is labeled LEGACY, and in POSIX.1-2001 it has been dropped; HP-UX does not have this call. Portable applications should employ sysconf(_SC_PAGESIZE) instead of this call.

NOTES

Whether getpagesize() is present as a Linux system call depends on the architecture. If it is, it returns the kernel symbol PAGE_SIZE, which is architecture and machine model dependent. Generally, one uses binaries that are architecture but not machine model dependent, in order to have a single binary distribution per architecture. This means that a user program should not find PAGE_SIZE at compile time from a header file, but use an actual system call, at least for those architectures (like sun4) where this dependency exists. Here libc4, libc5, glibc 2.0 fail because their getpagesize() returns a statically derived value, and does not use a system call. Things are OK in glibc 2.1.

SEE ALSO

mmap(2), sysconf(3)


listen(2)

LISTEN

Section: Linux Programmer's Manual (2)
Updated: 1993-07-23 Return to Main Contents

NAME

listen - listen for connections on a socket

SYNOPSIS

#include <sys/socket.h>

int listen(int sockfd, int backlog);

DESCRIPTION

To accept connections, a socket is first created with socket(2), a willingness to accept incoming connections and a queue limit for incoming connections are specified with listen(), and then the connections are accepted with accept(2). The listen() call applies only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

The backlog parameter defines the maximum length the queue of pending connections may grow to. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that retries succeed.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EADDRINUSE
Another socket is already listening on the same port.
EBADF
The argument sockfd is not a valid descriptor.
ENOTSOCK
The argument sockfd is not a socket.
EOPNOTSUPP
The socket is not of a type that supports the listen() operation.

CONFORMING TO

4.4BSD, POSIX.1-2001. The listen() function call first appeared in 4.2BSD.

NOTES

The behavior of the backlog parameter on TCP sockets changed with Linux 2.2. Now it specifies the queue length for completely established sockets waiting to be accepted, instead of the number of incomplete connection requests. The maximum length of the queue for incomplete sockets can be set using the tcp_max_syn_backlog sysctl. When syncookies are enabled there is no logical maximum length and this sysctl setting is ignored. See tcp(7) for more information.

If the backlog argument is greater than the value in /proc/sys/net/somaxconn, then it is silently truncated to that value; the default value in this file is 128. In kernels before 2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.

EXAMPLE

See bind(2).

SEE ALSO

accept(2), bind(2), connect(2), socket(2)


mprotect(2)

MPROTECT

Section: Linux Programmer's Manual (2)
Updated: 2007-06-02 Return to Main Contents

NAME

mprotect - set protection on a region of memory

SYNOPSIS

#include <sys/mman.h>

int mprotect(const void *addr, size_t len, int prot);

DESCRIPTION

mprotect() changes protection for the calling process's memory page(s) containing any part of the address range in the interval [addr,addr+len-1]. addr must be aligned to a page boundary.

If the calling process tries to access memory in a manner that violates the protection, then the kernel generates a SIGSEGV signal for the process.

prot is either PROT_NONE or a bitwise-or of the other values in the following list:

PROT_NONE
The memory cannot be accessed at all.
PROT_READ
The memory can be read.
PROT_WRITE
The memory can be modified.
PROT_EXEC
The memory can contain be executed.

RETURN VALUE

On success, mprotect() returns zero. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
The memory cannot be given the specified access. This can happen, for example, if you mmap(2) a file to which you have read-only access, then ask mprotect() to mark it PROT_WRITE.
EFAULT
The memory cannot be accessed.
EINVAL
addr is not a valid pointer, or not a multiple of the system page size.
ENOMEM
Internal kernel structures could not be allocated. Or: addresses in the range [addr, addr+len] are invalid for the address space of the process, or specify one or more pages that are not mapped.

CONFORMING TO

SVr4, POSIX.1-2001. POSIX says that the behavior of mprotect() is unspecified if it is applied to a region of memory that was not obtained via mmap(2).

NOTES

On Linux it is always legal to call mprotect() on any address in a process' address space (except for the kernel vsyscall area). In particular it can be used to change existing code mappings to be writable.

Whether PROT_EXEC has any effect different from PROT_READ is architecture and kernel version dependent.

POSIX.1-2001 says that an implementation may permit access other than that specified in prot, but at a minimum can only allow write access if PROT_WRITE has been set, and must not allow any access if PROT_NONE has been set.

EXAMPLE

The program below allocates four pages of memory, makes the third of these pages read-only, and then executes a loop that walks upwards through the allocated region modifying bytes.

An example of what we might see when running the program is the following:

$ ./a.out
Start of region:        0x804c000
Got SIGSEGV at address: 0x804e000

#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>

#define die(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)

char *buffer;

static void
handler(int sig, siginfo_t *si, void *unused)
{
    printf("Got SIGSEGV at address: 0x%lx\n",
            (long) si->si_addr);
    exit(EXIT_FAILURE);
}

int
main(int argc, char *argv[])
{
    char *p;
    int pagesize;
    struct sigaction sa;

    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = handler;
    if (sigaction(SIGSEGV, &sa, NULL) == -1)
        die("sigaction");

    pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize == -1)
        die("sysconf");

    /* Allocate a buffer aligned on a page boundary;
       initial protection is PROT_READ | PROT_WRITE */

    buffer = memalign(pagesize, 4 * pagesize);
    if (buffer == NULL)
        die("memalign");

    printf("Start of region:        0x%lx\n", (long) buffer);

    if (mprotect(buffer + pagesize * 2, pagesize,
                PROT_NONE) == -1)
        die("mprotect");

    for (p = buffer ; ; )
        *(p++) = 'a';

    printf("Loop completed\n");     /* Should never happen */
    exit(EXIT_SUCCESS);
}

SEE ALSO

mmap(2), sysconf(3)


msgop(2)

MSGOP

Section: Linux Programmer's Manual (2)
Updated: 2006-02-02 Return to Main Contents

NAME

msgop, msgrcv, msgsnd - message operations

SYNOPSIS

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
               int msgflg);

DESCRIPTION

The msgsnd() and msgrcv() system calls are used, respectively, to send messages to, and receive messages from, a message queue. The calling process must have write permission on the message queue in order to send a message, and read permission to receive a message.

The msgp argument is a pointer to caller-defined structure of the following general form:

struct msgbuf {
    long mtype;       /* message type, must be > 0 */
    char mtext[1];    /* message data */
};

The mtext field is an array (or other structure) whose size is specified by msgsz, a non-negative integer value. Messages of zero length (i.e., no mtext field) are permitted. The mtype field must have a strictly positive integer value. This value can be used by the receiving process for message selection (see the description of msgrcv() below).

The msgsnd() system call appends a copy of the message pointed to by msgp to the message queue whose identifier is specified by msqid.

If sufficient space is available in the queue, msgsnd() succeeds immediately. (The queue capacity is defined by the msg_bytes field in the associated data structure for the message queue. During queue creation this field is initialized to MSGMNB bytes, but this limit can be modified using msgctl(2).) If insufficient space is available in the queue, then the default behavior of msgsnd() is to block until space becomes available. If IPC_NOWAIT is specified in msgflg, then the call instead fails with the error EAGAIN.

A blocked msgsnd() call may also fail if the queue is removed (in which case the system call fails with errno set to EIDRM), or a signal is caught (in which case the system call fails with errno set to EINTR). (msgsnd and msgrcv are never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.)

Upon successful completion the message queue data structure is updated as follows:

msg_lspid is set to the process ID of the calling process.
msg_qnum is incremented by 1.
msg_stime is set to the current time.

The system call msgrcv() removes a message from the queue specified by msqid and places it in the buffer pointed to msgp.

The argument msgsz specifies the maximum size in bytes for the member mtext of the structure pointed to by the msgp argument. If the message text has length greater than msgsz, then the behavior depends on whether MSG_NOERROR is specified in msgflg. If MSG_NOERROR is specified, then the message text will be truncated (and the truncated part will be lost); if MSG_NOERROR is not specified, then the message isn't removed from the queue and the system call fails returning -1 with errno set to E2BIG.

The argument msgtyp specifies the type of message requested as follows:

If msgtyp is 0, then the first message in the queue is read.
If msgtyp is greater than 0, then the first message in the queue of type msgtyp is read, unless MSG_EXCEPT was specified in msgflg, in which case the first message in the queue of type not equal to msgtyp will be read.
If msgtyp is less than 0, then the first message in the queue with the lowest type less than or equal to the absolute value of msgtyp will be read.

The msgflg argument is a bit mask constructed by ORing together zero or more of the following flags:

IPC_NOWAIT
Return immediately if no message of the requested type is in the queue. The system call fails with errno set to ENOMSG.
MSG_EXCEPT
Used with msgtyp greater than 0 to read the first message in the queue with message type that differs from msgtyp.
MSG_NOERROR
To truncate the message text if longer than msgsz bytes.

If no message of the requested type is available and IPC_NOWAIT isn't specified in msgflg, the calling process is blocked until one of the following conditions occurs:

A message of the desired type is placed in the queue.
The message queue is removed from the system. In this case the system call fails with errno set to EIDRM.
The calling process catches a signal. In this case the system call fails with errno set to EINTR.

Upon successful completion the message queue data structure is updated as follows:

msg_lrpid is set to the process ID of the calling process.
msg_qnum is decremented by 1.
msg_rtime is set to the current time.

RETURN VALUE

On failure both functions return -1 with errno indicating the error, otherwise msgsnd() returns 0 and msgrcv() returns the number of bytes actually copied into the mtext array.

ERRORS

When msgsnd() fails, errno will be set to one among the following values:
EACCES
The calling process does not have write permission on the message queue, and does not have the CAP_IPC_OWNER capability.
EAGAIN
The message can't be sent due to the msg_qbytes limit for the queue and IPC_NOWAIT was specified in msgflg.
EFAULT
The address pointed to by msgp isn't accessible.
EIDRM
The message queue was removed.
EINTR
Sleeping on a full message queue condition, the process caught a signal.
EINVAL
Invalid msqid value, or non-positive mtype value, or invalid msgsz value (less than 0 or greater than the system value MSGMAX).
ENOMEM
The system does not have enough memory to make a copy of the message pointed to by msgp.

When msgrcv() fails, errno will be set to one among the following values:

E2BIG
The message text length is greater than msgsz and MSG_NOERROR isn't specified in msgflg.
EACCES
The calling process does not have read permission on the message queue, and does not have the CAP_IPC_OWNER capability.
EAGAIN
No message was available in the queue and IPC_NOWAIT was specified in msgflg.
EFAULT
The address pointed to by msgp isn't accessible.
EIDRM
While the process was sleeping to receive a message, the message queue was removed.
EINTR
While the process was sleeping to receive a message, the process caught a signal.
EINVAL
msgqid was invalid, or msgsz was less than 0.
ENOMSG
IPC_NOWAIT was specified in msgflg and no message of the requested type existed on the message queue.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

The msgp argument is declared as struct msgbuf * with libc4, libc5, glibc 2.0, glibc 2.1. It is declared as void * with glibc 2.2 and later, as required by SUSv2 and SUSv3.

The following limits on message queue resources affect the msgsnd() call:

MSGMAX
Maximum size for a message text: 8192 bytes (on Linux, this limit can be read and modified via /proc/sys/kernel/msgmax).
MSGMNB
Default maximum size in bytes of a message queue: 16384 bytes (on Linux, this limit can be read and modified via /proc/sys/kernel/msgmnb). The superuser can increase the size of a message queue beyond MSGMNB by a msgctl(2) system call.

The implementation has no intrinsic limits for the system wide maximum number of message headers (MSGTQL) and for the system wide maximum size in bytes of the message pool (MSGPOOL).

SEE ALSO

msgctl(2), msgget(2), msgrcv(2), msgsnd(2), capabilities(7), mq_overview(7), svipc(7)


msgsnd (2)

 Continue to this page.


obsolete(2)

OBSOLETE

Section: Linux Programmer's Manual (2)
Updated: 1995-07-22 Return to Main Contents

NAME

oldfstat, oldlstat, oldstat, oldolduname, olduname - obsolete system calls

SYNOPSIS

Obsolete system calls.

DESCRIPTION

The Linux 2.0 kernel implements these calls to support old executables. These calls return structures which have grown since their first implementation, but old executables must continue to receive old smaller structures.

Current executables should be linked with current libraries and never use these calls.

CONFORMING TO

These calls are unique to Linux and should not be used at all in new programs.

SEE ALSO

fstat(2), lstat(2), stat(2), uname(2), unimplemented(2)


personality(2)

PERSONALITY

Section: Linux Programmer's Manual (2)
Updated: 2003-01-01 Return to Main Contents

NAME

personality - set the process execution domain

SYNOPSIS

#include <sys/personality.h>

int personality(unsigned long persona);

DESCRIPTION

Linux supports different execution domains, or personalities, for each process. Among other things, execution domains tell Linux how to map signal numbers into signal actions. The execution domain system allows Linux to provide limited support for binaries compiled under other Unix-like operating systems.

This function will return the current personality() when persona equals 0xffffffff. Otherwise, it will make the execution domain referenced by persona the new execution domain of the current process.

RETURN VALUE

On success, the previous persona is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
The kernel was unable to change the personality.

CONFORMING TO

personality() is Linux specific and should not be used in programs intended to be portable.


setregid (2)

 Continue to this page.


setresuid(2)

SETRESUID

Section: Linux Programmer's Manual (2)
Updated: 2003-05-26 Return to Main Contents

NAME

setresuid, setresgid - set real, effective and saved user or group ID

SYNOPSIS

#define _GNU_SOURCE
#include <unistd.h>

int setresuid(uid_t ruid, uid_t euid, uid_t suid);
int setresgid(gid_t rgid, gid_t egid, gid_t sgid);

DESCRIPTION

setresuid() sets the real user ID, the effective user ID, and the saved set-user-ID of the current process.

Unprivileged user processes may change the real UID, effective UID, and saved set-user-ID, each to one of: the current real UID, the current effective UID or the current saved set-user-ID.

Privileged processes (on Linux, those having the CAP_SETUID capability) may set the real UID, effective UID, and saved set-user-ID to arbitrary values.

If one of the parameters equals -1, the corresponding value is not changed.

Regardless of what changes are made to the real UID, effective UID, and saved set-user-ID, the file system UID is always set to the same value as the (possibly new) effective UID.

Completely analogously, setresgid() sets the real GID, effective GID, and saved set-group-ID of the current process (and always modifies the file system GID to be the same as the effective GID), with the same restrictions for non-privileged processes.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EAGAIN
uid does not match the current UID and this call would bring that user ID over its NPROC rlimit.
EPERM
The calling process is not privileged (did not have the CAP_SETUID capability) and tried to change the IDs to values that are not permitted.

VERSIONS

These calls are available under Linux since Linux 2.1.44.

CONFORMING TO

These calls are non-standard; they also appear on HP-UX and some of the BSDs.

NOTES

Under HP-UX and FreeBSD the prototype is found in <unistd.h>. Under Linux the prototype is given by glibc since version 2.3.2 provided _GNU_SOURCE is defined.

SEE ALSO

getresuid(2), getuid(2), setfsuid(2), setfsgid(2), setreuid(2), setuid(2), capabilities(7), credentials(7), feature_test_macros(7)


settimeofday (2)

 Continue to this page.


afs_syscall (2)

 Continue to this page.


sched_rr_get_interval(2)

SCHED_RR_GET_INTERVAL

Section: Linux Programmer's Manual (2)
Updated: 2007-04-06 Return to Main Contents

NAME

sched_rr_get_interval - get the SCHED_RR interval for the named process

SYNOPSIS

#include <sched.h>

int sched_rr_get_interval(pid_t pid, struct timespec *tp);

DESCRIPTION

sched_rr_get_interval() writes into the timespec structure pointed to by tp the round-robin time quantum for the process identified by pid.

The timespec structure has the following form:

struct timespec {
    time_t tv_sec;    /* seconds */
    long   tv_nsec;   /* nanoseconds */
};

If pid is zero, the time quantum for the calling process is written into *tp. The identified process should be running under the SCHED_RR scheduling policy.

POSIX systems on which sched_rr_get_interval() is available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

RETURN VALUE

On success, sched_rr_get_interval() returns 0. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
Problem with copying information to userspace.
EINVAL
Invalid pid.
ENOSYS
The system call is not yet implemented (only on rather old kernels).
ESRCH
The process whose ID is pid could not be found.

CONFORMING TO

POSIX.1-2001.

NOTES

Linux Notes

POSIX does not specify any mechanism for controlling the size of the round-robin time quantum. However, Linux provides a (non-portable) method of doing this. The quantum can be controlled by adjusting the process's nice value (see setpriority(2)). Assigning a negative (i.e., high) nice value results in a longer quantum; assigning a positive (i.e., low) nice value results in a shorter quantum. The default quantum is 0.1 seconds; the degree to which changing the nice value affects the quantum has varied somewhat across kernel versions.

SEE ALSO

sched_setscheduler(2) has a description of the Linux scheduling scheme.

Programming for the real world - POSIX.4 by Bill O. Gallmeister, O'Reilly & Associates, Inc., ISBN 1-56592-074-0


sched_setscheduler(2)

SCHED_SETSCHEDULER

Section: Linux Programmer's Manual (2)
Updated: 2006-03-23 Return to Main Contents

NAME

sched_setscheduler, sched_getscheduler - set and get scheduling algorithm/parameters

SYNOPSIS

#include <sched.h>

int sched_setscheduler(pid_t pid, int policy,

                       const struct sched_param *param);

int sched_getscheduler(pid_t pid);

struct sched_param {
    ...
    int sched_priority;
    ...
};

DESCRIPTION

sched_setscheduler() sets both the scheduling policy and the associated parameters for the process identified by pid. If pid equals zero, the scheduler of the calling process will be set. The interpretation of the parameter param depends on the selected policy. Currently, the following three scheduling policies are supported under Linux: SCHED_FIFO, SCHED_RR, SCHED_OTHER, and SCHED_BATCH; their respective semantics are described below.

sched_getscheduler() queries the scheduling policy currently applied to the process identified by pid. If pid equals zero, the policy of the calling process will be retrieved.

Scheduling Policies

The scheduler is the kernel part that decides which runnable process will be executed by the CPU next. The Linux scheduler offers three different scheduling policies, one for normal processes and two for real-time applications. A static priority value sched_priority is assigned to each process and this value can be changed only via system calls. Conceptually, the scheduler maintains a list of runnable processes for each possible sched_priority value, and sched_priority can have a value in the range 0 to 99. In order to determine the process that runs next, the Linux scheduler looks for the non-empty list with the highest static priority and takes the process at the head of this list. The scheduling policy determines for each process, where it will be inserted into the list of processes with equal static priority and how it will move inside this list.

SCHED_OTHER is the default universal time-sharing scheduler policy used by most processes. SCHED_BATCH is intended for "batch" style execution of processes. SCHED_FIFO and SCHED_RR are intended for special time-critical applications that need precise control over the way in which runnable processes are selected for execution.

Processes scheduled with SCHED_OTHER or SCHED_BATCH must be assigned the static priority 0. Processes scheduled under SCHED_FIFO or SCHED_RR can have a static priority in the range 1 to 99. The system calls sched_get_priority_min(2) and sched_get_priority_max(2) can be used to find out the valid priority range for a scheduling policy in a portable way on all POSIX.1-2001 conforming systems.

All scheduling is preemptive: If a process with a higher static priority gets ready to run, the current process will be preempted and returned into its wait list. The scheduling policy only determines the ordering within the list of runnable processes with equal static priority.

SCHED_FIFO: First In-First Out scheduling

SCHED_FIFO can only be used with static priorities higher than 0, which means that when a SCHED_FIFO processes becomes runnable, it will always immediately preempt any currently running SCHED_OTHER or SCHED_BATCH process. SCHED_FIFO is a simple scheduling algorithm without time slicing. For processes scheduled under the SCHED_FIFO policy, the following rules are applied: A SCHED_FIFO process that has been preempted by another process of higher priority will stay at the head of the list for its priority and will resume execution as soon as all processes of higher priority are blocked again. When a SCHED_FIFO process becomes runnable, it will be inserted at the end of the list for its priority. A call to sched_setscheduler() or sched_setparam(2) will put the SCHED_FIFO (or SCHED_RR) process identified by pid at the start of the list if it was runnable. As a consequence, it may preempt the currently running process if it has the same priority. (POSIX.1-2001 specifies that the process should go to the end of the list.) A process calling sched_yield(2) will be put at the end of the list. No other events will move a process scheduled under the SCHED_FIFO policy in the wait list of runnable processes with equal static priority. A SCHED_FIFO process runs until either it is blocked by an I/O request, it is preempted by a higher priority process, or it calls sched_yield(2).

SCHED_RR: Round Robin scheduling

SCHED_RR is a simple enhancement of SCHED_FIFO. Everything described above for SCHED_FIFO also applies to SCHED_RR, except that each process is only allowed to run for a maximum time quantum. If a SCHED_RR process has been running for a time period equal to or longer than the time quantum, it will be put at the end of the list for its priority. A SCHED_RR process that has been preempted by a higher priority process and subsequently resumes execution as a running process will complete the unexpired portion of its round robin time quantum. The length of the time quantum can be retrieved using sched_rr_get_interval(2).

SCHED_OTHER: Default Linux time-sharing scheduling

SCHED_OTHER can only be used at static priority 0. SCHED_OTHER is the standard Linux time-sharing scheduler that is intended for all processes that do not require special static priority real-time mechanisms. The process to run is chosen from the static priority 0 list based on a dynamic priority that is determined only inside this list. The dynamic priority is based on the nice level (set by nice(2) or setpriority(2)) and increased for each time quantum the process is ready to run, but denied to run by the scheduler. This ensures fair progress among all SCHED_OTHER processes.

SCHED_BATCH: Scheduling batch processes

(Since Linux 2.6.16.) SCHED_BATCH can only be used at static priority 0. This policy is similar to SCHED_OTHER, except that this policy will cause the scheduler to always assume that the process is CPU-intensive. Consequently, the scheduler will apply a small scheduling penalty so that this process is mildly disfavored in scheduling decisions. This policy is useful for workloads that are non-interactive, but do not want to lower their nice value, and for workloads that want a deterministic scheduling policy without interactivity causing extra preemptions (between the workload's tasks).

Privileges and resource limits

In Linux kernels before 2.6.12, only privileged (CAP_SYS_NICE) processes can set a non-zero static priority. The only change that an unprivileged process can make is to set the SCHED_OTHER policy, and this can only be done if the effective user ID of the caller of sched_setscheduler() matches the real or effective user ID of the target process (i.e., the process specified by pid) whose policy is being changed.

Since Linux 2.6.12, the RLIMIT_RTPRIO resource limit defines a ceiling on an unprivileged process's priority for the SCHED_RR and SCHED_FIFO policies. If an unprivileged process has a non-zero RLIMIT_RTPRIO soft limit, then it can change its scheduling policy and priority, subject to the restriction that the priority cannot be set to a value higher than the RLIMIT_RTPRIO soft limit. If the RLIMIT_RTPRIO soft limit is 0, then the only permitted change is to lower the priority. Subject to the same rules, another unprivileged process can also make these changes, as long as the effective user ID of the process making the change matches the real or effective user ID of the target process. See getrlimit(2) for further information on RLIMIT_RTPRIO. Privileged (CAP_SYS_NICE) processes ignore this limit; as with older kernels, they can make arbitrary changes to scheduling policy and priority.

Response time

A blocked high priority process waiting for the I/O has a certain response time before it is scheduled again. The device driver writer can greatly reduce this response time by using a "slow interrupt" interrupt handler.

Miscellaneous

Child processes inherit the scheduling algorithm and parameters across a fork(2). The scheduling algorithm and parameters are preserved across execve(2).

Memory locking is usually needed for real-time processes to avoid paging delays, this can be done with mlock(2) or mlockall(2).

As a non-blocking end-less loop in a process scheduled under SCHED_FIFO or SCHED_RR will block all processes with lower priority forever, a software developer should always keep available on the console a shell scheduled under a higher static priority than the tested application. This will allow an emergency kill of tested real-time applications that do not block or terminate as expected.

POSIX systems on which sched_setscheduler() and sched_getscheduler() are available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

RETURN VALUE

On success, sched_setscheduler() returns zero. On success, sched_getscheduler() returns the policy for the process (a non-negative integer). On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
The scheduling policy is not one of the recognized policies, or the parameter param does not make sense for the policy.
EPERM
The calling process does not have appropriate privileges.
ESRCH
The process whose ID is pid could not be found.

CONFORMING TO

POSIX.1-2001. The SCHED_BATCH policy is Linux specific.

NOTES

Standard Linux is a general-purpose operating system and can handle background processes, interactive applications, and soft real-time applications (applications that need to usually meet timing deadlines). This man page is directed at these kinds of applications.

Standard Linux is not designed to support hard real-time applications, that is, applications in which deadlines (often much shorter than a second) must be guaranteed or the system will fail catastrophically. Like all general-purpose operating systems, Linux is designed to maximize average case performance instead of worst case performance. Linux's worst case performance for interrupt handling is much poorer than its average case, its various kernel locks (such as for SMP) produce long maximum wait times, and many of its performance improvement techniques decrease average time by increasing worst-case time. For most situations, that's what you want, but if you truly are developing a hard real-time application, consider using hard real-time extensions to Linux such as RTLinux (http://www.rtlinux.org) or RTAI (http://www.rtai.org) or use a different operating system designed specifically for hard real-time applications.

SEE ALSO

getpriority(2), mlock(2), mlockall(2), munlock(2), munlockall(2), nice(2), sched_get_priority_max(2), sched_get_priority_min(2), sched_getaffinity(2), sched_getparam(2), sched_rr_get_interval(2), sched_setaffinity(2), sched_setparam(2), sched_yield(2), setpriority(2), capabilities(7)

Programming for the real world - POSIX.4 by Bill O. Gallmeister, O'Reilly & Associates, Inc., ISBN 1-56592-074-0


select(2)

SELECT

Section: Linux Programmer's Manual (2)
Updated: 2006-03-11 Return to Main Contents

NAME

select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing

SYNOPSIS

/* According to POSIX.1-2001 */

#include <sys/select.h>

/* According to earlier standards */

#include <sys/time.h>

#include <sys/types.h>

#include <unistd.h>

int select(int nfds, fd_set *readfds, fd_set *writefds,
           fd_set *exceptfds, struct timeval *timeout);

void FD_CLR(int fd, fd_set *set);

int  FD_ISSET(int fd, fd_set *set);

void FD_SET(int fd, fd_set *set);

void FD_ZERO(fd_set *set);

#define _XOPEN_SOURCE 600
#include <sys/select.h>

int pselect(int nfds, fd_set *readfds, fd_set *writefds,
            fd_set *exceptfds, const struct timespec *timeout,
            const sigset_t *sigmask);

DESCRIPTION

select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking.

The operation of select() and pselect() is identical, with three differences:

(i)
select() uses a timeout that is a struct timeval (with seconds and microseconds), while pselect() uses a struct timespec (with seconds and nanoseconds).
(ii)
select() may update the timeout argument to indicate how much time was left. pselect() does not change this argument.
(iii)
select() has no sigmask argument, and behaves as pselect() called with NULL sigmask.

Three independent sets of file descriptors are watched. Those listed in readfds will be watched to see if characters become available for reading (more precisely, to see if a read will not block; in particular, a file descriptor is also ready on end-of-file), those in writefds will be watched to see if a write will not block, and those in exceptfds will be watched for exceptions. On exit, the sets are modified in place to indicate which file descriptors actually changed status. Each of the three file descriptor sets may be specified as NULL if no file descriptors are to be watched for the corresponding class of events.

Four macros are provided to manipulate the sets. FD_ZERO() clears a set. FD_SET() and FD_CLR() respectively add and remove a given file descriptor from a set. FD_ISSET() tests to see if a file descriptor is part of the set; this is useful after select() returns.

nfds is the highest-numbered file descriptor in any of the three sets, plus 1.

timeout is an upper bound on the amount of time elapsed before select() returns. It may be zero, causing select() to return immediately. (This is useful for polling.) If timeout is NULL (no timeout), select() can block indefinitely.

sigmask is a pointer to a signal mask (see sigprocmask(2)); if it is not NULL, then pselect() first replaces the current signal mask by the one pointed to by sigmask, then does the `select' function, and then restores the original signal mask.

Other than the difference in the precision of the timeout argument, the following pselect() call:

    ready = pselect(nfds, &readfds, &writefds, &exceptfds,
                    timeout, &sigmask);
is equivalent to atomically executing the following calls:

    sigset_t origmask;

    sigprocmask(SIG_SETMASK, &sigmask, &origmask);
    ready = select(nfds, &readfds, &writefds, &exceptfds, timeout);
    sigprocmask(SIG_SETMASK, &origmask, NULL);

The reason that pselect() is needed is that if one wants to wait for either a signal or for a file descriptor to become ready, then an atomic test is needed to prevent race conditions. (Suppose the signal handler sets a global flag and returns. Then a test of this global flag followed by a call of select() could hang indefinitely if the signal arrived just after the test but just before the call. By contrast, pselect() allows one to first block signals, handle the signals that have come in, then call pselect() with the desired sigmask, avoiding the race.)

The timeout

The time structures involved are defined in <sys/time.h> and look like

struct timeval {
    long    tv_sec;         /* seconds */
    long    tv_usec;        /* microseconds */
};

and

struct timespec {
    long    tv_sec;         /* seconds */
    long    tv_nsec;        /* nanoseconds */
};

(However, see below on the POSIX.1-2001 versions.)

Some code calls select() with all three sets empty, nfds zero, and a non-NULL timeout as a fairly portable way to sleep with subsecond precision.

On Linux, select() modifies timeout to reflect the amount of time not slept; most other implementations do not do this. (POSIX.1-2001 permits either behavior.) This causes problems both when Linux code which reads timeout is ported to other operating systems, and when code is ported to Linux that reuses a struct timeval for multiple select()s in a loop without reinitializing it. Consider timeout to be undefined after select() returns.

RETURN VALUE

On success, select() and pselect() return the number of file descriptors contained in the three returned descriptor sets (that is, the total number of bits that are set in readfds, writefds, exceptfds) which may be zero if the timeout expires before anything interesting happens. On error, -1 is returned, and errno is set appropriately; the sets and timeout become undefined, so do not rely on their contents after an error.

ERRORS

EBADF
An invalid file descriptor was given in one of the sets. (Perhaps a file descriptor that was already closed, or one on which an error has occurred.)
EINTR
A signal was caught.
EINVAL
nfds is negative or the value contained within timeout is invalid.
ENOMEM
unable to allocate memory for internal tables.

VERSIONS

pselect() was added to Linux in kernel 2.6.16. Prior to this, pselect() was emulated in glibc (but see BUGS).

CONFORMING TO

select() conforms to POSIX.1-2001 and 4.4BSD (select() first appeared in 4.2BSD). Generally portable to/from non-BSD systems supporting clones of the BSD socket layer (including System V variants). However, note that the System V variant typically sets the timeout variable before exit, but the BSD variant does not.

pselect() is defined in POSIX.1g, and in POSIX.1-2001.

NOTES

An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with a value of fd that is negative or is equal to or larger than FD_SETSIZE will result in undefined behavior. Moreover, POSIX requires fd to be a valid file descriptor.

Concerning the types involved, the classical situation is that the two fields of a timeval structure are longs (as shown above), and the structure is defined in <sys/time.h>. The POSIX.1-2001 situation is

struct timeval {
    time_t         tv_sec;     /* seconds */
    suseconds_t    tv_usec;    /* microseconds */
};

where the structure is defined in <sys/select.h> and the data types time_t and suseconds_t are defined in <sys/types.h>.

Concerning prototypes, the classical situation is that one should include <time.h> for select(). The POSIX.1-2001 situation is that one should include <sys/select.h> for select() and pselect(). Libc4 and libc5 do not have a <sys/select.h> header; under glibc 2.0 and later this header exists. Under glibc 2.0 it unconditionally gives the wrong prototype for pselect(), under glibc 2.1-2.2.1 it gives pselect() when _GNU_SOURCE is defined, under glibc 2.2.2-2.2.4 it gives it when _XOPEN_SOURCE is defined and has a value of 600 or larger. No doubt, since POSIX.1-2001, it should give the prototype by default.

Linux Notes

The Linux pselect() system call modifies its timeout argument. However, the glibc wrapper function hides this behavior by using a local variable for the timeout argument that is passed to the system call. Thus, the glibc pselect() function does not modify its timeout argument; this is the behavior required by POSIX.1-2001.

BUGS

Glibc 2.0 provided a version of pselect() that did not take a sigmask argument.

Since version 2.1, glibc has provided an emulation of pselect() that is implemented using sigprocmask(2) and select(). This implementation remains vulnerable to the very race condition that pselect() was designed to prevent. On systems that lack pselect() reliable (and more portable) signal trapping can be achieved using the self-pipe trick (where a signal handler writes a byte to a pipe whose other end is monitored by select() in the main program.)

Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.

EXAMPLE

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int
main(void)
{
    fd_set rfds;
    struct timeval tv;
    int retval;

    /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(0, &rfds);

    /* Wait up to five seconds. */
    tv.tv_sec = 5;
    tv.tv_usec = 0;

    retval = select(1, &rfds, NULL, NULL, &tv);
    /* Don't rely on the value of tv now! */

    if (retval == -1)
        perror("select()");
    else if (retval)
        printf("Data is available now.\n");
        /* FD_ISSET(0, &rfds) will be true. */
    else
        printf("No data within five seconds.\n");

    exit(EXIT_SUCCESS);
}

SEE ALSO

For a tutorial with discussion and examples, see select_tut(2).

For vaguely related stuff, see
accept(2),

connect(2),

poll(2),

read(2),

recv(2),

send(2),

sigprocmask(2),

write(2),

epoll(7),

feature_test_macros(7)


semctl(2)

SEMCTL

Section: Linux Programmer's Manual (2)
Updated: 2004-11-10 Return to Main Contents

NAME

semctl - semaphore control operations

SYNOPSIS

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int semctl(int semid, int semnum, int cmd, ...);

DESCRIPTION

semctl() performs the control operation specified by cmd on the semaphore set identified by semid, or on the semnum-th semaphore of that set. (The semaphores in a set are numbered starting at 0.)

This function has three or four arguments, depending on cmd. When there are four, the fourth has the type union semun. The calling program must define this union as follows:

union semun {
    int              val;    /* Value for SETVAL */
    struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
    unsigned short  *array;  /* Array for GETALL, SETALL */
    struct seminfo  *__buf;  /* Buffer for IPC_INFO
                                (Linux specific) */
};

The semid_ds data structure is defined in <sys/sem.h> as follows:

struct semid_ds {
    struct ipc_perm sem_perm;  /* Ownership and permissions
    time_t          sem_otime; /* Last semop time */
    time_t          sem_ctime; /* Last change time */
    unsigned short  sem_nsems; /* No. of semaphores in set */
};

The ipc_perm structure is defined in <sys/ipc.h> as follows (the highlighted fields are settable using IPC_SET):

struct ipc_perm {
    key_t key;            /* Key supplied to semget(2) */
    uid_t uid;            /* Effective UID of owner */
    gid_t gid;            /* Effective GID of owner */
    uid_t cuid;           /* Effective UID of creator */
    gid_t cgid;           /* Effective GID of creator */
    unsigned short mode;  /* Permissions */
    unsigned short seq;   /* Sequence number */
};

Valid values for cmd are:

IPC_STAT
Copy information from the kernel data structure associated with semid into the semid_ds structure pointed to by arg.buf. The argument semnum is ignored. The calling process must have read permission on the semaphore set.
IPC_SET
Write the values of some members of the semid_ds structure pointed to by arg.buf to the kernel data structure associated with this semaphore set, updating also its sem_ctime member. The following members of the structure are updated: sem_perm.uid, sem_perm.gid, and (the least significant 9 bits of) sem_perm.mode. The effective UID of the calling process must match the owner (sem_perm.uid) or creator (sem_perm.cuid) of the semaphore set, or the caller must be privileged. The argument semnum is ignored.
IPC_RMID
Immediately remove the semaphore set, awakening all processes blocked in semop(2) calls on the set (with an error return and errno set to EIDRM). The effective user ID of the calling process must match the creator or owner of the semaphore set, or the caller must be privileged. The argument semnum is ignored.
IPC_INFO (Linux specific)
Returns information about system-wide semaphore limits and parameters in the structure pointed to by arg.__buf. This structure is of type seminfo, defined in <sys/sem.h> if the _GNU_SOURCE feature test macro is defined:

struct  seminfo {
    int semmap;  /* # of entries in semaphore map;
                    unused */
    int semmni;  /* Max. # of semaphore sets */
    int semmns;  /* Max. # of semaphores in all
                    semaphore sets */
    int semmnu;  /* System-wide max. # of undo
                    structures; unused */
    int semmsl;  /* Max. # of semaphores in a set */
    int semopm;  /* Max. # of operations for semop(2) */
    int semume;  /* Max. # of undo entries per
                    process; unused */
    int semusz;  /* size of struct sem_undo */
    int semvmx;  /* Maximum semaphore value */
    int semaem;  /* Max. value that can be recorded for
                    semaphore adjustment (SEM_UNDO) */
};
The semmsl, semmns, semopm, and semmni settings can be changed via /proc/sys/kernel/sem; see proc(5) for details.
SEM_INFO (Linux specific)
Returns a seminfo structure containing the same information as for IPC_INFO, except that the following fields are returned with information about system resources consumed by semaphores: the semusz field returns the number of semaphore sets that currently exist on the system; and the semaem field returns the total number of semaphores in all semaphore sets on the system.
SEM_STAT (Linux specific)
Returns a semid_ds structure as for IPC_STAT. However, the semid argument is not a semaphore identifier, but instead an index into the kernel's internal array that maintains information about all semaphore sets on the system.
GETALL
Return semval (i.e., the current value) for all semaphores of the set into arg.array. The argument semnum is ignored. The calling process must have read permission on the semaphore set.
GETNCNT
The system call returns the value of semncnt (i.e., the number of processes waiting for the value of this semaphore to increase) for the semnum-th semaphore of the set (i.e., the number of processes waiting for an increase of semval for the semnum-th semaphore of the set). The calling process must have read permission on the semaphore set.
GETPID
The system call returns the value of sempid for the semnum-th semaphore of the set (i.e. the PID of the process that executed the last semop(2) call for the semnum-th semaphore of the set). The calling process must have read permission on the semaphore set.
GETVAL
The system call returns the value of semval for the semnum-th semaphore of the set. The calling process must have read permission on the semaphore set.
GETZCNT
The system call returns the value of semzcnt (i.e., the number of processes waiting for the value of this semaphore to become zero) for the semnum-th semaphore of the set (i.e. the number of processes waiting for semval of the semnum-th semaphore of the set to become 0). The calling process must have read permission on the semaphore set.
SETALL
Set semval for all semaphores of the set using arg.array, updating also the sem_ctime member of the semid_ds structure associated with the set. Undo entries (see semop(2)) are cleared for altered semaphores in all processes. If the changes to semaphore values would permit blocked semop(2) calls in other processes to proceed, then those processes are woken up. The argument semnum is ignored. The calling process must have alter (write) permission on the semaphore set.
SETVAL
Set the value of semval to arg.val for the semnum-th semaphore of the set, updating also the sem_ctime member of the semid_ds structure associated with the set. Undo entries are cleared for altered semaphores in all processes. If the changes to semaphore values would permit blocked semop(2) calls in other processes to proceed, then those processes are woken up. The calling process must have alter permission on the semaphore set.

RETURN VALUE

On failure semctl() returns -1 with errno indicating the error.

Otherwise the system call returns a non-negative value depending on cmd as follows:

GETNCNT
the value of semncnt.
GETPID
the value of sempid.
GETVAL
the value of semval.
GETZCNT
the value of semzcnt.
IPC_INFO
the index of the highest used entry in the kernel's internal array recording information about all semaphore sets. (This information can be used with repeated SEM_STAT operations to obtain information about all semaphore sets on the system.)
SEM_INFO
As for IPC_INFO.
SEM_STAT
the identifier of the semaphore set whose index was given in semid.

All other cmd values return 0 on success.

ERRORS

On failure, errno will be set to one of the following:
EACCES
The argument cmd has one of the values GETALL, GETPID, GETVAL, GETNCNT, GETZCNT, IPC_STAT, SEM_STAT, SETALL, or SETVAL and the calling process does not have the required permissions on the semaphore set and does not have the CAP_IPC_OWNER capability.
EFAULT
The address pointed to by arg.buf or arg.array isn't accessible.
EIDRM
The semaphore set was removed.
EINVAL
Invalid value for cmd or semid. Or: for a SEM_STAT operation, the index value specified in semid referred to an array slot that is currently unused.
EPERM
The argument cmd has the value IPC_SET or IPC_RMID but the effective user ID of the calling process is not the creator (as found in sem_perm.cuid) or the owner (as found in sem_perm.uid) of the semaphore set, and the process does not have the CAP_SYS_ADMIN capability.
ERANGE
The argument cmd has the value SETALL or SETVAL and the value to which semval is to be set (for some semaphore of the set) is less than 0 or greater than the implementation limit SEMVMX.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

The IPC_INFO, SEM_STAT and SEM_INFO operations are used by the ipcs(8) program to provide information on allocated resources. In the future these may modified or moved to a /proc file system interface.

Various fields in a struct semid_ds were shorts under Linux 2.2 and have become longs under Linux 2.4. To take advantage of this, a recompilation under glibc-2.1.91 or later should suffice. (The kernel distinguishes old and new calls by an IPC_64 flag in cmd.)

In some earlier versions of glibc, the semun union was defined in <sys/sem.h>, but POSIX.1-2001 requires that the caller define this union. On versions of glibc where this union is not defined, the macro _SEM_SEMUN_UNDEFINED is defined in <sys/sem.h>.

The following system limit on semaphore sets affects a semctl() call:

SEMVMX
Maximum value for semval: implementation dependent (32767).

For greater portability it is best to always call semctl() with four arguments.

Under Linux, semctl() is not a system call, but is implemented via the system call ipc(2).

SEE ALSO

ipc(2), semget(2), semop(2), capabilities(7), sem_overview(7), svipc(7)


setdomainname (2)

 Continue to this page.


close(2)

CLOSE

Section: Linux Programmer's Manual (2)
Updated: 2001-12-13 Return to Main Contents

NAME

close - close a file descriptor

SYNOPSIS

#include <unistd.h>

int close(int fd);

DESCRIPTION

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).

If fd is the last copy of a particular file descriptor the resources associated with it are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted.

RETURN VALUE

close() returns zero on success. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
fd isn't a valid open file descriptor.
EINTR
The close() call was interrupted by a signal.
EIO
An I/O error occurred.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota.

A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a filesystem to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use fsync(2). (It will depend on the disk hardware at this point.)

SEE ALSO

fcntl(2), fsync(2), open(2), shutdown(2), unlink(2), fclose(3)


pread(2)

PREAD

Section: Linux Programmer's Manual (2)
Updated: 1999-01-21 Return to Main Contents

NAME

pread, pwrite - read from or write to a file descriptor at a given offset

SYNOPSIS

#define _XOPEN_SOURCE 500

#include <unistd.h>

ssize_t pread(int fd, void *buf, size_t count, off_t offset);

ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);

DESCRIPTION

pread() reads up to count bytes from file descriptor fd at offset offset (from the start of the file) into the buffer starting at buf. The file offset is not changed.

pwrite() writes up to count bytes from the buffer starting at buf to the file descriptor fd at offset offset. The file offset is not changed.

The file referenced by fd must be capable of seeking.

RETURN VALUE

On success, the number of bytes read or written is returned (zero indicates that nothing was written, in the case of pwrite(), or end of file, in the case of pread(), or -1 on error, in which case errno is set to indicate the error.

ERRORS

pread() can fail and set errno to any error specified for read(2) or lseek(2). pwrite() can fail and set errno to any error specified for write(2) or lseek(2).

VERSIONS

The pread() and pwrite() system calls were added to Linux in version 2.1.60; the entries in the i386 system call table were added in 2.1.69. The libc support (including emulation on older kernels without the system calls) was added in glibc 2.1.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

lseek(2), read(2), write(2), feature_test_macros(7)


sched_setparam(2)

SCHED_SETPARAM

Section: Linux Programmer's Manual (2)
Updated: 2006-03-23 Return to Main Contents

NAME

sched_setparam, sched_getparam - set and get scheduling parameters

SYNOPSIS

#include <sched.h>

int sched_setparam(pid_t pid, const struct sched_param *param);

int sched_getparam(pid_t pid, struct sched_param *param);

struct sched_param {
    ...
    int sched_priority;
    ...
};

DESCRIPTION

sched_setparam() sets the scheduling parameters associated with the scheduling policy for the process identified by pid. If pid is zero, then the parameters of the current process are set. The interpretation of the parameter param depends on the scheduling policy of the process identified by pid. See sched_setscheduler(2) for a description of the scheduling policies supported under Linux.

sched_getparam() retrieves the scheduling parameters for the process identified by pid. If pid is zero, then the parameters of the current process are retrieved.

sched_setparam() checks the validity of param for the scheduling policy of the process. The parameter param->sched_priority must lie within the range given by sched_get_priority_min(2) and sched_get_priority_max(2).

For a discussion of the privileges and resource limits related to scheduling priority and policy, see sched_setscheduler(2).

POSIX systems on which sched_setparam() and sched_getparam() are available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

RETURN VALUE

On success, sched_setparam() and sched_getparam() return 0. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
The parameter param does not make sense for the current scheduling policy.
EPERM
The calling process does not have appropriate privileges (Linux: does not have the CAP_SYS_NICE capability).
ESRCH
The process whose ID is pid could not be found.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

getpriority(2), nice(2), sched_get_priority_max(2), sched_get_priority_min(2), sched_getaffinity(2), sched_getscheduler(2), sched_setaffinity(2), sched_setscheduler(2), setpriority(2), capabilities(7)

Programming for the real world - POSIX.4 by Bill O. Gallmeister, O'Reilly & Associates, Inc., ISBN 1-56592-074-0


sched_yield(2)

SCHED_YIELD

Section: Linux Programmer's Manual (2)
Updated: 1996-04-10 Return to Main Contents

NAME

sched_yield - yield the processor

SYNOPSIS

#include <sched.h>

int sched_yield(void);

DESCRIPTION

A process can relinquish the processor voluntarily without blocking by calling sched_yield(). The process will then be moved to the end of the queue for its static priority and a new process gets to run.

Note: If the current process is the only process in the highest priority list at that time, this process will continue to run after a call to sched_yield().

POSIX systems on which sched_yield() is available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

RETURN VALUE

On success, sched_yield() returns 0. On error, -1 is returned, and errno is set appropriately.

ERRORS

In the Linux implementation, sched_yield() always succeeds.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

sched_setscheduler(2) for a description of Linux scheduling.

Programming for the real world - POSIX.4 by Bill O. Gallmeister, O'Reilly & Associates, Inc., ISBN 1-56592-074-0


setreuid(2)

SETREUID

Section: Linux Programmer's Manual (2)
Updated: 2004-07-04 Return to Main Contents

NAME

setreuid, setregid - set real and/or effective user or group ID

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int setreuid(uid_t ruid, uid_t euid);
int setregid(gid_t rgid, gid_t egid);

DESCRIPTION

setreuid() sets real and effective user IDs of the current process.

Supplying a value of -1 for either the real or effective user ID forces the system to leave that ID unchanged.

Unprivileged processes may only set the effective user ID to the real user ID, the effective user ID or the saved set-user-ID.

POSIX: It is unspecified whether unprivileged processes may set the real user ID to the real user ID, the effective user ID or the saved set-user-ID.

Linux: Unprivileged users may only set the real user ID to the real user ID or the effective user ID.

Linux: If the real user ID is set or the effective user ID is set to a value not equal to the previous real user ID, the saved set-user-ID will be set to the new effective user ID.

Completely analogously, setregid() sets real and effective group ID's of the current process, and all of the above holds with "group" instead of "user".

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EPERM
The current process is not privileged (Linux: does not have the CAP_SETUID capability in the case of setreuid(), or the CAP_SETGID capability in the case of setregid()) and a change other than (i) swapping the effective user (group) ID with the real user (group) ID, or (ii) setting one to the value of the other or (iii) setting the effective user (group) ID to the value of the saved set-user-ID (saved set-group-ID) was specified.

CONFORMING TO

POSIX.1-2001, 4.3BSD (the setreuid() and setregid() function calls first appeared in 4.2BSD).

NOTES

Setting the effective user (group) ID to the saved set-user-ID (saved set-group-ID) is possible since Linux 1.1.37 (1.1.38).

SEE ALSO

getgid(2), getuid(2), seteuid(2), setgid(2), setresuid(2), setuid(2), capabilities(7)


fchdir (2)

 Continue to this page.


msync(2)

MSYNC

Section: Linux Programmer's Manual (2)
Updated: 2003-08-21 Return to Main Contents

NAME

msync - synchronize a file with a memory map

SYNOPSIS

#include <sys/mman.h>

int msync(void *start, size_t length, int flags);

DESCRIPTION

msync() flushes changes made to the in-core copy of a file that was mapped into memory using mmap(2) back to disk. Without use of this call there is no guarantee that changes are written back before munmap(2) is called. To be more precise, the part of the file that corresponds to the memory area starting at start and having length length is updated.

The flags argument may have the bits MS_ASYNC, MS_SYNC, and MS_INVALIDATE set, but not both MS_ASYNC and MS_SYNC. MS_ASYNC specifies that an update be scheduled, but the call returns immediately. MS_SYNC asks for an update and waits for it to complete. MS_INVALIDATE asks to invalidate other mappings of the same file (so that they can be updated with the fresh values just written).

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBUSY
MS_INVALIDATE was specified in flags, and a memory lock exists for the specified address range.
EINVAL
start is not a multiple of PAGESIZE; or any bit other than MS_ASYNC | MS_INVALIDATE | MS_SYNC is set in flags; or both MS_SYNC and MS_ASYNC are set in flags.
ENOMEM
The indicated memory (or part of it) was not mapped.

CONFORMING TO

POSIX.1-2001.

This call was introduced in Linux 1.3.21, and then used EFAULT instead of ENOMEM. In Linux 2.4.19 this was changed to the POSIX value ENOMEM.

AVAILABILITY

On POSIX systems on which msync() is available, both _POSIX_MAPPED_FILES and _POSIX_SYNCHRONIZED_IO are defined in <unistd.h> to a value greater than 0. (See also sysconf(3).)

SEE ALSO

mmap(2)
B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128-129 and 389-391.


munlockall (2)

 Continue to this page.


fork(2)

FORK

Section: Linux Programmer's Manual (2)
Updated: 2006-09-04 Return to Main Contents

NAME

fork - create a child process

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

pid_t fork(void);

DESCRIPTION

fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent, except for the following points:
*
The child has its own unique process ID, and this PID does not match the ID of any existing process group (setpgid(2)).
*
The child's parent process ID is the same as the parent's process ID.
*
The child does not inherit its parent's memory locks (mlock(2), mlockall(2)).
*
Process resource utilizations (getrusage(2)) and CPU time counters (times(2)) are reset to zero in the child.
*
The child's set of pending signals is initially empty (sigpending(2)).
*
The child does not inherit semaphore adjustments from its parent (semop(2)).
*
The child does not inherit record locks from its parent (fcntl(2)).
*
The parent does not inherit timers from its parent
(setitimer(2)

alarm(2),

timer_create(3)).
*
The child does not inherit outstanding asynchronous I/O operations from its parent (aio_read(3), aio_write(3)).

The process attributes in the preceding list are all specified in POSIX.1-2001. The parent and child also differ with respect to the following Linux-specific process attributes:

*
The child does not inherit directory change notifications (dnotify) from its parent (see the description of F_NOTIFY in fcntl(2)).
*
The prctl(2) PR_SET_PDEATHSIG setting is reset so that the child does not receive a signal when its parent terminates.
*
Memory mappings that have been marked with the madvise(2) MADV_DONTFORK flag are not inherited across a fork(2).
*
The termination signal of the child is always SIGCHLD (see clone(2)).

Note the following further points:

*
The child process is created with a single thread --- the one that called fork(2). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.
*
The child inherits copies of the parent's set of open file descriptors. Each file descriptor in the child refers to the same open file description (see open(2)) as the corresponding file descriptor in the parent. This means that the two descriptors share open file status flags, current file offset, and signal-driven I/O attributes (see the description of F_SETOWN and F_SETSIG in fcntl(2)).
*
The child inherits copies of the parent's set of open message queue descriptors (see mq_overview(7)). Each descriptor in the child refers to the same open message queue description as the corresponding descriptor in the parent. This means that the two descriptors share the same flags (mq_flags).

RETURN VALUE

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

ERRORS

EAGAIN
fork() cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child.
EAGAIN
It was not possible to create a new process because the caller's RLIMIT_NPROC resource limit was encountered. To exceed this limit, the process must have either the CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability.
ENOMEM
fork() failed to allocate the necessary kernel structures because memory is tight.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

EXAMPLE

See pipe(2) and wait(2).

SEE ALSO

clone(2), execve(2), setrlimit(2), unshare(2), vfork(2), wait(2), capabilities(7), credentials(7)


_newselect (2)

 Continue to this page.


_sysctl (2)

 Continue to this page.


cacheflush(2)

CACHEFLUSH

Section: Linux Programmer's Manual (2)
Updated: 2007-05-26 Return to Main Contents

NAME

cacheflush - flush contents of instruction and/or data cache

SYNOPSIS

#include <asm/cachectl.h>

int cacheflush(char *addr, int nbytes, int cache);

DESCRIPTION

cacheflush() flushes the contents of the indicated cache(s) for the user addresses in the range addr to (addr+nbytes-1). cache may be one of:
ICACHE
Flush the instruction cache.
DCACHE
Write back to memory and invalidate the affected valid cache lines.
BCACHE
Same as (ICACHE|DCACHE).

RETURN VALUE

cacheflush() returns 0 on success or -1 on error. If errors are detected, errno will indicate the error.

ERRORS

EFAULT
Some or all of the address range addr to (addr+nbytes-1) is not accessible.
EINVAL
cache is not one of ICACHE, DCACHE, or BCACHE.

CONFORMING TO

This Linux-specific system call is only available on MIPS based systems. It should not be used in programs intended to be portable.

BUGS

The current implementation ignores the addr and nbytes arguments. Therefore, the whole cache is always flushed.


ioctl_list(2)

IOCTL_LIST

Section: Linux Programmer's Manual (2)
Updated: 2003-03-30 Return to Main Contents

NAME

ioctl_list - list of ioctl calls in Linux/i386 kernel

DESCRIPTION

This is Ioctl List 1.3.27, a list of ioctl calls in Linux/i386 kernel 1.3.27. It contains 421 ioctls from /usr/include/{asm,linux}/*.h. For each ioctl, its numerical value, its name, and its argument type are given.

An argument type of 'const struct foo *' means the argument is input to the kernel. 'struct foo *' means the kernel outputs the argument. If the kernel uses the argument for both input and output, this is marked with // I-O.

Some ioctls take more arguments or return more values than a single structure. These are marked // MORE and documented further in a separate section.

This list is very incomplete. Please e-mail changes and comments to <mec@duracef.shout.net>.

ioctl structure

Ioctl command values are 32-bit constants. In principle these constants are completely arbitrary, but people have tried to build some structure into them.

The old Linux situation was that of mostly 16-bit constants, where the last byte is a serial number, and the preceding byte(s) give a type indicating the driver. Sometimes the major number was used: 0x03 for the HDIO_* ioctls, 0x06 for the LP* ioctls. And sometimes one or more ASCII letters were used. For example, TCGETS has value 0x00005401, with 0x54 = 'T' indicating the terminal driver, and CYGETTIMEOUT has value 0x00435906, with 0x43 0x59 = 'C' 'Y' indicating the cyclades driver.

Later (0.98p5) some more information was built into the number. One has 2 direction bits (00: none, 01: write, 10: read, 11: read/write) followed by 14 size bits (giving the size of the argument), followed by an 8-bit type (collecting the ioctls in groups for a common purpose or a common driver), and an 8-bit serial number.

The macros describing this structure live in <asm/ioctl.h> and are _IO(type,nr) and {_IOR,_IOW,_IOWR}(type,nr,size). They use sizeof(size) so that size is a misnomer here: this third parameter is a data type.

Note that the size bits are very unreliable: in lots of cases they are wrong, either because of buggy macros using sizeof(sizeof(struct)), or because of legacy values.

Thus, it seems that the new structure only gave disadvantages: it does not help in checking, but it causes varying values for the various architectures.

RETURN VALUE

Decent ioctls return 0 on success and -1 on error, while any output value is stored via the argument. However, quite a few ioctls in fact return an output value. This is not yet indicated below.

// Main table.

// <include/asm-i386/socket.h>
0x00008901  FIOSETOWN                   const int *
0x00008902  SIOCSPGRP                   const int *
0x00008903  FIOGETOWN                   int *
0x00008904  SIOCGPGRP                   int *
0x00008905  SIOCATMARK                  int *
0x00008906  SIOCGSTAMP                  timeval *

// <include/asm-i386/termios.h>
0x00005401  TCGETS                      struct termios *
0x00005402  TCSETS                      const struct termios *
0x00005403  TCSETSW                     const struct termios *
0x00005404  TCSETSF                     const struct termios *
0x00005405  TCGETA                      struct termio *
0x00005406  TCSETA                      const struct termio *
0x00005407  TCSETAW                     const struct termio *
0x00005408  TCSETAF                     const struct termio *
0x00005409  TCSBRK                      int
0x0000540A  TCXONC                      int
0x0000540B  TCFLSH                      int
0x0000540C  TIOCEXCL                    void
0x0000540D  TIOCNXCL                    void
0x0000540E  TIOCSCTTY                   int
0x0000540F  TIOCGPGRP                   pid_t *
0x00005410  TIOCSPGRP                   const pid_t *
0x00005411  TIOCOUTQ                    int *
0x00005412  TIOCSTI                     const char *
0x00005413  TIOCGWINSZ                  struct winsize *
0x00005414  TIOCSWINSZ                  const struct winsize *
0x00005415  TIOCMGET                    int *
0x00005416  TIOCMBIS                    const int *
0x00005417  TIOCMBIC                    const int *
0x00005418  TIOCMSET                    const int *
0x00005419  TIOCGSOFTCAR                int *
0x0000541A  TIOCSSOFTCAR                const int *
0x0000541B  FIONREAD                    int *
0x0000541B  TIOCINQ                     int *
0x0000541C  TIOCLINUX                   const char *                    // MORE
0x0000541D  TIOCCONS                    void
0x0000541E  TIOCGSERIAL                 struct serial_struct *
0x0000541F  TIOCSSERIAL                 const struct serial_struct *
0x00005420  TIOCPKT                     const int *
0x00005421  FIONBIO                     const int *
0x00005422  TIOCNOTTY                   void
0x00005423  TIOCSETD                    const int *
0x00005424  TIOCGETD                    int *
0x00005425  TCSBRKP                     int
0x00005426  TIOCTTYGSTRUCT              struct tty_struct *
0x00005450  FIONCLEX                    void
0x00005451  FIOCLEX                     void
0x00005452  FIOASYNC                    const int *
0x00005453  TIOCSERCONFIG               void
0x00005454  TIOCSERGWILD                int *
0x00005455  TIOCSERSWILD                const int *
0x00005456  TIOCGLCKTRMIOS              struct termios *
0x00005457  TIOCSLCKTRMIOS              const struct termios *
0x00005458  TIOCSERGSTRUCT              struct async_struct *
0x00005459  TIOCSERGETLSR               int *
0x0000545A  TIOCSERGETMULTI             struct serial_multiport_struct *
0x0000545B  TIOCSERSETMULTI             const struct serial_multiport_struct *

// <include/linux/ax25.h>
0x000089E0  SIOCAX25GETUID              const struct sockaddr_ax25 *
0x000089E1  SIOCAX25ADDUID              const struct sockaddr_ax25 *
0x000089E2  SIOCAX25DELUID              const struct sockaddr_ax25 *
0x000089E3  SIOCAX25NOUID               const int *
0x000089E4  SIOCAX25DIGCTL              const int *
0x000089E5  SIOCAX25GETPARMS            struct ax25_parms_struct *      // I-O
0x000089E6  SIOCAX25SETPARMS            const struct ax25_parms_struct *

// <include/linux/cdk.h>
0x00007314  STL_BINTR                   void
0x00007315  STL_BSTART                  void
0x00007316  STL_BSTOP                   void
0x00007317  STL_BRESET                  void

// <include/linux/cdrom.h>
0x00005301  CDROMPAUSE                  void
0x00005302  CDROMRESUME                 void
0x00005303  CDROMPLAYMSF                const struct cdrom_msf *
0x00005304  CDROMPLAYTRKIND             const struct cdrom_ti *
0x00005305  CDROMREADTOCHDR             struct cdrom_tochdr *
0x00005306  CDROMREADTOCENTRY           struct cdrom_tocentry *         // I-O
0x00005307  CDROMSTOP                   void
0x00005308  CDROMSTART                  void
0x00005309  CDROMEJECT                  void
0x0000530A  CDROMVOLCTRL                const struct cdrom_volctrl *
0x0000530B  CDROMSUBCHNL                struct cdrom_subchnl *          // I-O
0x0000530C  CDROMREADMODE2              const struct cdrom_msf *        // MORE
0x0000530D  CDROMREADMODE1              const struct cdrom_msf *        // MORE
0x0000530E  CDROMREADAUDIO              const struct cdrom_read_audio * // MORE
0x0000530F  CDROMEJECT_SW               int
0x00005310  CDROMMULTISESSION           struct cdrom_multisession *     // I-O
0x00005311  CDROM_GET_UPC               struct { char [8]; } *
0x00005312  CDROMRESET                  void
0x00005313  CDROMVOLREAD                struct cdrom_volctrl *
0x00005314  CDROMREADRAW                const struct cdrom_msf *        // MORE
0x00005315  CDROMREADCOOKED             const struct cdrom_msf *        // MORE
0x00005316  CDROMSEEK                   const struct cdrom_msf *

// <include/linux/cm206.h>
0x00002000  CM206CTL_GET_STAT           int
0x00002001  CM206CTL_GET_LAST_STAT      int

// <include/linux/cyclades.h>
0x00435901  CYGETMON                    struct cyclades_monitor *
0x00435902  CYGETTHRESH                 int *
0x00435903  CYSETTHRESH                 int
0x00435904  CYGETDEFTHRESH              int *
0x00435905  CYSETDEFTHRESH              int
0x00435906  CYGETTIMEOUT                int *
0x00435907  CYSETTIMEOUT                int
0x00435908  CYGETDEFTIMEOUT             int *
0x00435909  CYSETDEFTIMEOUT             int

// <include/linux/ext2_fs.h>
0x80046601  EXT2_IOC_GETFLAGS           int *
0x40046602  EXT2_IOC_SETFLAGS           const int *
0x80047601  EXT2_IOC_GETVERSION         int *
0x40047602  EXT2_IOC_SETVERSION         const int *

// <include/linux/fd.h>
0x00000000  FDCLRPRM                    void
0x00000001  FDSETPRM                    const struct floppy_struct *
0x00000002  FDDEFPRM                    const struct floppy_struct *
0x00000003  FDGETPRM                    struct floppy_struct *
0x00000004  FDMSGON                     void
0x00000005  FDMSGOFF                    void
0x00000006  FDFMTBEG                    void
0x00000007  FDFMTTRK                    const struct format_descr *
0x00000008  FDFMTEND                    void
0x0000000A  FDSETEMSGTRESH              int
0x0000000B  FDFLUSH                     void
0x0000000C  FDSETMAXERRS                const struct floppy_max_errors *
0x0000000E  FDGETMAXERRS                struct floppy_max_errors *
0x00000010  FDGETDRVTYP                 struct { char [16]; } *
0x00000014  FDSETDRVPRM                 const struct floppy_drive_params *
0x00000015  FDGETDRVPRM                 struct floppy_drive_params *
0x00000016  FDGETDRVSTAT                struct floppy_drive_struct *
0x00000017  FDPOLLDRVSTAT               struct floppy_drive_struct *
0x00000018  FDRESET                     int
0x00000019  FDGETFDCSTAT                struct floppy_fdc_state *
0x0000001B  FDWERRORCLR                 void
0x0000001C  FDWERRORGET                 struct floppy_write_errors *
0x0000001E  FDRAWCMD                    struct floppy_raw_cmd * // MORE // I-O
0x00000028  FDTWADDLE                   void

// <include/linux/fs.h>
0x0000125D  BLKROSET                    const int *
0x0000125E  BLKROGET                    int *
0x0000125F  BLKRRPART                   void
0x00001260  BLKGETSIZE                  int *
0x00001261  BLKFLSBUF                   void
0x00001262  BLKRASET                    int
0x00001263  BLKRAGET                    int *
0x00000001  FIBMAP                      int *                           // I-O
0x00000002  FIGETBSZ                    int *

// <include/linux/hdreg.h>
0x00000301  HDIO_GETGEO                 struct hd_geometry *
0x00000302  HDIO_GET_UNMASKINTR         int *
0x00000304  HDIO_GET_MULTCOUNT          int *
0x00000307  HDIO_GET_IDENTITY           struct hd_driveid *
0x00000308  HDIO_GET_KEEPSETTINGS       int *
0x00000309  HDIO_GET_CHIPSET            int *
0x0000030A  HDIO_GET_NOWERR             int *
0x0000030B  HDIO_GET_DMA                int *
0x0000031F  HDIO_DRIVE_CMD              int *                           // I-O
0x00000321  HDIO_SET_MULTCOUNT          int
0x00000322  HDIO_SET_UNMASKINTR         int
0x00000323  HDIO_SET_KEEPSETTINGS       int
0x00000324  HDIO_SET_CHIPSET            int
0x00000325  HDIO_SET_NOWERR             int
0x00000326  HDIO_SET_DMA                int

// <include/linux/if_eql.h>
0x000089F0  EQL_ENSLAVE                 struct ifreq *          // MORE // I-O
0x000089F1  EQL_EMANCIPATE              struct ifreq *          // MORE // I-O
0x000089F2  EQL_GETSLAVECFG             struct ifreq *          // MORE // I-O
0x000089F3  EQL_SETSLAVECFG             struct ifreq *          // MORE // I-O
0x000089F4  EQL_GETMASTRCFG             struct ifreq *          // MORE // I-O
0x000089F5  EQL_SETMASTRCFG             struct ifreq *          // MORE // I-O

// <include/linux/if_plip.h>
0x000089F0  SIOCDEVPLIP                 struct ifreq *                  // I-O

// <include/linux/if_ppp.h>
0x00005490  PPPIOCGFLAGS                int *
0x00005491  PPPIOCSFLAGS                const int *
0x00005492  PPPIOCGASYNCMAP             int *
0x00005493  PPPIOCSASYNCMAP             const int *
0x00005494  PPPIOCGUNIT                 int *
0x00005495  PPPIOCSINPSIG               const int *
0x00005497  PPPIOCSDEBUG                const int *
0x00005498  PPPIOCGDEBUG                int *
0x00005499  PPPIOCGSTAT                 struct ppp_stats *
0x0000549A  PPPIOCGTIME                 struct ppp_ddinfo *
0x0000549B  PPPIOCGXASYNCMAP            struct { int [8]; } *
0x0000549C  PPPIOCSXASYNCMAP            const struct { int [8]; } *
0x0000549D  PPPIOCSMRU                  const int *
0x0000549E  PPPIOCRASYNCMAP             const int *
0x0000549F  PPPIOCSMAXCID               const int *

// <include/linux/ipx.h>
0x000089E0  SIOCAIPXITFCRT              const char *
0x000089E1  SIOCAIPXPRISLT              const char *
0x000089E2  SIOCIPXCFGDATA              struct ipx_config_data *

// <include/linux/kd.h>
0x00004B60  GIO_FONT                    struct { char [8192]; } *
0x00004B61  PIO_FONT                    const struct { char [8192]; } *
0x00004B6B  GIO_FONTX                   struct console_font_desc *  // MORE I-O
0x00004B6C  PIO_FONTX                   const struct console_font_desc * //MORE
0x00004B70  GIO_CMAP                    struct { char [48]; } *
0x00004B71  PIO_CMAP                    const struct { char [48]; }
0x00004B2F  KIOCSOUND                   int
0x00004B30  KDMKTONE                    int
0x00004B31  KDGETLED                    char *
0x00004B32  KDSETLED                    int
0x00004B33  KDGKBTYPE                   char *
0x00004B34  KDADDIO                     int                             // MORE
0x00004B35  KDDELIO                     int                             // MORE
0x00004B36  KDENABIO                    void                            // MORE
0x00004B37  KDDISABIO                   void                            // MORE
0x00004B3A  KDSETMODE                   int
0x00004B3B  KDGETMODE                   int *
0x00004B3C  KDMAPDISP                   void                            // MORE
0x00004B3D  KDUNMAPDISP                 void                            // MORE
0x00004B40  GIO_SCRNMAP                 struct { char [E_TABSZ]; } *
0x00004B41  PIO_SCRNMAP                 const struct { char [E_TABSZ]; } *
0x00004B69  GIO_UNISCRNMAP              struct { short [E_TABSZ]; } *
0x00004B6A  PIO_UNISCRNMAP              const struct { short [E_TABSZ]; } *
0x00004B66  GIO_UNIMAP                  struct unimapdesc *     // MORE // I-O
0x00004B67  PIO_UNIMAP                  const struct unimapdesc *       // MORE
0x00004B68  PIO_UNIMAPCLR               const struct unimapinit *
0x00004B44  KDGKBMODE                   int *
0x00004B45  KDSKBMODE                   int
0x00004B62  KDGKBMETA                   int *
0x00004B63  KDSKBMETA                   int
0x00004B64  KDGKBLED                    int *
0x00004B65  KDSKBLED                    int
0x00004B46  KDGKBENT                    struct kbentry *                // I-O
0x00004B47  KDSKBENT                    const struct kbentry *
0x00004B48  KDGKBSENT                   struct kbsentry *               // I-O
0x00004B49  KDSKBSENT                   const struct kbsentry *
0x00004B4A  KDGKBDIACR                  struct kbdiacrs *
0x00004B4B  KDSKBDIACR                  const struct kbdiacrs *
0x00004B4C  KDGETKEYCODE                struct kbkeycode *              // I-O
0x00004B4D  KDSETKEYCODE                const struct kbkeycode *
0x00004B4E  KDSIGACCEPT                 int

// <include/linux/lp.h>
0x00000601  LPCHAR                      int
0x00000602  LPTIME                      int
0x00000604  LPABORT                     int
0x00000605  LPSETIRQ                    int
0x00000606  LPGETIRQ                    int *
0x00000608  LPWAIT                      int
0x00000609  LPCAREFUL                   int
0x0000060A  LPABORTOPEN                 int
0x0000060B  LPGETSTATUS                 int *
0x0000060C  LPRESET                     void
0x0000060D  LPGETSTATS                  struct lp_stats *

// <include/linux/mroute.h>
0x000089E0  SIOCGETVIFCNT               struct sioc_vif_req *           // I-O
0x000089E1  SIOCGETSGCNT                struct sioc_sg_req *            // I-O

// <include/linux/mtio.h>
0x40086D01  MTIOCTOP                    const struct mtop *
0x801C6D02  MTIOCGET                    struct mtget *
0x80046D03  MTIOCPOS                    struct mtpos *
0x80206D04  MTIOCGETCONFIG              struct mtconfiginfo *
0x40206D05  MTIOCSETCONFIG              const struct mtconfiginfo *

// <include/linux/netrom.h>
0x000089E0  SIOCNRGETPARMS              struct nr_parms_struct *        // I-O
0x000089E1  SIOCNRSETPARMS              const struct nr_parms_struct *
0x000089E2  SIOCNRDECOBS                void
0x000089E3  SIOCNRRTCTL                 const int *

// <include/linux/sbpcd.h>
0x00009000  DDIOCSDBG                   const int *
0x00005382  CDROMAUDIOBUFSIZ            int

// <include/linux/scc.h>
0x00005470  TIOCSCCINI                  void
0x00005471  TIOCCHANINI                 const struct scc_modem *
0x00005472  TIOCGKISS                   struct ioctl_command *          // I-O
0x00005473  TIOCSKISS                   const struct ioctl_command *
0x00005474  TIOCSCCSTAT                 struct scc_stat *

// <include/linux/scsi.h>
0x00005382  SCSI_IOCTL_GET_IDLUN        struct { int [2]; } *
0x00005383  SCSI_IOCTL_TAGGED_ENABLE    void
0x00005384  SCSI_IOCTL_TAGGED_DISABLE   void
0x00005385  SCSI_IOCTL_PROBE_HOST       const int *                     // MORE

// <include/linux/smb_fs.h>
0x80027501  SMB_IOC_GETMOUNTUID         uid_t *

// <include/linux/sockios.h>
0x0000890B  SIOCADDRT                   const struct rtentry *          // MORE
0x0000890C  SIOCDELRT                   const struct rtentry *          // MORE
0x00008910  SIOCGIFNAME                 char []
0x00008911  SIOCSIFLINK                 void
0x00008912  SIOCGIFCONF                 struct ifconf *         // MORE // I-O
0x00008913  SIOCGIFFLAGS                struct ifreq *                  // I-O
0x00008914  SIOCSIFFLAGS                const struct ifreq *
0x00008915  SIOCGIFADDR                 struct ifreq *                  // I-O
0x00008916  SIOCSIFADDR                 const struct ifreq *
0x00008917  SIOCGIFDSTADDR              struct ifreq *                  // I-O
0x00008918  SIOCSIFDSTADDR              const struct ifreq *
0x00008919  SIOCGIFBRDADDR              struct ifreq *                  // I-O
0x0000891A  SIOCSIFBRDADDR              const struct ifreq *
0x0000891B  SIOCGIFNETMASK              struct ifreq *                  // I-O
0x0000891C  SIOCSIFNETMASK              const struct ifreq *
0x0000891D  SIOCGIFMETRIC               struct ifreq *                  // I-O
0x0000891E  SIOCSIFMETRIC               const struct ifreq *
0x0000891F  SIOCGIFMEM                  struct ifreq *                  // I-O
0x00008920  SIOCSIFMEM                  const struct ifreq *
0x00008921  SIOCGIFMTU                  struct ifreq *                  // I-O
0x00008922  SIOCSIFMTU                  const struct ifreq *
0x00008923  OLD_SIOCGIFHWADDR           struct ifreq *                  // I-O
0x00008924  SIOCSIFHWADDR               const struct ifreq *            // MORE
0x00008925  SIOCGIFENCAP                int *
0x00008926  SIOCSIFENCAP                const int *
0x00008927  SIOCGIFHWADDR               struct ifreq *                  // I-O
0x00008929  SIOCGIFSLAVE                void
0x00008930  SIOCSIFSLAVE                void
0x00008931  SIOCADDMULTI                const struct ifreq *
0x00008932  SIOCDELMULTI                const struct ifreq *
0x00008940  SIOCADDRTOLD                void
0x00008941  SIOCDELRTOLD                void
0x00008950  SIOCDARP                    const struct arpreq *
0x00008951  SIOCGARP                    struct arpreq *                 // I-O
0x00008952  SIOCSARP                    const struct arpreq *
0x00008960  SIOCDRARP                   const struct arpreq *
0x00008961  SIOCGRARP                   struct arpreq *                 // I-O
0x00008962  SIOCSRARP                   const struct arpreq *
0x00008970  SIOCGIFMAP                  struct ifreq *                  // I-O
0x00008971  SIOCSIFMAP                  const struct ifreq *

// <include/linux/soundcard.h>
0x00005100  SNDCTL_SEQ_RESET            void
0x00005101  SNDCTL_SEQ_SYNC             void
0xC08C5102  SNDCTL_SYNTH_INFO           struct synth_info *             // I-O
0xC0045103  SNDCTL_SEQ_CTRLRATE         int *                           // I-O
0x80045104  SNDCTL_SEQ_GETOUTCOUNT      int *
0x80045105  SNDCTL_SEQ_GETINCOUNT       int *
0x40045106  SNDCTL_SEQ_PERCMODE         void
0x40285107  SNDCTL_FM_LOAD_INSTR        const struct sbi_instrument *
0x40045108  SNDCTL_SEQ_TESTMIDI         const int *
0x40045109  SNDCTL_SEQ_RESETSAMPLES     const int *
0x8004510A  SNDCTL_SEQ_NRSYNTHS         int *
0x8004510B  SNDCTL_SEQ_NRMIDIS          int *
0xC074510C  SNDCTL_MIDI_INFO            struct midi_info *              // I-O
0x4004510D  SNDCTL_SEQ_THRESHOLD        const int *
0xC004510E  SNDCTL_SYNTH_MEMAVL         int *                           // I-O
0x4004510F  SNDCTL_FM_4OP_ENABLE        const int *
0xCFB85110  SNDCTL_PMGR_ACCESS          struct patmgr_info *            // I-O
0x00005111  SNDCTL_SEQ_PANIC            void
0x40085112  SNDCTL_SEQ_OUTOFBAND        const struct seq_event_rec *
0xC0045401  SNDCTL_TMR_TIMEBASE         int *                           // I-O
0x00005402  SNDCTL_TMR_START            void
0x00005403  SNDCTL_TMR_STOP             void
0x00005404  SNDCTL_TMR_CONTINUE         void
0xC0045405  SNDCTL_TMR_TEMPO            int *                           // I-O
0xC0045406  SNDCTL_TMR_SOURCE           int *                           // I-O
0x40045407  SNDCTL_TMR_METRONOME        const int *
0x40045408  SNDCTL_TMR_SELECT           int *                           // I-O
0xCFB85001  SNDCTL_PMGR_IFACE           struct patmgr_info *            // I-O
0xC0046D00  SNDCTL_MIDI_PRETIME         int *                           // I-O
0xC0046D01  SNDCTL_MIDI_MPUMODE         const int *
0xC0216D02  SNDCTL_MIDI_MPUCMD          struct mpu_command_rec *        // I-O
0x00005000  SNDCTL_DSP_RESET            void
0x00005001  SNDCTL_DSP_SYNC             void
0xC0045002  SNDCTL_DSP_SPEED            int *                           // I-O
0xC0045003  SNDCTL_DSP_STEREO           int *                           // I-O
0xC0045004  SNDCTL_DSP_GETBLKSIZE       int *                           // I-O
0xC0045006  SOUND_PCM_WRITE_CHANNELS    int *                           // I-O
0xC0045007  SOUND_PCM_WRITE_FILTER      int *                           // I-O
0x00005008  SNDCTL_DSP_POST             void
0xC0045009  SNDCTL_DSP_SUBDIVIDE        int *                           // I-O
0xC004500A  SNDCTL_DSP_SETFRAGMENT      int *                           // I-O
0x8004500B  SNDCTL_DSP_GETFMTS          int *
0xC0045005  SNDCTL_DSP_SETFMT           int *                           // I-O
0x800C500C  SNDCTL_DSP_GETOSPACE        struct audio_buf_info *
0x800C500D  SNDCTL_DSP_GETISPACE        struct audio_buf_info *
0x0000500E  SNDCTL_DSP_NONBLOCK         void
0x80045002  SOUND_PCM_READ_RATE         int *
0x80045006  SOUND_PCM_READ_CHANNELS     int *
0x80045005  SOUND_PCM_READ_BITS         int *
0x80045007  SOUND_PCM_READ_FILTER       int *
0x00004300  SNDCTL_COPR_RESET           void
0xCFB04301  SNDCTL_COPR_LOAD            const struct copr_buffer *
0xC0144302  SNDCTL_COPR_RDATA           struct copr_debug_buf *         // I-O
0xC0144303  SNDCTL_COPR_RCODE           struct copr_debug_buf *         // I-O
0x40144304  SNDCTL_COPR_WDATA           const struct copr_debug_buf *
0x40144305  SNDCTL_COPR_WCODE           const struct copr_debug_buf *
0xC0144306  SNDCTL_COPR_RUN             struct copr_debug_buf *         // I-O
0xC0144307  SNDCTL_COPR_HALT            struct copr_debug_buf *         // I-O
0x4FA44308  SNDCTL_COPR_SENDMSG         const struct copr_msg *
0x8FA44309  SNDCTL_COPR_RCVMSG          struct copr_msg *
0x80044D00  SOUND_MIXER_READ_VOLUME     int *
0x80044D01  SOUND_MIXER_READ_BASS       int *
0x80044D02  SOUND_MIXER_READ_TREBLE     int *
0x80044D03  SOUND_MIXER_READ_SYNTH      int *
0x80044D04  SOUND_MIXER_READ_PCM        int *
0x80044D05  SOUND_MIXER_READ_SPEAKER    int *
0x80044D06  SOUND_MIXER_READ_LINE       int *
0x80044D07  SOUND_MIXER_READ_MIC        int *
0x80044D08  SOUND_MIXER_READ_CD         int *
0x80044D09  SOUND_MIXER_READ_IMIX       int *
0x80044D0A  SOUND_MIXER_READ_ALTPCM     int *
0x80044D0B  SOUND_MIXER_READ_RECLEV     int *
0x80044D0C  SOUND_MIXER_READ_IGAIN      int *
0x80044D0D  SOUND_MIXER_READ_OGAIN      int *
0x80044D0E  SOUND_MIXER_READ_LINE1      int *
0x80044D0F  SOUND_MIXER_READ_LINE2      int *
0x80044D10  SOUND_MIXER_READ_LINE3      int *
0x80044D1C  SOUND_MIXER_READ_MUTE       int *
0x80044D1D  SOUND_MIXER_READ_ENHANCE    int *
0x80044D1E  SOUND_MIXER_READ_LOUD       int *
0x80044DFF  SOUND_MIXER_READ_RECSRC     int *
0x80044DFE  SOUND_MIXER_READ_DEVMASK    int *
0x80044DFD  SOUND_MIXER_READ_RECMASK    int *
0x80044DFB  SOUND_MIXER_READ_STEREODEVS int *
0x80044DFC  SOUND_MIXER_READ_CAPS       int *
0xC0044D00  SOUND_MIXER_WRITE_VOLUME    int *                           // I-O
0xC0044D01  SOUND_MIXER_WRITE_BASS      int *                           // I-O
0xC0044D02  SOUND_MIXER_WRITE_TREBLE    int *                           // I-O
0xC0044D03  SOUND_MIXER_WRITE_SYNTH     int *                           // I-O
0xC0044D04  SOUND_MIXER_WRITE_PCM       int *                           // I-O
0xC0044D05  SOUND_MIXER_WRITE_SPEAKER   int *                           // I-O
0xC0044D06  SOUND_MIXER_WRITE_LINE      int *                           // I-O
0xC0044D07  SOUND_MIXER_WRITE_MIC       int *                           // I-O
0xC0044D08  SOUND_MIXER_WRITE_CD        int *                           // I-O
0xC0044D09  SOUND_MIXER_WRITE_IMIX      int *                           // I-O
0xC0044D0A  SOUND_MIXER_WRITE_ALTPCM    int *                           // I-O
0xC0044D0B  SOUND_MIXER_WRITE_RECLEV    int *                           // I-O
0xC0044D0C  SOUND_MIXER_WRITE_IGAIN     int *                           // I-O
0xC0044D0D  SOUND_MIXER_WRITE_OGAIN     int *                           // I-O
0xC0044D0E  SOUND_MIXER_WRITE_LINE1     int *                           // I-O
0xC0044D0F  SOUND_MIXER_WRITE_LINE2     int *                           // I-O
0xC0044D10  SOUND_MIXER_WRITE_LINE3     int *                           // I-O
0xC0044D1C  SOUND_MIXER_WRITE_MUTE      int *                           // I-O
0xC0044D1D  SOUND_MIXER_WRITE_ENHANCE   int *                           // I-O
0xC0044D1E  SOUND_MIXER_WRITE_LOUD      int *                           // I-O
0xC0044DFF  SOUND_MIXER_WRITE_RECSRC    int *                           // I-O

// <include/linux/umsdos_fs.h>
0x000004D2  UMSDOS_READDIR_DOS          struct umsdos_ioctl *           // I-O
0x000004D3  UMSDOS_UNLINK_DOS           const struct umsdos_ioctl *
0x000004D4  UMSDOS_RMDIR_DOS            const struct umsdos_ioctl *
0x000004D5  UMSDOS_STAT_DOS             struct umsdos_ioctl *           // I-O
0x000004D6  UMSDOS_CREAT_EMD            const struct umsdos_ioctl *
0x000004D7  UMSDOS_UNLINK_EMD           const struct umsdos_ioctl *
0x000004D8  UMSDOS_READDIR_EMD          struct umsdos_ioctl *           // I-O
0x000004D9  UMSDOS_GETVERSION           struct umsdos_ioctl *
0x000004DA  UMSDOS_INIT_EMD             void
0x000004DB  UMSDOS_DOS_SETUP            const struct umsdos_ioctl *
0x000004DC  UMSDOS_RENAME_DOS           const struct umsdos_ioctl *

// <include/linux/vt.h>
0x00005600  VT_OPENQRY                  int *
0x00005601  VT_GETMODE                  struct vt_mode *
0x00005602  VT_SETMODE                  const struct vt_mode *
0x00005603  VT_GETSTATE                 struct vt_stat *
0x00005604  VT_SENDSIG                  void
0x00005605  VT_RELDISP                  int
0x00005606  VT_ACTIVATE                 int
0x00005607  VT_WAITACTIVE               int
0x00005608  VT_DISALLOCATE              int
0x00005609  VT_RESIZE                   const struct vt_sizes *
0x0000560A  VT_RESIZEX                  const struct vt_consize *

// More arguments.
Some ioctl's take a pointer to a structure which contains additional pointers. These are documented here in alphabetical order.

CDROMREADAUDIO takes an input pointer 'const struct cdrom_read_audio *'. The 'buf' field points to an output buffer of length 'nframes * CD_FRAMESIZE_RAW'.

CDROMREADCOOKED, CDROMREADMODE1, CDROMREADMODE2, and CDROMREADRAW take an input pointer 'const struct cdrom_msf *'. They use the same pointer as an output pointer to 'char []'. The length varies by request. For CDROMREADMODE1, most drivers use 'CD_FRAMESIZE', but the Optics Storage driver uses 'OPT_BLOCKSIZE' instead (both have the numerical value 2048).

            CDROMREADCOOKED             char [CD_FRAMESIZE]
            CDROMREADMODE1              char [CD_FRAMESIZE or OPT_BLOCKSIZE]
            CDROMREADMODE2              char [CD_FRAMESIZE_RAW0]
            CDROMREADRAW                char [CD_FRAMESIZE_RAW]
EQL_ENSLAVE, EQL_EMANCIPATE, EQL_GETSLAVECFG, EQL_SETSLAVECFG, EQL_GETMASTERCFG, and EQL_SETMASTERCFG take a 'struct ifreq *'. The 'ifr_data' field is a pointer to another structure as follows:

            EQL_ENSLAVE                 const struct slaving_request *
            EQL_EMANCIPATE              const struct slaving_request *
            EQL_GETSLAVECFG             struct slave_config *           // I-O
            EQL_SETSLAVECFG             const struct slave_config *
            EQL_GETMASTERCFG            struct master_config *
            EQL_SETMASTERCFG            const struct master_config *
FDRAWCMD takes a 'struct floppy raw_cmd *'. If 'flags & FD_RAW_WRITE' is non-zero, then 'data' points to an input buffer of length 'length'. If 'flags & FD_RAW_READ' is non-zero, then 'data' points to an output buffer of length 'length'.

GIO_FONTX and PIO_FONTX take a 'struct console_font_desc *' or a 'const struct console_font_desc *', respectively. 'chardata' points to a buffer of 'char [charcount]'. This is an output buffer for GIO_FONTX and an input buffer for PIO_FONTX.

GIO_UNIMAP and PIO_UNIMAP take a 'struct unimapdesc *' or a 'const struct unimapdesc *', respectively. 'entries' points to a buffer of 'struct unipair [entry_ct]'. This is an output buffer for GIO_UNIMAP and an input buffer for PIO_UNIMAP.

KDADDIO, KDDELIO, KDDISABIO, and KDENABIO enable or disable access to I/O ports. They are essentially alternate interfaces to 'ioperm'.

KDMAPDISP and KDUNMAPDISP enable or disable memory mappings or I/O port access. They are not implemented in the kernel.

SCSI_IOCTL_PROBE_HOST takes an input pointer 'const int *', which is a length. It uses the same pointer as an output pointer to a 'char []' buffer of this length.

SIOCADDRT and SIOCDELRT take an input pointer whose type depends on the protocol:

            Most protocols              const struct rtentry *
            AX.25                       const struct ax25_route *
            NET/ROM                     const struct nr_route_struct *
SIOCGIFCONF takes a 'struct ifconf *'. The 'ifc_buf' field points to a buffer of length 'ifc_len' bytes, into which the kernel writes a list of type 'struct ifreq []'.

SIOCSIFHWADDR takes an input pointer whose type depends on the protocol:

            Most protocols              const struct ifreq *
            AX.25                       const char [AX25_ADDR_LEN]
TIOCLINUX takes a 'const char *'. It uses this to distinguish several independent sub-cases. In the table below, 'N + foo' means 'foo' after an N-byte pad. 'struct selection' is implicitly defined in 'drivers/char/selection.c'

            TIOCLINUX-2                 1 + const struct selection *
            TIOCLINUX-3                 void
            TIOCLINUX-4                 void
            TIOCLINUX-5                 4 + const struct { long [8]; } *
            TIOCLINUX-6                 char *
            TIOCLINUX-7                 char *
            TIOCLINUX-10                1 + const char *
// Duplicate ioctls

This list does not include ioctls in the range SIOCDEVPRIVATE and SIOCPROTOPRIVATE.

0x00000001  FDSETPRM                    FIBMAP
0x00000002  FDDEFPRM                    FIGETBSZ
0x00005382  CDROMAUDIOBUFSIZ            SCSI_IOCTL_GET_IDLUN
0x00005402  SNDCTL_TMR_START            TCSETS
0x00005403  SNDCTL_TMR_STOP             TCSETSW
0x00005404  SNDCTL_TMR_CONTINUE         TCSETSF

SEE ALSO

ioctl(2)


fchmod (2)

 Continue to this page.


setrlimit (2)

 Continue to this page.


flock(2)

FLOCK

Section: Linux Programmer's Manual (2)
Updated: 2002-04-24 Return to Main Contents

NAME

flock - apply or remove an advisory lock on an open file

SYNOPSIS

#include <sys/file.h>

int flock(int fd, int operation);

DESCRIPTION

Apply or remove an advisory lock on the open file specified by fd. The parameter operation is one of the following:
LOCK_SH
Place a shared lock. More than one process may hold a shared lock for a given file at a given time.
LOCK_EX
Place an exclusive lock. Only one process may hold an exclusive lock for a given file at a given time.
LOCK_UN
Remove an existing lock held by this process.

A call to flock() may block if an incompatible lock is held by another process. To make a non-blocking request, include LOCK_NB (by ORing) with any of the above operations.

A single file may not simultaneously have both shared and exclusive locks.

Locks created by flock() are associated with an open file table entry. This means that duplicate file descriptors (created by, for example, fork(2) or dup(2)) refer to the same lock, and this lock may be modified or released using any of these descriptors. Furthermore, the lock is released either by an explicit LOCK_UN operation on any of these duplicate descriptors, or when all such descriptors have been closed.

If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, these descriptors are treated independently by flock(). An attempt to lock the file using one of these file descriptors may be denied by a lock that the calling process has already placed via another descriptor.

A process may only hold one type of lock (shared or exclusive) on a file. Subsequent flock() calls on an already locked file will convert an existing lock to the new lock mode.

Locks created by flock() are preserved across an execve(2).

A shared or exclusive lock can be placed on a file regardless of the mode in which the file was opened.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
fd is not a not an open file descriptor.
EINTR
While waiting to acquire a lock, the call was interrupted by delivery of a signal caught by a handler.
EINVAL
operation is invalid.
ENOLCK
The kernel ran out of memory for allocating lock records.
EWOULDBLOCK
The file is locked and the LOCK_NB flag was selected.

CONFORMING TO

4.4BSD (the flock(2) call first appeared in 4.2BSD). A version of flock(2), possibly implemented in terms of fcntl(2), appears on most Unix systems.

NOTES

flock(2) does not lock files over NFS. Use fcntl(2) instead: that does work over NFS, given a sufficiently recent version of Linux and a server which supports locking.

Since kernel 2.0, flock(2) is implemented as a system call in its own right rather than being emulated in the GNU C library as a call to fcntl(2). This yields true BSD semantics: there is no interaction between the types of lock placed by flock(2) and fcntl(2), and flock(2) does not detect deadlock.

flock(2) places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock(2) and perform I/O on the file.

flock(2) and fcntl(2) locks have different semantics with respect to forked processes and dup(2). On systems that implement flock() using fcntl(2), the semantics of flock() will be different from those described in this manual page.

Converting a lock (shared to exclusive, or vice versa) is not guaranteed to be atomic: the existing lock is first removed, and then a new lock is established. Between these two steps, a pending lock request by another process may be granted, with the result that the conversion either blocks, or fails if LOCK_NB was specified. (This is the original BSD behavior, and occurs on many other implementations.)

SEE ALSO

close(2), dup(2), execve(2), fcntl(2), fork(2), open(2), lockf(3)

See also Documentation/locks.txt and Documentation/mandatory.txt in the kernel source.


fstat (2)

 Continue to this page.


ptrace(2)

PTRACE

Section: Linux Programmer's Manual (2)
Updated: 2006-03-24 Return to Main Contents

NAME

ptrace - process trace

SYNOPSIS

#include <sys/ptrace.h>

long ptrace(enum __ptrace_request request, pid_t pid,
            void *addr, void *data);

DESCRIPTION

The ptrace() system call provides a means by which a parent process may observe and control the execution of another process, and examine and change its core image and registers. It is primarily used to implement breakpoint debugging and system call tracing.

The parent can initiate a trace by calling fork(2) and having the resulting child do a PTRACE_TRACEME, followed (typically) by an exec(3). Alternatively, the parent may commence trace of an existing process using PTRACE_ATTACH.

While being traced, the child will stop each time a signal is delivered, even if the signal is being ignored. (The exception is SIGKILL, which has its usual effect.) The parent will be notified at its next wait(2) and may inspect and modify the child process while it is stopped. The parent then causes the child to continue, optionally ignoring the delivered signal (or even delivering a different signal instead).

When the parent is finished tracing, it can terminate the child with PTRACE_KILL or cause it to continue executing in a normal, untraced mode via PTRACE_DETACH.

The value of request determines the action to be performed:

PTRACE_TRACEME
Indicates that this process is to be traced by its parent. Any signal (except SIGKILL) delivered to this process will cause it to stop and its parent to be notified via wait(2). Also, all subsequent calls to execve(2) by this process will cause a SIGTRAP to be sent to it, giving the parent a chance to gain control before the new program begins execution. A process probably shouldn't make this request if its parent isn't expecting to trace it. (pid, addr, and data are ignored.)

The above request is used only by the child process; the rest are used only by the parent. In the following requests, pid specifies the child process to be acted on. For requests other than PTRACE_KILL, the child process must be stopped.

PTRACE_PEEKTEXT, PTRACE_PEEKDATA
Reads a word at the location addr in the child's memory, returning the word as the result of the ptrace() call. Linux does not have separate text and data address spaces, so the two requests are currently equivalent. (The argument data is ignored.)
PTRACE_PEEKUSR
Reads a word at offset addr in the child's USER area, which holds the registers and other information about the process (see <linux/user.h> and <sys/user.h>). The word is returned as the result of the ptrace() call. Typically the offset must be word-aligned, though this might vary by architecture. (data is ignored.)
PTRACE_POKETEXT, PTRACE_POKEDATA
Copies the word data to location addr in the child's memory. As above, the two requests are currently equivalent.
PTRACE_POKEUSR
Copies the word data to offset addr in the child's USER area. As above, the offset must typically be word-aligned. In order to maintain the integrity of the kernel, some modifications to the USER area are disallowed.
PTRACE_GETREGS, PTRACE_GETFPREGS
Copies the child's general purpose or floating-point registers, respectively, to location data in the parent. See <linux/user.h> for information on the format of this data. (addr is ignored.)
PTRACE_GETSIGINFO (since Linux 2.3.99-pre6)
Retrieve information about the signal that caused the stop. Copies a siginfo_t structure (see sigaction(2)) from the child to location data in the parent. (addr is ignored.)
PTRACE_SETREGS, PTRACE_SETFPREGS
Copies the child's general purpose or floating-point registers, respectively, from location data in the parent. As for PTRACE_POKEUSER, some general purpose register modifications may be disallowed. (addr is ignored.)
PTRACE_SETSIGINFO (since Linux 2.3.99-pre6)
Set signal information. Copies a siginfo_t structure from location data in the parent to the child. This will only affect signals that would normally be delivered to the child and were caught by the tracer. It may be difficult to tell these normal signals from synthetic signals generated by ptrace() itself. (addr is ignored.)
PTRACE_SETOPTIONS (since Linux 2.4.6; see BUGS for caveats)
Sets ptrace options from data in the parent. (addr is ignored.) data is interpreted as a bitmask of options, which are specified by the following flags:
PTRACE_O_TRACESYSGOOD (since Linux 2.4.6)
When delivering syscall traps, set bit 7 in the signal number (i.e., deliver (SIGTRAP | 0x80) This makes it easy for the tracer to tell the difference between normal traps and those caused by a syscall. (PTRACE_O_TRACESYSGOOD may not work on all architectures.)
PTRACE_O_TRACEFORK (since Linux 2.5.46)
Stop the child at the next fork(2) call with SIGTRAP | PTRACE_EVENT_FORK << 8 and automatically start tracing the newly forked process, which will start with a SIGSTOP. The PID for the new process can be retrieved with PTRACE_GETEVENTMSG.
PTRACE_O_TRACEVFORK (since Linux 2.5.46)
Stop the child at the next vfork(2) call with SIGTRAP | PTRACE_EVENT_VFORK << 8 and automatically start tracing the newly vforked process, which will start with a SIGSTOP. The PID for the new process can be retrieved with PTRACE_GETEVENTMSG.
PTRACE_O_TRACECLONE (since Linux 2.5.46)
Stop the child at the next clone(2) call with SIGTRAP | PTRACE_EVENT_CLONE << 8 and automatically start tracing the newly cloned process, which will start with a SIGSTOP. The PID for the new process can be retrieved with PTRACE_GETEVENTMSG. This option may not catch clone(2) calls in all cases. If the child calls clone(2) with the CLONE_VFORK flag, PTRACE_EVENT_VFORK will be delivered instead if PTRACE_O_TRACEVFORK is set; otherwise if the child calls clone(2) with the exit signal set to SIGCHLD, PTRACE_EVENT_FORK will be delivered if PTRACE_O_TRACEFORK is set.
PTRACE_O_TRACEEXEC (since Linux 2.5.46)
Stop the child at the next execve(2) call with SIGTRAP | PTRACE_EVENT_EXEC << 8.
PTRACE_O_TRACEVFORKDONE (since Linux 2.5.60)
Stop the child at the completion of the next vfork(2) call with SIGTRAP | PTRACE_EVENT_VFORK_DONE << 8.
PTRACE_O_TRACEEXIT (since Linux 2.5.60)
Stop the child at exit with SIGTRAP | PTRACE_EVENT_EXIT << 8. The child's exit status can be retrieved with PTRACE_GETEVENTMSG. This stop will be done early during process exit when registers are still available, allowing the tracer to see where the exit occurred, whereas the normal exit notification is done after the process is finished exiting. Even though context is available, the tracer cannot prevent the exit from happening at this point.
PTRACE_GETEVENTMSG (since Linux 2.5.46)
Retrieve a message (as an unsigned long) about the ptrace event that just happened, placing it in the location data in the parent. For PTRACE_EVENT_EXIT this is the child's exit status. For PTRACE_EVENT_FORK, PTRACE_EVENT_VFORK and PTRACE_EVENT_CLONE this is the PID of the new process. Since Linux 2.6.18, the PID of the new process is also available for PTRACE_EVENT_VFORK_DONE. (addr is ignored.)
PTRACE_CONT
Restarts the stopped child process. If data is non-zero and not SIGSTOP, it is interpreted as a signal to be delivered to the child; otherwise, no signal is delivered. Thus, for example, the parent can control whether a signal sent to the child is delivered or not. (addr is ignored.)
PTRACE_SYSCALL, PTRACE_SINGLESTEP
Restarts the stopped child as for PTRACE_CONT, but arranges for the child to be stopped at the next entry to or exit from a system call, or after execution of a single instruction, respectively. (The child will also, as usual, be stopped upon receipt of a signal.) From the parent's perspective, the child will appear to have been stopped by receipt of a SIGTRAP. So, for PTRACE_SYSCALL, for example, the idea is to inspect the arguments to the system call at the first stop, then do another PTRACE_SYSCALL and inspect the return value of the system call at the second stop. (addr is ignored.)
PTRACE_SYSEMU, PTRACE_SYSEMU_SINGLESTEP (since Linux 2.6.14)
For PTRACE_SYSEMU, continue and stop on entry to the next syscall, which will not be executed. For PTRACE_SYSEMU_SINGLESTEP, do the same but also singlestep if not a syscall. This call is used by programs like User Mode Linux that want to emulate all the child's system calls. (addr and data are ignored; not supported on all architectures.)
PTRACE_KILL
Sends the child a SIGKILL to terminate it. (addr and data are ignored.)
PTRACE_ATTACH
Attaches to the process specified in pid, making it a traced "child" of the current process; the behavior of the child is as if it had done a PTRACE_TRACEME. The current process actually becomes the parent of the child process for most purposes (e.g., it will receive notification of child events and appears in ps(1) output as the child's parent), but a getppid(2) by the child will still return the PID of the original parent. The child is sent a SIGSTOP, but will not necessarily have stopped by the completion of this call; use wait(2) to wait for the child to stop. (addr and data are ignored.)
PTRACE_DETACH
Restarts the stopped child as for PTRACE_CONT, but first detaches from the process, undoing the reparenting effect of PTRACE_ATTACH, and the effects of PTRACE_TRACEME. Although perhaps not intended, under Linux a traced child can be detached in this way regardless of which method was used to initiate tracing. (addr is ignored.)

RETURN VALUE

On success, PTRACE_PEEK* requests return the requested data, while other requests return zero. On error, all requests return -1, and errno is set appropriately. Since the value returned by a successful PTRACE_PEEK* request may be -1, the caller must check errno after such requests to determine whether or not an error occurred.

ERRORS

EBUSY
(i386 only) There was an error with allocating or freeing a debug register.
EFAULT
There was an attempt to read from or write to an invalid area in the parent's or child's memory, probably because the area wasn't mapped or accessible. Unfortunately, under Linux, different variations of this fault will return EIO or EFAULT more or less arbitrarily.
EINVAL
An attempt was made to set an invalid option.
EIO
request is invalid, or an attempt was made to read from or write to an invalid area in the parent's or child's memory, or there was a word-alignment violation, or an invalid signal was specified during a restart request.
EPERM
The specified process cannot be traced. This could be because the parent has insufficient privileges (the required capability is CAP_SYS_PTRACE); non-root processes cannot trace processes that they cannot send signals to or those running set-user-ID/set-group-ID programs, for obvious reasons. Alternatively, the process may already be being traced, or be init (PID 1).
ESRCH
The specified process does not exist, or is not currently being traced by the caller, or is not stopped (for requests that require that).

CONFORMING TO

SVr4, 4.3BSD

NOTES

Although arguments to ptrace() are interpreted according to the prototype given, GNU libc currently declares ptrace() as a variadic function with only the request argument fixed. This means that unneeded trailing arguments may be omitted, though doing so makes use of undocumented gcc(1) behavior.

init(8), the process with PID 1, may not be traced.

The layout of the contents of memory and the USER area are quite OS- and architecture-specific.

The size of a "word" is determined by the OS variant (e.g., for 32-bit Linux it is 32 bits, etc.).

Tracing causes a few subtle differences in the semantics of traced processes. For example, if a process is attached to with PTRACE_ATTACH, its original parent can no longer receive notification via wait(2) when it stops, and there is no way for the new parent to effectively simulate this notification.

When the parent receives an event with PTRACE_EVENT_* set, the child is not in the normal signal delivery path. This means the parent cannot do ptrace(PTRACE_CONT) with a signal or ptrace(PTRACE_KILL). kill(2) with a SIGKILL signal can be used instead to kill the child process after receiving one of these messages.

This page documents the way the ptrace() call works currently in Linux. Its behavior differs noticeably on other flavors of Unix. In any case, use of ptrace() is highly OS- and architecture-specific.

The SunOS man page describes ptrace() as "unique and arcane", which it is. The proc-based debugging interface present in Solaris 2 implements a superset of ptrace() functionality in a more powerful and uniform way.

BUGS

On hosts with 2.6 kernel headers, PTRACE_SETOPTIONS is declared with a different value than the one for 2.4. This leads to applications compiled with such headers failing when run on 2.4 kernels. This can be worked around by redefining PTRACE_SETOPTIONS to PTRACE_OLDSETOPTIONS, if that is defined.

SEE ALSO

gdb(1), strace(1), execve(2), fork(2), signal(2), wait(2), exec(3), capabilities(7)


fsync(2)

FSYNC

Section: Linux Programmer's Manual (2)
Updated: 2006-04-28 Return to Main Contents

NAME

fsync, fdatasync - synchronize a file's in-core state with storage device

SYNOPSIS

#include <unistd.h>

int fsync(int fd);

int fdatasync(int fd);

DESCRIPTION

fsync() transfers ("flushes") all modified in-core data of (i.e., modified buffer cache pages for) the file referred to by the file descriptor fd to the disk device (or other permanent storage device) where that file resides. The call blocks until the device reports that the transfer has completed. It also flushes metadata information associated with the file (see stat(2)).

Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed.

fdatasync() is similar to fsync(), but does not flush modified metadata unless that metadata is needed in order to allow a subsequent data retrieval to be correctly handled. For example, changes to st_atime or st_mtime (respectively, time of last access and time of last modification; see stat(2)) do not require flushing because they are not necessary for a subsequent data read to be handled correctly. On the other hand, a change to the file size (st_size, as made by say ftruncate(2)), would require a metadata flush.

The aim of fdatasync(2) is to reduce disk activity for applications that do not require all metadata to be synchronized with the disk.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
fd is not a valid file descriptor open for writing.
EIO
An error occurred during synchronization.
EROFS, EINVAL
fd is bound to a special file which does not support synchronization.

CONFORMING TO

4.3BSD, POSIX.1-2001

NOTES

If the underlying hard disk has write caching enabled, then the data may not really be on permanent storage when fsync() / fdatasync() return.

When an ext2 file system is mounted with the sync option, directory entries are also implicitly synced by fsync().

On kernels before 2.4, fsync() on big files can be inefficient. An alternative might be to use the O_SYNC flag to open(2).

SEE ALSO

bdflush(2), open(2), sync(2), sync_file_range(2), hdparm(8), mount(8), sync(8), update(8)


getdents(2)

GETDENTS

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

getdents - get directory entries

SYNOPSIS

#include <unistd.h>
#include <linux/types.h>
#include <linux/dirent.h>
#include <linux/unistd.h>
#include <errno.h>

int getdents(unsigned int fd, struct dirent *dirp, unsigned int count);

DESCRIPTION

This is not the function you are interested in. Look at readdir(3) for the POSIX conforming C library interface. This page documents the bare kernel system call interface.

The system call getdents() reads several dirent structures from the directory pointed at by fd into the memory area pointed to by dirp. The parameter count is the size of the memory area.

The dirent structure is declared as follows:

struct dirent {
    long d_ino;                 /* inode number */
    off_t d_off;                /* offset to next dirent */
    unsigned short d_reclen;    /* length of this dirent */
    char d_name [NAME_MAX+1];   /* filename (null-terminated) */
}

d_ino is an inode number. d_off is the distance from the start of the directory to the start of the next dirent. d_reclen is the size of this entire dirent. d_name is a null-terminated filename.

This call supersedes readdir(2).

RETURN VALUE

On success, the number of bytes read is returned. On end of directory, 0 is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
Invalid file descriptor fd.
EFAULT
Argument points outside the calling process's address space.
EINVAL
Result buffer is too small.
ENOENT
No such directory.
ENOTDIR
File descriptor does not refer to a directory.

CONFORMING TO

SVr4.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

SEE ALSO

readdir(2), readdir(3)


getdtablesize(2)

GETDTABLESIZE

Section: Linux Programmer's Manual (2)
Updated: 2002-04-15 Return to Main Contents

NAME

getdtablesize - get descriptor table size

SYNOPSIS

#include <unistd.h>

int getdtablesize(void);

DESCRIPTION

getdtablesize() returns the maximum number of files a process can have open, one more than the largest possible value for a file descriptor.

RETURN VALUE

The current limit on the number of open files per process.

ERRORS

On Linux, getdtablesize() can return any of the errors described for getrlimit(2); see NOTES below.

CONFORMING TO

SVr4, 4.4BSD (the getdtablesize() function first appeared in 4.2BSD). It is not specified in POSIX.1-2001; portable applications should employ sysconf(_SC_OPEN_MAX) instead of this call.

NOTES

getdtablesize() is implemented as a libc library function. The glibc version calls getrlimit(2) and returns the current RLIMIT_NOFILE limit, or OPEN_MAX when that fails. The libc4 and libc5 versions return OPEN_MAX (set to 256 since Linux 0.98.4).

SEE ALSO

close(2), dup(2), getrlimit(2), open(2)


getegid (2)

 Continue to this page.


getrlimit(2)

GETRLIMIT

Section: Linux Programmer's Manual (2)
Updated: 2005-09-20 Return to Main Contents

NAME

getrlimit, setrlimit - get/set resource limits

SYNOPSIS

#include <sys/time.h>
#include <sys/resource.h>

int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);

DESCRIPTION

getrlimit() and setrlimit() get and set resource limits respectively. Each resource has an associated soft and hard limit, as defined by the rlimit structure (the rlim argument to both getrlimit() and setrlimit()):

struct rlimit {
    rlim_t rlim_cur;  /* Soft limit */
    rlim_t rlim_max;  /* Hard limit (ceiling for rlim_cur) */
};
The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit: an unprivileged process may only set its soft limit to a value in the range from 0 up to the hard limit, and (irreversibly) lower its hard limit. A privileged process (under Linux: one with the CAP_SYS_RESOURCE capability) may make arbitrary changes to either limit value.

The value RLIM_INFINITY denotes no limit on a resource (both in the structure returned by getrlimit() and in the structure passed to setrlimit()).

resource must be one of:

RLIMIT_AS
The maximum size of the process's virtual memory (address space) in bytes. This limit affects calls to brk(2), mmap(2) and mremap(2), which fail with the error ENOMEM upon exceeding this limit. Also automatic stack expansion will fail (and generate a SIGSEGV that kills the process if no alternate stack has been made available via sigaltstack(2)). Since the value is a long, on machines with a 32-bit long either this limit is at most 2 GiB, or this resource is unlimited.
RLIMIT_CORE
Maximum size of core file. When 0 no core dump files are created. When non-zero, larger dumps are truncated to this size.
RLIMIT_CPU
CPU time limit in seconds. When the process reaches the soft limit, it is sent a SIGXCPU signal. The default action for this signal is to terminate the process. However, the signal can be caught, and the handler can return control to the main program. If the process continues to consume CPU time, it will be sent SIGXCPU once per second until the hard limit is reached, at which time it is sent SIGKILL. (This latter point describes Linux 2.2 through 2.6 behavior. Implementations vary in how they treat processes which continue to consume CPU time after reaching the soft limit. Portable applications that need to catch this signal should perform an orderly termination upon first receipt of SIGXCPU.)
RLIMIT_DATA
The maximum size of the process's data segment (initialized data, uninitialized data, and heap). This limit affects calls to brk(2) and sbrk(2), which fail with the error ENOMEM upon encountering the soft limit of this resource.
RLIMIT_FSIZE
The maximum size of files that the process may create. Attempts to extend a file beyond this limit result in delivery of a SIGXFSZ signal. By default, this signal terminates a process, but a process can catch this signal instead, in which case the relevant system call (e.g., write(2) truncate(2)) fails with the error EFBIG.
RLIMIT_LOCKS (Early Linux 2.4 only)
A limit on the combined number of flock(2) locks and fcntl(2) leases that this process may establish.
RLIMIT_MEMLOCK
The maximum number of bytes of memory that may be locked into RAM. In effect this limit is rounded down to the nearest multiple of the system page size. This limit affects mlock(2) and mlockall(2) and the mmap(2) MAP_LOCKED operation. Since Linux 2.6.9 it also affects the shmctl(2) SHM_LOCK operation, where it sets a maximum on the total bytes in shared memory segments (see shmget(2)) that may be locked by the real user ID of the calling process. The shmctl(2) SHM_LOCK locks are accounted for separately from the per-process memory locks established by mlock(2), mlockall(2), and mmap(2) MAP_LOCKED; a process can lock bytes up to this limit in each of these two categories. In Linux kernels before 2.6.9, this limit controlled the amount of memory that could be locked by a privileged process. Since Linux 2.6.9, no limits are placed on the amount of memory that a privileged process may lock, and this limit instead governs the amount of memory that an unprivileged process may lock.
RLIMIT_MSGQUEUE (Since Linux 2.6.8)
Specifies the limit on the number of bytes that can be allocated for POSIX message queues for the real user ID of the calling process. This limit is enforced for mq_open(3). Each message queue that the user creates counts (until it is removed) against this limit according to the formula:

    bytes = attr.mq_maxmsg * sizeof(struct msg_msg *) +
            attr.mq_maxmsg * attr.mq_msgsize
where attr is the mq_attr structure specified as the fourth argument to mq_open(3).

The first addend in the formula, which includes sizeof(struct msg_msg *) (4 bytes on Linux/x86), ensures that the user cannot create an unlimited number of zero-length messages (such messages nevertheless each consume some system memory for bookkeeping overhead).

RLIMIT_NICE (since kernel 2.6.12, but see BUGS below)
Specifies a ceiling to which the process's nice value can be raised using setpriority(2) or nice(2). The actual ceiling for the nice value is calculated as 20 - rlim_cur. (This strangeness occurs because negative numbers cannot be specified as resource limit values, since they typically have special meanings. For example, RLIM_INFINITY typically is the same as -1.)
RLIMIT_NOFILE
Specifies a value one greater than the maximum file descriptor number that can be opened by this process. Attempts (open(2), pipe(2), dup(2), etc.) to exceed this limit yield the error EMFILE.
RLIMIT_NPROC
The maximum number of processes (or, more precisely on Linux, threads) that can be created for the real user ID of the calling process. Upon encountering this limit, fork(2) fails with the error EAGAIN.
RLIMIT_RSS
Specifies the limit (in pages) of the process's resident set (the number of virtual pages resident in RAM). This limit only has effect in Linux 2.4.x, x < 30, and there only affects calls to madvise(2) specifying MADV_WILLNEED.
RLIMIT_RTPRIO (Since Linux 2.6.12, but see BUGS)
Specifies a ceiling on the real-time priority that may be set for this process using sched_setscheduler(2) and sched_setparam(2).
RLIMIT_SIGPENDING (Since Linux 2.6.8)
Specifies the limit on the number of signals that may be queued for the real user ID of the calling process. Both standard and real-time signals are counted for the purpose of checking this limit. However, the limit is only enforced for sigqueue(2); it is always possible to use kill(2) to queue one instance of any of the signals that are not already queued to the process.
RLIMIT_STACK
The maximum size of the process stack, in bytes. Upon reaching this limit, a SIGSEGV signal is generated. To handle this signal, a process must employ an alternate signal stack (sigaltstack(2)).

RLIMIT_OFILE is the BSD name for RLIMIT_NOFILE.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
rlim points outside the accessible address space.
EINVAL
resource is not valid; or, for setrlimit(): rlim->rlim_cur was greater than rlim->rlim_max.
EPERM
An unprivileged process tried to use setrlimit() to increase a soft or hard limit above the current hard limit; the CAP_SYS_RESOURCE capability is required to do this. Or, the process tried to use setrlimit() to increase the soft or hard RLIMIT_NOFILE limit above the current kernel maximum (NR_OPEN).

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001. RLIMIT_MEMLOCK and RLIMIT_NPROC derive from BSD and are not specified in POSIX.1-2001; they are present on the BSDs and Linux, but on few other implementations. RLIMIT_RSS derives from BSD and is not specified in POSIX.1-2001; it is nevertheless present on most implementations. RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, and RLIMIT_SIGPENDING are Linux specific.

NOTES

A child process created via fork(2) inherits its parents resource limits. Resource limits are preserved across execve(2).

BUGS

In older Linux kernels, the SIGXCPU and SIGKILL signals delivered when a process encountered the soft and hard RLIMIT_CPU limits were delivered one (CPU) second later than they should have been. This was fixed in kernel 2.6.8.

In 2.6.x kernels before 2.6.17, a RLIMIT_CPU limit of 0 is wrongly treated as "no limit" (like RLIM_INFINITY). Since kernel 2.6.17, setting a limit of 0 does have an effect, but is actually treated as a limit of 1 second.

A kernel bug means that RLIMIT_RTPRIO does not work in kernel 2.6.12; the problem is fixed in kernel 2.6.13.

In kernel 2.6.12, there was an off-by-one mismatch between the priority ranges returned by getpriority(2) and RLIMIT_NICE. This had the effect that actual ceiling for the nice value was calculated as 19 - rlim_cur. This was fixed in kernel 2.6.13.

Kernels before 2.4.22 did not diagnose the error EINVAL for setrlimit() when rlim->rlim_cur was greater than rlim->rlim_max.

SEE ALSO

dup(2), fcntl(2), fork(2), getrusage(2), mlock(2), mmap(2), open(2), quotactl(2), sbrk(2), shmctl(2), sigqueue(2), malloc(3), ulimit(3), core(5), capabilities(7), signal(7)


getrusage(2)

GETRUSAGE

Section: Linux Programmer's Manual (2)
Updated: 2004-11-16 Return to Main Contents

NAME

getrusage - get resource usage

SYNOPSIS

#include <sys/time.h>
#include <sys/resource.h>

int getrusage(int who, struct rusage *usage);

DESCRIPTION

getrusage() returns current resource usages, for a who of either RUSAGE_SELF or RUSAGE_CHILDREN. The former asks for resources used by the current process, the latter for resources used by those of its children that have terminated and have been waited for.

struct rusage {
    struct timeval ru_utime; /* user time used */
    struct timeval ru_stime; /* system time used */
    long   ru_maxrss;        /* maximum resident set size */
    long   ru_ixrss;         /* integral shared memory size */
    long   ru_idrss;         /* integral unshared data size */
    long   ru_isrss;         /* integral unshared stack size */
    long   ru_minflt;        /* page reclaims */
    long   ru_majflt;        /* page faults */
    long   ru_nswap;         /* swaps */
    long   ru_inblock;       /* block input operations */
    long   ru_oublock;       /* block output operations */
    long   ru_msgsnd;        /* messages sent */
    long   ru_msgrcv;        /* messages received */
    long   ru_nsignals;      /* signals received */
    long   ru_nvcsw;         /* voluntary context switches */
    long   ru_nivcsw;        /* involuntary context switches */
};

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
usage points outside the accessible address space.
EINVAL
who is invalid.

CONFORMING TO

SVr4, 4.3BSD. POSIX.1-2001 specifies getrusage(), but only specifies the fields ru_utime and ru_stime.

NOTES

Including <sys/time.h> is not required these days, but increases portability. (Indeed, struct timeval is defined in <sys/time.h>.)

In Linux kernel versions before 2.6.9, if the disposition of SIGCHLD is set to SIG_IGN then the resource usages of child processes are automatically included in the value returned by RUSAGE_CHILDREN, although POSIX.1-2001 explicitly prohibits this. This non-conformance is rectified in Linux 2.6.9 and later.

The above struct was taken from 4.3BSD Reno. Not all fields are meaningful under Linux. In linux 2.4 only the fields ru_utime, ru_stime, ru_minflt, and ru_majflt are maintained. Since Linux 2.6, ru_nvcsw and ru_nivcsw are also maintained.

SEE ALSO

getrlimit(2), times(2), wait(2), wait4(2)


getsockopt(2)

GETSOCKOPT

Section: Linux Programmer's Manual (2)
Updated: 1999-05-24 Return to Main Contents

NAME

getsockopt, setsockopt - get and set options on sockets

SYNOPSIS

#include <sys/types.h>

#include <sys/socket.h>

int getsockopt(int s, int level, int optname,
               void *optval, socklen_t *optlen);

int setsockopt(int s, int level, int optname,
               const void *optval, socklen_t optlen);

DESCRIPTION

getsockopt() and setsockopt() manipulate the options associated with a socket. Options may exist at multiple protocol levels; they are always present at the uppermost socket level.

When manipulating socket options the level at which the option resides and the name of the option must be specified. To manipulate options at the socket level, level is specified as SOL_SOCKET. To manipulate options at any other level the protocol number of the appropriate protocol controlling the option is supplied. For example, to indicate that an option is to be interpreted by the TCP protocol, level should be set to the protocol number of TCP; see getprotoent(3).

The parameters optval and optlen are used to access option values for setsockopt(). For getsockopt() they identify a buffer in which the value for the requested option(s) are to be returned. For getsockopt(), optlen is a value-result parameter, initially containing the size of the buffer pointed to by optval, and modified on return to indicate the actual size of the value returned. If no option value is to be supplied or returned, optval may be NULL.

Optname and any specified options are passed uninterpreted to the appropriate protocol module for interpretation. The include file <sys/socket.h> contains definitions for socket level options, described below. Options at other protocol levels vary in format and name; consult the appropriate entries in section 4 of the manual.

Most socket-level options utilize an int parameter for optval. For setsockopt(), the parameter should be non-zero to enable a boolean option, or zero if the option is to be disabled.

For a description of the available socket options see socket(7) and the appropriate protocol man pages.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
The argument s is not a valid descriptor.
EFAULT
The address pointed to by optval is not in a valid part of the process address space. For getsockopt(), this error may also be returned if optlen is not in a valid part of the process address space.
EINVAL
optlen invalid in setsockopt().
ENOPROTOOPT
The option is unknown at the level indicated.
ENOTSOCK
The argument s is a file, not a socket.

CONFORMING TO

SVr4, 4.4BSD (these system calls first appeared in 4.2BSD), POSIX.1-2001.

NOTES

The optlen argument of getsockopt and setsockopt is in reality an int [*] (and this is what 4.x BSD and libc4 and libc5 have). Some POSIX confusion resulted in the present socklen_t, also used by glibc. See also accept(2).

BUGS

Several of the socket options should be handled at lower levels of the system.

SEE ALSO

ioctl(2), socket(2), getprotoent(3), protocols(5), socket(7), tcp(7), unix(7)


getuid(2)

GETUID

Section: Linux Programmer's Manual (2)
Updated: 1993-07-23 Return to Main Contents

NAME

getuid, geteuid - get user identity

SYNOPSIS

#include <unistd.h>
#include <sys/types.h>

uid_t getuid(void);
uid_t geteuid(void);

DESCRIPTION

getuid() returns the real user ID of the current process.

geteuid() returns the effective user ID of the current process.

ERRORS

These functions are always successful.

CONFORMING TO

POSIX.1-2001, 4.3BSD.

NOTES

History

In Unix V6 the getuid() call returned (euid << 8) + uid. Unix V7 introduced separate calls getuid() and geteuid().

SEE ALSO

setreuid(2), setuid(2)


killpg(2)

KILLPG

Section: Linux Programmer's Manual (2)
Updated: 2004-06-21 Return to Main Contents

NAME

killpg - send signal to a process group

SYNOPSIS

#include <signal.h>

int killpg(int pgrp, int sig);

DESCRIPTION

killpg() sends the signal sig to the process group pgrp. See signal(7) for a list of signals. If pgrp is 0, killpg() sends the signal to the sending process's process group.

(POSIX says: If pgrp is less than or equal to 1, the behavior is undefined.)

For a process to have permission to send a signal it must either be privileged (under Linux: have the CAP_KILL capability), or the real or effective user ID of the sending process must equal the real or saved set-user-ID of the target process. In the case of SIGCONT it suffices when the sending and receiving processes belong to the same session.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
Sig is not a valid signal number.
EPERM
The process does not have permission to send the signal to any of the target processes.
ESRCH
No process can be found in the process group specified by pgrp.
ESRCH
The process group was given as 0 but the sending process does not have a process group.

CONFORMING TO

SVr4, 4.4BSD (The killpg() function call first appeared in 4BSD), POSIX.1-2001.

NOTES

There are various differences between the permission checking in BSD-type systems and System V-type systems. See the POSIX rationale for kill(2). A difference not mentioned by POSIX concerns the return value EPERM: BSD documents that no signal is sent and EPERM returned when the permission check failed for at least one target process, while POSIX documents EPERM only when the permission check failed for all target processes.

SEE ALSO

getpgrp(2), kill(2), signal(2), capabilities(7), credentials(7)


lchown (2)

 Continue to this page.


oldfstat (2)

 Continue to this page.


oldolduname (2)

 Continue to this page.


prof (2)

 Continue to this page.


read(2)

READ

Section: Linux Programmer's Manual (2)
Updated: 1997-07-12 Return to Main Contents

NAME

read - read from a file descriptor

SYNOPSIS

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);

DESCRIPTION

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

If count is zero, read() returns zero and has no other results. If count is greater than SSIZE_MAX, the result is unspecified.

RETURN VALUE

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.

ERRORS

EAGAIN
Non-blocking I/O has been selected using O_NONBLOCK and no data was immediately available for reading.
EBADF
fd is not a valid file descriptor or is not open for reading.
EFAULT
buf is outside your accessible address space.
EINTR
The call was interrupted by a signal before any data was read.
EINVAL
fd is attached to an object which is unsuitable for reading; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the current file offset is not suitably aligned.
EIO
I/O error. This will happen for example when the process is in a background process group, tries to read from its controlling tty, and either it is ignoring or blocking SIGTTIN or its process group is orphaned. It may also occur when there is a low-level I/O error while reading from a disk or tape.
EISDIR
fd refers to a directory.

Other errors may occur, depending on the object connected to fd. POSIX allows a read() that is interrupted after reading some data to return -1 (with errno set to EINTR) or to return the number of bytes already read.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

On NFS file systems, reading small amounts of data will only update the time stamp the first time, subsequent calls may not do so. This is caused by client side attribute caching, because most if not all NFS clients leave st_atime (last file access time) updates to the server and client side reads satisfied from the client's cache will not cause st_atime updates on the server as there are no server side reads. UNIX semantics can be obtained by disabling client side attribute caching, but in most situations this will substantially increase server load and decrease performance.

Many filesystems and disks were considered to be fast enough that the implementation of O_NONBLOCK was deemed unnecessary. So, O_NONBLOCK may not be available on files and/or disks.

SEE ALSO

close(2), fcntl(2), ioctl(2), lseek(2), open(2), pread(2), readdir(2), readlink(2), readv(2), select(2), write(2), fread(3)


recvfrom (2)

 Continue to this page.


sched_get_priority_min (2)

 Continue to this page.


sched_getparam (2)

 Continue to this page.


setuid(2)

SETUID

Section: Linux Programmer's Manual (2)
Updated: 2004-05-27 Return to Main Contents

NAME

setuid - set user identity

SYNOPSIS

#include <sys/types.h>
#include <unistd.h>

int setuid(uid_t uid);

DESCRIPTION

setuid() sets the effective user ID of the current process. If the effective UID of the caller is root, the real UID and saved set-user-ID are also set.

Under Linux, setuid() is implemented like the POSIX version with the _POSIX_SAVED_IDS feature. This allows a set-user-ID (other than root) program to drop all of its user privileges, do some un-privileged work, and then re-engage the original effective user ID in a secure manner.

If the user is root or the program is set-user-ID-root, special care must be taken. The setuid() function checks the effective user ID of the caller and if it is the superuser, all process-related user ID's are set to uid. After this has occurred, it is impossible for the program to regain root privileges.

Thus, a set-user-ID-root program wishing to temporarily drop root privileges, assume the identity of a non-root user, and then regain root privileges afterwards cannot use setuid(). You can accomplish this with the (non-POSIX, BSD) call seteuid(2).

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EAGAIN
The uid does not match the current uid and uid brings process over its NPROC rlimit.
EPERM
The user is not privileged (Linux: does not have the CAP_SETUID capability) and uid does not match the real UID or saved set-user-ID of the calling process.

CONFORMING TO

SVr4, POSIX.1-2001. Not quite compatible with the 4.4BSD call, which sets all of the real, saved, and effective user IDs.

NOTES

Linux Notes

Linux has the concept of filesystem user ID, normally equal to the effective user ID. The setuid() call also sets the filesystem user ID of the current process. See setfsuid(2).

If uid is different from the old effective uid, the process will be forbidden from leaving core dumps.

SEE ALSO

getuid(2), seteuid(2), setfsuid(2), setreuid(2), capabilities(7), credentials(7)


sigprocmask(2)

SIGPROCMASK

Section: Linux Programmer's Manual (2)
Updated: 2005-09-15 Return to Main Contents

NAME

sigprocmask - examine and change blocked signals

SYNOPSIS

#include <signal.h>

int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);

DESCRIPTION

sigprocmask() is used to change the signal mask, the set of currently blocked signals. The behavior of the call is dependent on the value of how, as follows.
SIG_BLOCK
The set of blocked signals is the union of the current set and the set argument.
SIG_UNBLOCK
The signals in set are removed from the current set of blocked signals. It is legal to attempt to unblock a signal which is not blocked.
SIG_SETMASK
The set of blocked signals is set to the argument set.

If oldset is non-null, the previous value of the signal mask is stored in oldset.

If set is NULL, then the signal mask is unchanged (i.e., how is ignored), but the current value of the signal mask is nevertheless returned in oldset (it is not NULL).

The use of sigprocmask() is unspecified in a multithreaded process; see pthread_sigmask(3).

RETURN VALUE

sigprocmask() returns 0 on success and -1 on error.

ERRORS

EINVAL The value specified in how was invalid.

CONFORMING TO

POSIX.1-2001.

NOTES

It is not possible to block SIGKILL or SIGSTOP. Attempts to do so are silently ignored.

If SIGBUS, SIGFPE, SIGILL, or SIGSEGV are generated while they are blocked, the result is undefined, unless the signal was generated by the kill(2), sigqueue(2), or raise(3).

See sigsetops(3) for details on manipulating signal sets.

SEE ALSO

kill(2), pause(2), sigaction(2), signal(2), sigpending(2), sigprocmask(2), sigqueue(2), sigsuspend(2), pthread_sigmask(3), sigsetops(3), signal(7)


ssetmask (2)

 Continue to this page.


capget(2)

CAPGET

Section: Linux Programmer's Manual (2)
Updated: 2004-06-21 Return to Main Contents

NAME

capget, capset - set/get capabilities

SYNOPSIS

#undef _POSIX_SOURCE
#include <sys/capability.h>

int capget(cap_user_header_t hdrp, cap_user_data_t datap);

int capset(cap_user_header_t hdrp, const cap_user_data_t datap);

DESCRIPTION

As of Linux 2.2, the power of the superuser (root) has been partitioned into a set of discrete capabilities. Every thread has a set of effective capabilities identifying which capabilities (if any) it may currently exercise. Every thread also has a set of inheritable capabilities that may be passed through an execve(2) call, and a set of permitted capabilities that it can make effective or inheritable.

These two functions are the raw kernel interface for getting and setting capabilities. Not only are these system calls specific to Linux, but the kernel API is likely to change and use of these functions (in particular the format of the cap_user_*_t types) is subject to change with each kernel revision.

The portable interfaces are cap_set_proc(3) and cap_get_proc(3); if possible you should use those interfaces in applications. If you wish to use the Linux extensions in applications, you should use the easier-to-use interfaces capsetp(3) and capgetp(3).

Current details

Now that you have been warned, some current kernel details. The structs are defined as follows.

#define _LINUX_CAPABILITY_VERSION  0x19980330

typedef struct __user_cap_header_struct {
    int version;
    int pid;
} *cap_user_header_t;

typedef struct __user_cap_data_struct {
    int effective;
    int permitted;
    int inheritable;
} *cap_user_data_t;

The calls will return EINVAL, and set the version field of hdr to _LINUX_CAPABILITY_VERSION when another version was specified.

The calls operate on the capabilities of the thread specified by the pid field of hdr when that is non-zero, or on the capabilities of the calling thread if pid is 0. If pid refers to a single-threaded process, then pid can be specified as a traditional process ID; operating on a thread of a multithreaded process requires a thread ID of the type returned by gettid(2). For capset(), pid can also be: -1, meaning perform the change on all threads except the caller and init(8); or a value less than -1, in which case the change is applied to all members of the process group whose ID is -pid.

For details on the data, see capabilities(7).

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
Bad memory address. Neither of hdrp and datap may be NULL.
EINVAL
One of the arguments was invalid.
EPERM
An attempt was made to add a capability to the Permitted set, or to set a capability in the Effective or Inheritable sets that is not in the Permitted set.
EPERM
The caller attempted to use capset() to modify the capabilities of a thread other than itself, but lacked sufficient privilege; the CAP_SETPCAP capability is required. (A bug in kernels before 2.6.11 meant that this error could also occur if a thread without this capability tried to change its own capabilities by specifying the pid field as a non-zero value (i.e., the value returned by getpid(2)) instead of 0.)
ESRCH
No such thread.

CONFORMING TO

These system calls are Linux specific.

NOTES

The portable interface to the capability querying and setting functions is provided by the libcap library and is available from here:
ftp://ftp.kernel.org/pub/linux/libs/security/linux-privs

SEE ALSO

clone(2), gettid(2), capabilities(7)


capset (2)

 Continue to this page.


pivot_root(2)

PIVOT_ROOT

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

pivot_root - change the root file system

SYNOPSIS

int pivot_root(const char *new_root, const char *put_old);

DESCRIPTION

pivot_root() moves the root file system of the current process to the directory put_old and makes new_root the new root file system of the current process.

The typical use of pivot_root() is during system startup, when the system mounts a temporary root file system (e.g., an initrd), then mounts the real root file system, and eventually turns the latter into the current root of all relevant processes or threads.

pivot_root() may or may not change the current root and the current working directory (cwd) of any processes or threads which use the old root directory. The caller of pivot_root() must ensure that processes with root or cwd at the old root operate correctly in either case. An easy way to ensure this is to change their root and cwd to new_root before invoking pivot_root().

The paragraph above is intentionally vague because the implementation of pivot_root() may change in the future. At the time of writing, pivot_root() changes root and cwd of each process or thread to new_root if they point to the old root directory. This is necessary in order to prevent kernel threads from keeping the old root directory busy with their root and cwd, even if they never access the file system in any way. In the future, there may be a mechanism for kernel threads to explicitly relinquish any access to the file system, such that this fairly intrusive mechanism can be removed from pivot_root().

Note that this also applies to the current process: pivot_root() may or may not affect its cwd. It is therefore recommended to call chdir("/") immediately after pivot_root().

The following restrictions apply to new_root and put_old:

-
They must be directories.
-
new_root and put_old must not be on the same file system as the current root.
-
put_old must be underneath new_root, that is, adding a non-zero number of /.. to the string pointed to by put_old must yield the same directory as new_root.
-
No other file system may be mounted on put_old.

See also pivot_root(8) for additional usage examples.

If the current root is not a mount point (e.g., after chroot(2) or pivot_root(), see also below), not the old root directory, but the mount point of that file system is mounted on put_old.

new_root does not have to be a mount point. In this case, /proc/mounts will show the mount point of the file system containing new_root as root (/).

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

pivot_root() may return (in errno) any of the errors returned by stat(2). Additionally, it may return:
EBUSY
new_root or put_old are on the current root file system, or a file system is already mounted on put_old.
EINVAL
put_old is not underneath new_root.
ENOTDIR
new_root or put_old is not a directory.
EPERM
The current process does not have the CAP_SYS_ADMIN capability.

VERSIONS

pivot_root() was introduced in Linux 2.3.41.

CONFORMING TO

pivot_root() is Linux specific and hence is not portable.

BUGS

pivot_root() should not have to change root and cwd of all other processes in the system.

Some of the more obscure uses of pivot_root() may quickly lead to insanity.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

SEE ALSO

chdir(2), chroot(2), stat(2), initrd(4), pivot_root(8)


mincore(2)

MINCORE

Section: Linux Programmer's Manual (2)
Updated: 2007-01-08 Return to Main Contents

NAME

mincore - determine whether pages are resident in memory

SYNOPSIS

#include <unistd.h>
#include <sys/mman.h>

int mincore(void *start, size_t length, unsigned char *vec);

DESCRIPTION

mincore() returns a vector that indicates whether pages of the calling process's virtual memory are resident in core (RAM), and so will not cause a disk access (page fault) if referenced. The kernel returns residency information about the pages starting at the address start, and continuing for length bytes.

The start argument must be a multiple of the system page size. The length argument need not be a multiple of the page size, but since residency information is returned for whole pages, length is effectively rounded up to the next multiple of the page size. One may obtain the page size (PAGE_SIZE) using sysconf(_SC_PAGESIZE).

The vec argument must point to an array containing at least (length+PAGE_SIZE-1) / PAGE_SIZE bytes. On return, the least significant bit of each byte will be set if the corresponding page is currently resident in memory, and be clear otherwise. (The settings of the other bits in each byte are undefined; these bits are reserved for possible later use.) Of course the information returned in vec is only a snapshot: pages that are not locked in memory can come and go at any moment, and the contents of vec may already be stale by the time this call returns.

RETURN VALUE

On success, mincore() returns zero. On error, -1 is returned, and errno is set appropriately.

ERRORS

EAGAIN kernel is temporarily out of resources.
EFAULT
vec points to an invalid address.
EINVAL
start is not a multiple of the page size.
ENOMEM
length is greater than (TASK_SIZE - start). (This could occur if a negative value is specified for length, since that value will be interpreted as a large unsigned integer.) In Linux 2.6.11 and earlier, the error EINVAL was returned for this condition.
ENOMEM
start to start + length contained unmapped memory.

VERSIONS

Available since Linux 2.3.99pre1 and glibc 2.2.

CONFORMING TO

mincore() is not specified in POSIX.1-2001, and it is not available on all Unix implementations.

BUGS

Before kernel 2.6.21, mincore() did not return correct information for MAP_PRIVATE mappings, or for non-linear mappings (established using remap_file_pages(2)).

SEE ALSO

mlock(2), mmap(2)


pselect (2)

 Continue to this page.


madvise(2)

MADVISE

Section: Linux Programmer's Manual (2)
Updated: 2001-06-10 Return to Main Contents

NAME

madvise - give advice about use of memory

SYNOPSIS

#include <sys/mman.h>

int madvise(void *start, size_t length, int advice);

DESCRIPTION

The madvise() system call advises the kernel about how to handle paging input/output in the address range beginning at address start and with size length bytes. It allows an application to tell the kernel how it expects to use some mapped or shared memory areas, so that the kernel can choose appropriate read-ahead and caching techniques. This call does not influence the semantics of the application (except in the case of MADV_DONTNEED), but may influence its performance. The kernel is free to ignore the advice.

The advice is indicated in the advice parameter which can be

MADV_NORMAL
No special treatment. This is the default.
MADV_RANDOM
Expect page references in random order. (Hence, read ahead may be less useful than normally.)
MADV_SEQUENTIAL
Expect page references in sequential order. (Hence, pages in the given range can be aggressively read ahead, and may be freed soon after they are accessed.)
MADV_WILLNEED
Expect access in the near future. (Hence, it might be a good idea to read some pages ahead.)
MADV_DONTNEED
Do not expect access in the near future. (For the time being, the application is finished with the given range, so the kernel can free resources associated with it.) Subsequent accesses of pages in this range will succeed, but will result either in re-loading of the memory contents from the underlying mapped file (see mmap(2)) or zero-fill-on-demand pages for mappings without an underlying file.
MADV_REMOVE (Since Linux 2.6.16)
Free up a given range of pages and its associated backing store. Currently, only shmfs/tmpfs supports this; other filesystems return -ENOSYS.
MADV_DONTFORK (Since Linux 2.6.16)
Do not make the pages in this range available to the child after a fork(2). This is useful to prevent copy-on-write semantics from changing the physical location of a pagei(s) if the parent writes to it after a fork(2). (Such page relocations cause problems for hardware that DMAs into the page(s).)
MADV_DOFORK (Since Linux 2.6.16)
Undo the effect of MADV_DONTFORK, restoring the default behavior, whereby a mapping is inherited across fork(2).

RETURN VALUE

On success madvise() returns zero. On error, it returns -1 and errno is set appropriately.

ERRORS

EAGAIN
A kernel resource was temporarily unavailable.
EBADF
The map exists, but the area maps something that isn't a file.
EINVAL
The value len is negative, start is not page-aligned, advice is not a valid value, or the application is attempting to release locked or shared pages (with MADV_DONTNEED).
EIO
(for MADV_WILLNEED) Paging in this area would exceed the process's maximum resident set size.
ENOMEM
(for MADV_WILLNEED) Not enough memory: paging in failed.
ENOMEM
Addresses in the specified range are not currently mapped, or are outside the address space of the process.

CONFORMING TO

POSIX.1b. POSIX.1-2001 describes posix_madvise(3) with constants POSIX_MADV_NORMAL, etc., with a behavior close to that described here. There is a similar posix_fadvise(3) for file access.

MADV_REMOVE, MADV_DONTFORK, and MADV_DOFORK are Linux specific.

NOTES

Linux Notes

The current Linux implementation (2.4.0) views this system call more as a command than as advice and hence may return an error when it cannot do what it usually would do in response to this advice. (See the ERRORS description above.) This is nonstandard behavior.

The Linux implementation requires that the address start be page-aligned, and allows length to be zero. If there are some parts of the specified address range that are not mapped, the Linux version of madvise() ignores them and applies the call to the rest (but returns ENOMEM from the system call, as it should).

SEE ALSO

getrlimit(2), mincore(2), mmap(2), mprotect(2), msync(2), munmap(2)


sigaltstack(2)

SIGALTSTACK

Section: Linux Programmer's Manual (2)
Updated: 2001-09-27 Return to Main Contents

NAME

sigaltstack - set and/or get signal stack context

SYNOPSIS

#include <signal.h>

int sigaltstack(const stack_t *ss, stack_t *oss);

DESCRIPTION

sigaltstack() allows a process to define a new alternate signal stack and/or retrieve the state of an existing alternate signal stack. An alternate signal stack is used during the execution of a signal handler if the establishment of that handler (see sigaction(2)) requested it.

The normal sequence of events for using an alternate signal stack is the following:

1.
Allocate an area of memory to be used for the alternate signal stack.
2.
Use sigaltstack() to inform the system of the existence and location of the alternate signal stack.
3.
When establishing a signal handler using sigaction(2), inform the system that the signal handler should be executed on the alternate signal stack by specifying the SA_ONSTACK flag. The ss argument is used to specify a new alternate signal stack, while the oss argument is used to retrieve information about the currently established signal stack. If we are interested in performing just one of these tasks then the other argument can be specified as NULL. Each of these arguments is a structure of the following type:

typedef struct {
    void  *ss_sp;     /* Base address of stack */
    int    ss_flags;  /* Flags */
    size_t ss_size;   /* Number of bytes in stack */
} stack_t;

To establish a new alternate signal stack, ss.ss_flags is set to zero, and ss.ss_sp and ss.ss_size specify the starting address and size of the stack. The constant SIGSTKSZ is defined to be large enough to cover the usual size requirements for an alternate signal stack, and the constant MINSIGSTKSZ defines the minimum size required to execute a signal handler.

When a signal handler is invoked on the alternate stack, the kernel automatically aligns the address given in ss.ss_sp to a suitable address boundary for the underlying hardware architecture.

To disable an existing stack, specify ss.ss_flags as SS_DISABLE. In this case, the remaining fields in ss are ignored.

If oss is not NULL, then it is used to return information about the alternate signal stack which was in effect prior to the call to sigaltstack(). The oss.ss_sp and oss.ss_size fields return the starting address and size of that stack. The oss.ss_flags may return either of the following values:

SS_ONSTACK
The process is currently executing on the alternate signal stack. (Note that it is not possible to change the alternate signal stack if the process is currently executing on it.)
SS_DISABLE
The alternate signal stack is currently disabled.

RETURN VALUE

sigaltstack() returns 0 on success, or -1 on failure with errno set to indicate the error.

ERRORS

EFAULT
Either ss or oss is not NULL and points to an area outside of the process's address space.
EINVAL
ss is not NULL and the ss_flags field contains a non-zero value other than SS_DISABLE.
ENOMEM
The specified size of the new alternate signal stack (ss.ss_size) was less than MINSTKSZ.
EPERM
An attempt was made to change the alternate signal stack while it was active (i.e., the process was already executing on the current alternate signal stack).

CONFORMING TO

SUSv2, SVr4, POSIX.1-2001.

NOTES

The most common usage of an alternate signal stack is to handle the SIGSEGV signal that is generated if the space available for the normal process stack is exhausted: in this case, a signal handler for SIGSEGV cannot be invoked on the process stack; if we wish to handle it, we must use an alternate signal stack. Establishing an alternate signal stack is useful if a process expects that it may exhaust its standard stack. This may occur, for example, because the stack grows so large that it encounters the upwardly growing heap, or it reaches a limit established by a call to setrlimit(RLIMIT_STACK, &rlim). If the standard stack is exhausted, the kernel sends the process a SIGSEGV signal. In these circumstances the only way to catch this signal is on an alternate signal stack. On most hardware architectures supported by Linux, stacks grow downwards. sigaltstack() automatically takes account of the direction of stack growth. Functions called from a signal handler executing on an alternate signal stack will also use the alternate signal stack. (This also applies to any handlers invoked for other signals while the process is executing on the alternate signal stack.) Unlike the standard stack, the system does not automatically extend the alternate signal stack. Exceeding the allocated size of the alternate signal stack will lead to unpredictable results. A successful call to execve(2) removes any existing alternate signal stack. sigaltstack() supersedes the older sigstack() call. For backwards compatibility, glibc also provides sigstack(). All new applications should be written using sigaltstack().

History

4.2BSD had a sigstack() system call. It used a slightly different struct, and had the major disadvantage that the caller had to know the direction of stack growth.

EXAMPLE

The following code segment demonstrates the use of sigaltstack():

stack_t ss;

ss.ss_sp = malloc(SIGSTKSZ);
if (ss.ss_sp == NULL)
    /* Handle error */;
ss.ss_size = SIGSTKSZ;
ss.ss_flags = 0;
if (sigaltstack(&ss, NULL) == -1)
    /* Handle error */;

SEE ALSO

execve(2), setrlimit(2), sigaction(2), siglongjmp(3), sigsetjmp(3), signal(7)


setcontext (2)

 Continue to this page.


getcontext(2)

GETCONTEXT

Section: Linux Programmer's Manual (2)
Updated: 2001-11-15 Return to Main Contents

NAME

getcontext, setcontext - get or set the user context

SYNOPSIS

#include <ucontext.h>

int getcontext(ucontext_t *ucp);
int setcontext(const ucontext_t *ucp);

DESCRIPTION

In a System V-like environment, one has the two types mcontext_t and ucontext_t defined in <ucontext.h> and the four functions getcontext(), setcontext(), makecontext(3) and swapcontext(3) that allow user-level context switching between multiple threads of control within a process.

The mcontext_t type is machine-dependent and opaque. The ucontext_t type is a structure that has at least the following fields:

typedef struct ucontext {
    struct ucontext *uc_link;
    sigset_t         uc_sigmask;
    stack_t          uc_stack;
    mcontext_t       uc_mcontext;
    ...
} ucontext_t;
with sigset_t and stack_t defined in <signal.h>. Here uc_link points to the context that will be resumed when the current context terminates (in case the current context was created using makecontext(3)), uc_sigmask is the set of signals blocked in this context (see sigprocmask(2)), uc_stack is the stack used by this context (see sigaltstack(2)), and uc_mcontext is the machine-specific representation of the saved context, that includes the calling thread's machine registers.

The function getcontext() initializes the structure pointed at by ucp to the currently active context.

The function setcontext() restores the user context pointed at by ucp. A successful call does not return. The context should have been obtained by a call of getcontext(), or makecontext(3), or passed as third argument to a signal handler.

If the context was obtained by a call of getcontext(), program execution continues as if this call just returned.

If the context was obtained by a call of makecontext(3), program execution continues by a call to the function func specified as the second argument of that call to makecontext(3). When the function func returns, we continue with the uc_link member of the structure ucp specified as the first argument of that call to makecontext(3). When this member is NULL, the thread exits.

If the context was obtained by a call to a signal handler, then old standard text says that "program execution continues with the program instruction following the instruction interrupted by the signal". However, this sentence was removed in SUSv2, and the present verdict is "the result is unspecified".

RETURN VALUE

When successful, getcontext() returns 0 and setcontext() does not return. On error, both return -1 and set errno appropriately.

ERRORS

None defined.

CONFORMING TO

SUSv2, POSIX.1-2001.

NOTES

The earliest incarnation of this mechanism was the setjmp(3)/longjmp(3) mechanism. Since that does not define the handling of the signal context, the next stage was the sigsetjmp(3)/siglongjmp(3) pair. The present mechanism gives much more control. On the other hand, there is no easy way to detect whether a return from getcontext() is from the first call, or via a setcontext() call. The user has to invent her own bookkeeping device, and a register variable won't do since registers are restored.

When a signal occurs, the current user context is saved and a new context is created by the kernel for the signal handler. Do not leave the handler using longjmp(3): it is undefined what would happen with contexts. Use siglongjmp(3) or setcontext() instead.

SEE ALSO

sigaction(2), sigaltstack(2), sigprocmask(2), longjmp(3), makecontext(3), sigsetjmp(3)


pwrite (2)

 Continue to this page.


outb_p (2)

 Continue to this page.


outl (2)

 Continue to this page.


outl_p (2)

 Continue to this page.


outsb (2)

 Continue to this page.


outsl (2)

 Continue to this page.


outsw (2)

 Continue to this page.


outw (2)

 Continue to this page.


outw_p (2)

 Continue to this page.


inb (2)

 Continue to this page.


inb_p (2)

 Continue to this page.


inl (2)

 Continue to this page.


inl_p (2)

 Continue to this page.


insb (2)

 Continue to this page.


insl (2)

 Continue to this page.


insw (2)

 Continue to this page.


inw (2)

 Continue to this page.


inw_p (2)

 Continue to this page.


select_tut(2)

SELECT_TUT

Section: Linux Programmer's Manual (2)
Updated: 2006-05-13 Return to Main Contents

NAME

select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing

SYNOPSIS

/* According to POSIX.1-2001 */

#include <sys/select.h>

/* According to earlier standards */

#include <sys/time.h>

#include <sys/types.h>

#include <unistd.h>

int select(int nfds, fd_set *readfds, fd_set *writefds,
           fd_set *exceptfds, struct timeval *timeout);

void FD_CLR(int fd, fd_set *set);

int  FD_ISSET(int fd, fd_set *set);

void FD_SET(int fd, fd_set *set);

void FD_ZERO(fd_set *set);

#define _XOPEN_SOURCE 600
#include <sys/select.h>

int pselect(int nfds, fd_set *readfds, fd_set *writefds,
            fd_set *exceptfds, const struct timespec *timeout,
            const sigset_t *sigmask);

DESCRIPTION

select() (or pselect()) is the pivot function of most C programs that handle more than one simultaneous file descriptor (or socket handle) in an efficient manner. Its principal arguments are three arrays of file descriptors: readfds, writefds, and exceptfds. The way that select() is usually used is to block while waiting for a "change of status" on one or more of the file descriptors. A "change of status" is when more characters become available from the file descriptor, or when space becomes available within the kernel's internal buffers for more to be written to the file descriptor, or when a file descriptor goes into error (in the case of a socket or pipe this is when the other end of the connection is closed).

In summary, select() just watches multiple file descriptors, and is the standard Unix call to do so.

The arrays of file descriptors are called file descriptor sets. Each set is declared as type fd_set, and its contents can be altered with the macros FD_CLR(), FD_ISSET(), FD_SET(), and FD_ZERO(). FD_ZERO() is usually the first function to be used on a newly declared set. Thereafter, the individual file descriptors that you are interested in can be added one by one with FD_SET(). select() modifies the contents of the sets according to the rules described below; after calling select() you can test if your file descriptor is still present in the set with the FD_ISSET() macro. FD_ISSET() returns non-zero if the descriptor is present and zero if it is not. FD_CLR() removes a file descriptor from the set.

Arguments

readfds
This set is watched to see if data is available for reading from any of its file descriptors. After select() has returned, readfds will be cleared of all file descriptors except for those file descriptors that are immediately available for reading with a recv(2) (for sockets) or read(2) (for pipes, files, and sockets) call.
writefds
This set is watched to see if there is space to write data to any of its file descriptors. After select() has returned, writefds will be cleared of all file descriptors except for those file descriptors that are immediately available for writing with a send(2) (for sockets) or write(2) (for pipes, files, and sockets) call.
exceptfds
This set is watched for exceptions or errors on any of the file descriptors. However, that is actually just a rumor. How you use exceptfds is to watch for out-of-band (OOB) data. OOB data is data sent on a socket using the MSG_OOB flag, and hence exceptfds only really applies to sockets. See recv(2) and send(2) about this. After select() has returned, exceptfds will be cleared of all file descriptors except for those descriptors that are available for reading OOB data. You can only ever read one byte of OOB data though (which is done with recv(2)), and writing OOB data (done with send(2)) can be done at any time and will not block. Hence there is no need for a fourth set to check if a socket is available for writing OOB data.
nfds
This is an integer one more than the maximum of any file descriptor in any of the sets. In other words, while you are busy adding file descriptors to your sets, you must calculate the maximum integer value of all of them, then increment this value by one, and then pass this as nfds to select().
utimeout
This is the longest time select() must wait before returning, even if nothing interesting happened. If this value is passed as NULL, then select() blocks indefinitely waiting for an event. utimeout can be set to zero seconds, which causes select() to return immediately. The structure struct timeval is defined as,

struct timeval {
    time_t tv_sec;    /* seconds */
    long tv_usec;     /* microseconds */
};
ntimeout
This argument has the same meaning as utimeout but struct timespec has nanosecond precision as follows,

struct timespec {
    long tv_sec;    /* seconds */
    long tv_nsec;   /* nanoseconds */
};
sigmask
This argument holds a set of signals to allow while performing a pselect() call (see sigaddset(3) and sigprocmask(2)). It can be passed as NULL, in which case it does not modify the set of allowed signals on entry and exit to the function. It will then behave just like select().

Combining Signal and Data Events

pselect() must be used if you are waiting for a signal as well as data from a file descriptor. Programs that receive signals as events normally use the signal handler only to raise a global flag. The global flag will indicate that the event must be processed in the main loop of the program. A signal will cause the select() (or pselect()) call to return with errno set to EINTR. This behavior is essential so that signals can be processed in the main loop of the program, otherwise select() would block indefinitely. Now, somewhere in the main loop will be a conditional to check the global flag. So we must ask: what if a signal arrives after the conditional, but before the select() call? The answer is that select() would block indefinitely, even though an event is actually pending. This race condition is solved by the pselect() call. This call can be used to mask out signals that are not to be received except within the pselect() call. For instance, let us say that the event in question was the exit of a child process. Before the start of the main loop, we would block SIGCHLD using sigprocmask(2). Our pselect() call would enable SIGCHLD by using the virgin signal mask. Our program would look like:

int child_events = 0;

void
child_sig_handler(int x)
{
    child_events++;
    signal(SIGCHLD, child_sig_handler);
}

int
main(int argc, char **argv)
{
    sigset_t sigmask, orig_sigmask;

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &sigmask, &orig_sigmask);

    signal(SIGCHLD, child_sig_handler);

    for (;;) { /* main loop */
        for (; child_events > 0; child_events--) {
            /* do event work here */
        }
        r = pselect(nfds, &rd, &wr, &er, 0, &orig_sigmask);

        /* main body of program */
    }
}

Practical

So what is the point of select()? Can't I just read and write to my descriptors whenever I want? The point of select() is that it watches multiple descriptors at the same time and properly puts the process to sleep if there is no activity. It does this while enabling you to handle multiple simultaneous pipes and sockets. Unix programmers often find themselves in a position where they have to handle I/O from more than one file descriptor where the data flow may be intermittent. If you were to merely create a sequence of read(2) and write(2) calls, you would find that one of your calls may block waiting for data from/to a file descriptor, while another file descriptor is unused though available for data. select() efficiently copes with this situation.

A simple example of the use of select() can be found in the select(2) manual page.

Select Law

Many people who try to use select() come across behavior that is difficult to understand and produces non-portable or borderline results. For instance, the above program is carefully written not to block at any point, even though it does not set its file descriptors to non-blocking mode at all (see ioctl(2)). It is easy to introduce subtle errors that will remove the advantage of using select(), hence I will present a list of essentials to watch for when using the select() call.
1.
You should always try to use select() without a timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and is difficult to debug.
2.
The value nfds must be properly calculated for efficiency as explained above.
3.
No file descriptor must be added to any set if you do not intend to check its result after the select() call, and respond appropriately. See next rule.
4.
After select() returns, all file descriptors in all sets should be checked to see if they are ready.
5.
The functions read(2), recv(2), write(2), and send(2) do not necessarily read/write the full amount of data that you have requested. If they do read/write the full amount, its because you have a low traffic load and a fast stream. This is not always going to be the case. You should cope with the case of your functions only managing to send or receive a single byte.
6.
Never read/write only in single bytes at a time unless your are really sure that you have a small amount of data to process. It is extremely inefficient not to read/write as much data as you can buffer each time. The buffers in the example above are 1024 bytes although they could easily be made larger.
7.
The functions read(2), recv(2), write(2), and send(2) as well as the select() call can return -1 with errno set to EINTR, or with errno set to EAGAIN (EWOULDBLOCK). These results must be properly managed (not done properly above). If your program is not going to receive any signals then it is unlikely you will get EINTR. If your program does not set non-blocking I/O, you will not get EAGAIN. Nonetheless you should still cope with these errors for completeness.
8.
Never call read(2), recv(2), write(2), or send(2) with a buffer length of zero.
9.
If the functions read(2), recv(2), write(2), and send(2) fail with errors other than those listed in 7., or one of the input functions returns 0, indicating end of file, then you should not pass that descriptor to select() again. In the above example, I close the descriptor immediately, and then set it to -1 to prevent it being included in a set.
10.
The timeout value must be initialized with each new call to select(), since some operating systems modify the structure. pselect() however does not modify its timeout structure.
11.
I have heard that the Windows socket layer does not cope with OOB data properly. It also does not cope with select() calls when no file descriptors are set at all. Having no file descriptors set is a useful way to sleep the process with sub-second precision by using the timeout. (See further on.)

Usleep Emulation

On systems that do not have a usleep(3) function, you can call select() with a finite timeout and no file descriptors as follows:

    struct timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = 200000;  /* 0.2 seconds */
    select(0, NULL, NULL, NULL, &tv);

This is only guaranteed to work on Unix systems, however.

RETURN VALUE

On success, select() returns the total number of file descriptors still present in the file descriptor sets.

If select() timed out, then the return value will be zero. The file descriptors set should be all empty (but may not be on some systems).

A return value of -1 indicates an error, with errno being set appropriately. In the case of an error, the returned sets and the timeout struct contents are undefined and should not be used. pselect() however never modifies ntimeout.

NOTES

Generally speaking, all operating systems that support sockets, also support select(). Many types of programs become extremely complicated without the use of select(). select() can be used to solve many problems in a portable and efficient way that naive programmers try to solve in a more complicated manner using threads, forking, IPCs, signals, memory sharing, and so on.

The poll(2) system call has the same functionality as select(), and is somewhat more efficient when monitoring sparse file descriptor sets. It is nowadays widely available, but historically was less portable than select().

The Linux-specific epoll(7) API provides an interface that is more efficient than select(2) and poll(2) when monitoring large numbers of file descriptors.

EXAMPLE

Here is an example that better demonstrates the true utility of select(). The listing below is a TCP forwarding program that forwards from one TCP port to another.

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

static int forward_port;

#undef max
#define max(x,y) ((x) > (y) ? (x) : (y))

static int
listen_socket(int listen_port)
{
    struct sockaddr_in a;
    int s;
    int yes;
    if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        return -1;
    }
    yes = 1;
    if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
            (char *) &yes, sizeof(yes)) < 0) {
        perror("setsockopt");
        close(s);
        return -1;
    }
    memset(&a, 0, sizeof(a));
    a.sin_port = htons(listen_port);
    a.sin_family = AF_INET;
    if (bind(s, (struct sockaddr *) &a, sizeof(a)) < 0) {
        perror("bind");
        close(s);
        return -1;
    }
    printf("accepting connections on port %d\n", listen_port);
    listen(s, 10);
    return s;
}

static int
connect_socket(int connect_port, char *address)
{
    struct sockaddr_in a;
    int s;
    if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        close(s);
        return -1;
    }

    memset(&a, 0, sizeof(a));
    a.sin_port = htons(connect_port);
    a.sin_family = AF_INET;

    if (!inet_aton(address, (struct in_addr *) &a.sin_addr.s_addr)) {
        perror("bad IP address format");
        close(s);
        return -1;
    }

    if (connect(s, (struct sockaddr *) &a, sizeof(a)) < 0) {
        perror("connect()");
        shutdown(s, SHUT_RDWR);
        close(s);
        return -1;
    }
    return s;
}

#define SHUT_FD1 {                      \
        if (fd1 >= 0) {                 \
            shutdown(fd1, SHUT_RDWR);   \
            close(fd1);                 \
            fd1 = -1;                   \
        }                               \
    }

#define SHUT_FD2 {                      \
        if (fd2 >= 0) {                 \
            shutdown(fd2, SHUT_RDWR);   \
            close(fd2);                 \
            fd2 = -1;                   \
        }                               \
    }

#define BUF_SIZE 1024

int
main(int argc, char **argv)
{
    int h;
    int fd1 = -1, fd2 = -1;
    char buf1[BUF_SIZE], buf2[BUF_SIZE];
    int buf1_avail, buf1_written;
    int buf2_avail, buf2_written;

    if (argc != 4) {
        fprintf(stderr,
                 "Usage\n\tfwd <listen-port> "
                 "<forward-to-port> <forward-to-ip-address>\n");
        exit(EXIT_FAILURE);
    }

    signal(SIGPIPE, SIG_IGN);

    forward_port = atoi(argv[2]);

    h = listen_socket(atoi(argv[1]));
    if (h < 0)
        exit(EXIT_FAILURE);

    for (;;) {
        int r, nfds = 0;
        fd_set rd, wr, er;
        FD_ZERO(&rd);
        FD_ZERO(&wr);
        FD_ZERO(&er);
        FD_SET(h, &rd);
        nfds = max(nfds, h);
        if (fd1 > 0 && buf1_avail < BUF_SIZE) {
            FD_SET(fd1, &rd);
            nfds = max(nfds, fd1);
        }
        if (fd2 > 0 && buf2_avail < BUF_SIZE) {
            FD_SET(fd2, &rd);
            nfds = max(nfds, fd2);
        }
        if (fd1 > 0
            && buf2_avail - buf2_written > 0) {
            FD_SET(fd1, &wr);
            nfds = max(nfds, fd1);
        }
        if (fd2 > 0
            && buf1_avail - buf1_written > 0) {
            FD_SET(fd2, &wr);
            nfds = max(nfds, fd2);
        }
        if (fd1 > 0) {
            FD_SET(fd1, &er);
            nfds = max(nfds, fd1);
        }
        if (fd2 > 0) {
            FD_SET(fd2, &er);
            nfds = max(nfds, fd2);
        }

        r = select(nfds + 1, &rd, &wr, &er, NULL);

        if (r == -1 && errno == EINTR)
            continue;
        if (r < 0) {
            perror("select()");
            exit(EXIT_FAILURE);
        }
        if (FD_ISSET(h, &rd)) {
            unsigned int l;
            struct sockaddr_in client_address;
            memset(&client_address, 0, l = sizeof(client_address));
            r = accept(h, (struct sockaddr *) &client_address, &l);
            if (r < 0) {
                perror("accept()");
            } else {
                SHUT_FD1;
                SHUT_FD2;
                buf1_avail = buf1_written = 0;
                buf2_avail = buf2_written = 0;
                fd1 = r;
                fd2 =
                    connect_socket(forward_port, argv[3]);
                if (fd2 < 0) {
                    SHUT_FD1;
                } else
                    printf("connect from %s\n",
                            inet_ntoa(client_address.sin_addr));
            }
        }
/* NB: read oob data before normal reads */
        if (fd1 > 0)
            if (FD_ISSET(fd1, &er)) {
                char c;
                errno = 0;
                r = recv(fd1, &c, 1, MSG_OOB);
                if (r < 1) {
                    SHUT_FD1;
                } else
                    send(fd2, &c, 1, MSG_OOB);
            }
        if (fd2 > 0)
            if (FD_ISSET(fd2, &er)) {
                char c;
                errno = 0;
                r = recv(fd2, &c, 1, MSG_OOB);
                if (r < 1) {
                    SHUT_FD1;
                } else
                    send(fd1, &c, 1, MSG_OOB);
            }
        if (fd1 > 0)
            if (FD_ISSET(fd1, &rd)) {
                r =
                    read(fd1, buf1 + buf1_avail,
                          BUF_SIZE - buf1_avail);
                if (r < 1) {
                    SHUT_FD1;
                } else
                    buf1_avail += r;
            }
        if (fd2 > 0)
            if (FD_ISSET(fd2, &rd)) {
                r =
                    read(fd2, buf2 + buf2_avail,
                          BUF_SIZE - buf2_avail);
                if (r < 1) {
                    SHUT_FD2;
                } else
                    buf2_avail += r;
            }
        if (fd1 > 0)
            if (FD_ISSET(fd1, &wr)) {
                r =
                    write(fd1, buf2 + buf2_written,
                           buf2_avail - buf2_written);
                if (r < 1) {
                    SHUT_FD1;
                } else
                    buf2_written += r;
            }
        if (fd2 > 0)
            if (FD_ISSET(fd2, &wr)) {
                r =
                    write(fd2, buf1 + buf1_written,
                           buf1_avail - buf1_written);
                if (r < 1) {
                    SHUT_FD2;
                } else
                    buf1_written += r;
            }
/* check if write data has caught read data */
        if (buf1_written == buf1_avail)
            buf1_written = buf1_avail = 0;
        if (buf2_written == buf2_avail)
            buf2_written = buf2_avail = 0;
/* one side has closed the connection, keep
   writing to the other side until empty */
        if (fd1 < 0 && buf1_avail - buf1_written == 0) {
            SHUT_FD2;
        }
        if (fd2 < 0 && buf2_avail - buf2_written == 0) {
            SHUT_FD1;
        }
    }
    exit(EXIT_SUCCESS);
}

The above program properly forwards most kinds of TCP connections including OOB signal data transmitted by telnet servers. It handles the tricky problem of having data flow in both directions simultaneously. You might think it more efficient to use a fork(2) call and devote a thread to each stream. This becomes more tricky than you might suspect. Another idea is to set non-blocking I/O using an ioctl(2) call. This also has its problems because you end up having to have inefficient timeouts.

The program does not handle more than one simultaneous connection at a time, although it could easily be extended to do this with a linked list of buffers --- one for each connection. At the moment, new connections cause the current connection to be dropped.

SEE ALSO

accept(2), connect(2), ioctl(2), poll(2), read(2), recv(2), select(2), send(2), sigprocmask(2), write(2), sigaddset(3), sigdelset(3), sigemptyset(3), sigfillset(3), sigismember(3), epoll(7)


syscall(2)

SYSCALL

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

syscall - indirect system call

SYNOPSIS

#define _BSD_SOURCE        /* or _GNU_SOURCE or _SVID_SOURCE */
#include <unistd.h>
#include <sys/syscall.h>   /* For SYS_xxx definitions */

int syscall(int number, ...);

DESCRIPTION

syscall() performs the system call whose assembly language interface has the specified number with the specified arguments. Symbolic constants for system calls can be found in the header file <sys/syscall.h>.

RETURN VALUE

The return value is defined by the system call being invoked. In general, a 0 return value indicates success. A -1 return value indicates an error, and an error code is stored in errno.

NOTES

syscall() first appeared in 4BSD.

EXAMPLE

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>

int
main(int argc, char *argv[])
{
    pid_t tid;
    tid = (long) syscall(SYS_gettid);
}


mmap2(2)

MMAP2

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

mmap2 - map files or devices into memory

SYNOPSIS

#include <sys/mman.h>

void *mmap2(void *start, size_t length, int prot,
             int flags, int fd, off_t pgoffset);

DESCRIPTION

The mmap2() system call operates in exactly the same way as mmap(2), except that the final argument specifies the offset into the file in units of the system page size (instead of bytes). This enables applications that use a 32-bit off_t to map larger files (typically up to 2^44 bytes).

RETURN VALUE

On success, mmap2() returns a pointer to the mapped area. On error -1 is returned and errno is set appropriately.

ERRORS

EFAULT
Problem with getting the data from userspace.

CONFORMING TO

This system call is Linux specific.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

mmap2() is available since Linux 2.3.31. It is Linux specific, and should be avoided in portable applications. On 32-bit systems, mmap2() is used to implement the mmap64() function that is part of the LFS (Large File Summit).

SEE ALSO

getpagesize(2), mmap(2), mremap(2), msync(2), shm_open(3)


sigqueue(2)

SIGQUEUE

Section: Linux Programmer's Manual (2)
Updated: 2004-06-16 Return to Main Contents

NAME

sigqueue - queue a signal and data to a process

SYNOPSIS

#include <signal.h>

int sigqueue(pid_t pid, int sig, const union sigval value);

DESCRIPTION

sigqueue() sends the signal specified in sig to the process whose PID is given in pid. The permissions required to send a signal are the same as for kill(2). As with kill(2), the null signal (0) can be used to check if a process with a given PID exists.

The value argument is used to specify an accompanying item of data (either an integer or a pointer value) to be sent with the signal, and has the following type:

union sigval {
    int   sival_int;
    void *sival_ptr;
};

If the receiving process has installed a handler for this signal using the SA_SIGINFO flag to sigaction(2), then it can obtain this data via the si_value field of the siginfo_t structure passed as the second argument to the handler. Furthermore, the si_code field of that structure will be set to SI_QUEUE.

RETURN VALUE

On success, sigqueue() returns 0, indicating that the signal was successfully queued to the receiving process. Otherwise -1 is returned and errno is set to indicate the error.

ERRORS

EAGAIN
The limit of signals which may be queued has been reached. (See signal(7) for further information.)
EINVAL
sig was invalid.
EPERM
The process does not have permission to send the signal to the receiving process. For the required permissions, see kill(2).
ESRCH
No process has a PID matching pid.

CONFORMING TO

POSIX.1-2001

NOTES

If this function results in the sending of a signal to the process that invoked it, and that signal was not blocked by the calling thread, and no other threads were willing to handle this signal (either by having it unblocked, or by waiting for it using sigwait(3)), then at least some signal must be delivered to this thread before this function returns.

SEE ALSO

kill(2), sigaction(2), signal(2), sigwait(3), signal(7)


umount2 (2)

 Continue to this page.


sigwaitinfo(2)

SIGWAITINFO

Section: Linux Programmer's Manual (2)
Updated: 2002-06-07 Return to Main Contents

NAME

sigwaitinfo, sigtimedwait - synchronously wait for queued signals

SYNOPSIS

#include <signal.h>

int sigwaitinfo(const sigset_t *set, siginfo_t *info);

int sigtimedwait(const sigset_t *set, siginfo_t *info,
                 const struct timespec *timeout);

DESCRIPTION

sigwaitinfo() suspends execution of the calling process until one of the signals in set is delivered. (If one of the signals in set is already pending for the calling process, sigwaitinfo() will return immediately with information about that signal.)

sigwaitinfo() removes the delivered signal from the calling process's list of pending signals and returns the signal number as its function result. If the info argument is not NULL, then it returns a structure of type siginfo_t (see sigaction(2)) containing information about the signal.

Signals returned via sigwaitinfo() are delivered in the usual order; see signal(7) for further details.

sigtimedwait() operates in exactly the same way as sigwaitinfo() except that it has an additional argument, timeout, which enables an upper bound to be placed on the time for which the process is suspended. This argument is of the following type:

struct timespec {
    long    tv_sec;         /* seconds */
    long    tv_nsec;        /* nanoseconds */
}

If both fields of this structure are specified as 0, a poll is performed: sigtimedwait() returns immediately, either with information about a signal that was pending for the caller, or with an error if none of the signals in set was pending.

RETURN VALUE

On success, both sigwaitinfo() and sigtimedwait() return a signal number (i.e., a value greater than zero). On failure both calls return -1, with errno set to indicate the error.

ERRORS

EAGAIN
No signal in set was delivered within the timeout period specified to sigtimedwait().
EINTR
The wait was interrupted by a signal handler. (This handler was for a signal other than one of those in set.)
EINVAL
timeout was invalid.

CONFORMING TO

POSIX.1-2001

NOTES

In normal usage, the calling program blocks the signals in set via a prior call to sigprocmask(2) (so that the default disposition for these signals does not occur if they are delivered between successive calls to sigwaitinfo() or sigtimedwait()) and does not establish handlers for these signals. In a multithreaded program, the signal should be blocked in all threads to prevent the signal being delivered to a thread other than the one calling sigwaitinfo() or sigtimedwait()).

POSIX leaves the meaning of a NULL value for the timeout argument of sigtimedwait() unspecified, permitting the possibility that this has the same meaning as a call to sigwaitinfo(), and indeed this is what is done on Linux.

SEE ALSO

kill(2), sigaction(2), signal(2), sigpending(2), sigprocmask(2), sigqueue(2), sigsetops(3), signal(7)


sigtimedwait (2)

 Continue to this page.


sched_getaffinity (2)

 Continue to this page.


sched_setaffinity(2)

SCHED_SETAFFINITY

Section: Linux Programmer's Manual (2)
Updated: 2006-02-03 Return to Main Contents

NAME

sched_setaffinity, sched_getaffinity, CPU_CLR, CPU_ISSET, CPU_SET, CPU_ZERO - set and get a process's CPU affinity mask

SYNOPSIS

#include <sched.h>

int sched_setaffinity(pid_t pid, unsigned int cpusetsize,
                      cpu_set_t *mask);

int sched_getaffinity(pid_t pid, unsigned int cpusetsize,
                      cpu_set_t *mask);

void CPU_CLR(int cpu, cpu_set_t *set);

int CPU_ISSET(int cpu, cpu_set_t *set);

void CPU_SET(int cpu, cpu_set_t *set);

void CPU_ZERO(cpu_set_t *set);

DESCRIPTION

A process's CPU affinity mask determines the set of CPUs on which it is eligible to run. On a multiprocessor system, setting the CPU affinity mask can be used to obtain performance benefits. For example, by dedicating one CPU to a particular process (i.e., setting the affinity mask of that process to specify a single CPU, and setting the affinity mask of all other processes to exclude that CPU), it is possible to ensure maximum execution speed for that process. Restricting a process to run on a single CPU also prevents the performance cost caused by the cache invalidation that occurs when a process ceases to execute on one CPU and then recommences execution on a different CPU.

A CPU affinity mask is represented by the cpu_set_t structure, a "CPU set", pointed to by mask. Four macros are provided to manipulate CPU sets. CPU_ZERO() clears a set. CPU_SET() and CPU_CLR() respectively add and remove a given CPU from a set. CPU_ISSET() tests to see if a CPU is part of the set; this is useful after sched_getaffinity() returns. The first available CPU on the system corresponds to a cpu value of 0, the next CPU corresponds to a cpu value of 1, and so on. The constant CPU_SETSIZE (1024) specifies a value one greater than the maximum CPU number that can be stored in a CPU set.

sched_setaffinity() sets the CPU affinity mask of the process whose ID is pid to the value specified by mask. If pid is zero, then the calling process is used. The argument cpusetsize is the length (in bytes) of the data pointed to by mask. Normally this argument would be specified as sizeof(cpu_set_t).

If the process specified by pid is not currently running on one of the CPUs specified in mask, then that process is migrated to one of the CPUs specified in mask.

sched_getaffinity() writes the affinity mask of the process whose ID is pid into the cpu_set_t structure pointed to by mask. The cpusetsize argument specifies the size (in bytes) of mask. If pid is zero, then the mask of the calling process is returned.

RETURN VALUE

On success, sched_setaffinity() and sched_getaffinity() return 0. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
A supplied memory address was invalid.
EINVAL
The affinity bitmask mask contains no processors that are physically on the system, or cpusetsize is smaller than the size of the affinity mask used by the kernel.
EPERM
The calling process does not have appropriate privileges. The process calling sched_setaffinity() needs an effective user ID equal to the user ID or effective user ID of the process identified by pid, or it must possess the CAP_SYS_NICE capability.
ESRCH
The process whose ID is pid could not be found.

VERSIONS

The CPU affinity system calls were introduced in Linux kernel 2.5.8. The library interfaces were introduced in glibc 2.3. Initially, the glibc interfaces included a cpusetsize argument. In glibc 2.3.3, the cpusetsize argument was removed, but this argument was restored in glibc 2.3.4.

CONFORMING TO

These system calls are Linux specific.

NOTES

The affinity mask is actually a per-thread attribute that can be adjusted independently for each of the threads in a thread group. The value returned from a call to gettid(2) can be passed in the argument pid.

A child created via fork(2) inherits its parent's CPU affinity mask. The affinity mask is preserved across an execve(2).

This manual page describes the glibc interface for the CPU affinity calls. The actual system call interface is slightly different, with the mask being typed as unsigned long *, reflecting that the fact that the underlying implementation of CPU sets is a simple bitmask. On success, the raw sched_getaffinity() system call returns the size (in bytes) of the cpumask_t data type that is used internally by the kernel to represent the CPU set bitmask.

SEE ALSO

clone(2), getpriority(2), gettid(2), nice(2), sched_get_priority_max(2), sched_get_priority_min(2), sched_getscheduler(2), sched_setscheduler(2), setpriority(2), capabilities(7)

sched_setscheduler(2) has a description of the Linux scheduling scheme.


futex(2)

FUTEX

Section: Linux Programmer's Manual (2)
Updated: 2004-10-07 Return to Main Contents

NAME

futex - Fast Userspace Locking system call

SYNOPSIS

#include <linux/futex.h>
#include <sys/time.h>

int futex(int *uaddr, int op, int val, const struct timespec *timeout,

          int *uaddr2, int val3);

DESCRIPTION

The futex() system call provides a method for a program to wait for a value at a given address to change, and a method to wake up anyone waiting on a particular address (while the addresses for the same memory in separate processes may not be equal, the kernel maps them internally so the same memory mapped in different locations will correspond for futex() calls). It is typically used to implement the contended case of a lock in shared memory, as described in futex(7).

When a futex(7) operation did not finish uncontended in userspace, a call needs to be made to the kernel to arbitrate. Arbitration can either mean putting the calling process to sleep or, conversely, waking a waiting process.

Callers of this function are expected to adhere to the semantics as set out in futex(7). As these semantics involve writing non-portable assembly instructions, this in turn probably means that most users will in fact be library authors and not general application developers.

The uaddr argument needs to point to an aligned integer which stores the counter. The operation to execute is passed via the op parameter, along with a value val.

Five operations are currently defined:

FUTEX_WAIT
This operation atomically verifies that the futex address uaddr still contains the value val, and sleeps awaiting FUTEX_WAKE on this futex address. If the timeout argument is non-NULL, its contents describe the maximum duration of the wait, which is infinite otherwise. The arguments uaddr2 and val3 are ignored.

For futex(7), this call is executed if decrementing the count gave a negative value (indicating contention), and will sleep until another process releases the futex and executes the FUTEX_WAKE operation.

FUTEX_WAKE
This operation wakes at most val processes waiting on this futex address (ie. inside FUTEX_WAIT). The arguments timeout, uaddr2 and val3 are ignored.

For futex(7), this is executed if incrementing the count showed that there were waiters, once the futex value has been set to 1 (indicating that it is available).

FUTEX_FD
To support asynchronous wakeups, this operation associates a file descriptor with a futex. If another process executes a FUTEX_WAKE, the process will receive the signal number that was passed in val. The calling process must close the returned file descriptor after use. The arguments timeout, uaddr2 and val3 are ignored.

To prevent race conditions, the caller should test if the futex has been upped after FUTEX_FD returns.

Because it is inherently racy, FUTEX_FD is scheduled for removal in June 2007; any applications that use it should be fixed now.

FUTEX_REQUEUE (since Linux 2.5.70)
This operation was introduced in order to avoid a "thundering herd" effect when FUTEX_WAKE is used and all processes woken up need to acquire another futex. This call wakes up val processes, and requeues all other waiters on the futex at address uaddr2. The arguments timeout and val3 are ignored.
FUTEX_CMP_REQUEUE (since Linux 2.6.7)
There was a race in the intended use of FUTEX_REQUEUE, so FUTEX_CMP_REQUEUE was introduced. This is similar to FUTEX_REQUEUE, but first checks whether the location uaddr still contains the value val3. If not, an error EAGAIN is returned. The argument timeout is ignored.

RETURN VALUE

Depending on which operation was executed, the returned value can have differing meanings.

FUTEX_WAIT
Returns 0 if the process was woken by a FUTEX_WAKE call. In case of timeout, ETIMEDOUT is returned. If the futex was not equal to the expected value, the operation fails with the error EWOULDBLOCK. Signals (or other spurious wakeups) cause FUTEX_WAIT to return EINTR.
FUTEX_WAKE
Returns the number of processes woken up.
FUTEX_FD
Returns the new file descriptor associated with the futex.
FUTEX_REQUEUE
Returns the number of processes woken up.
FUTEX_CMP_REQUEUE
Returns the number of processes woken up.

ERRORS

EACCES
No read access to futex memory.
EAGAIN
FUTEX_CMP_REQUEUE found an unexpected futex value. (This probably indicates a race; use the safe FUTEX_WAKE now.)
EFAULT
Error in getting timeout information from userspace.
EINVAL
An operation was not defined or error in page alignment.
ENFILE
The system limit on the total number of open files has been reached.

VERSIONS

Initial futex support was merged in Linux 2.5.7 but with different semantics from what was described above. A 4-parameter system call with the semantics given here was introduced in Linux 2.5.40. In Linux 2.5.70 one parameter was added. In Linux 2.6.7 a sixth parameter was added --- messy, especially on the s390 architecture.

CONFORMING TO

This system call is Linux specific.

NOTES

To reiterate, bare futexes are not intended as an easy to use abstraction for end-users. Implementors are expected to be assembly literate and to have read the sources of the futex userspace library referenced below.

SEE ALSO

futex(7), `Fuss, Futexes and Furwocks: Fast Userlevel Locking in Linux' (proceedings of the Ottawa Linux Symposium 2002), futex example library, futex-*.tar.bz2 <URL:ftp://ftp.nl.kernel.org:/pub/linux/kernel/people/rusty/>.


undocumented(2)

UNDOCUMENTED

Section: Linux Programmer's Manual (2)
Updated: 2003-02-01 Return to Main Contents

NAME

madvise1, rt_sigaction, rt_sigpending, rt_sigprocmask, rt_sigqueueinfo, rt_sigreturn, rt_sigsuspend, rt_sigtimedwait, ugetrlimit - undocumented system calls

SYNOPSIS

Undocumented system calls.

DESCRIPTION

The 2.4.20 kernel knows 253 syscalls for the i386 architecture. The above ones have not yet been documented.

SEE ALSO

obsolete(2), syscalls(2), unimplemented(2)


gettid(2)

GETTID

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

gettid - get thread identification

SYNOPSIS

#include <sys/types.h>

pid_t gettid(void);

DESCRIPTION

gettid() returns the thread ID of the current process. This is equal to the process ID (as returned by getpid(2)), unless the process is part of a thread group (created by specifying the CLONE_THREAD flag to the clone(2) system call). All processes in the same thread group have the same PID, but each one has a unique TID.

RETURN VALUE

On success, returns the thread ID of the current process.

ERRORS

This call is always successful.

CONFORMING TO

gettid() is Linux specific and should not be used in programs that are intended to be portable.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2).

SEE ALSO

clone(2), fork(2), getpid(2)


alloc_hugepages(2)

ALLOC_HUGEPAGES

Section: Linux Programmer's Manual (2)
Updated: 2007-05-31 Return to Main Contents

NAME

alloc_hugepages, free_hugepages - allocate or free huge pages

SYNOPSIS

void *alloc_hugepages(int key, void *addr, size_t len,
                      int prot, int flag);

int free_hugepages(void *addr);

DESCRIPTION

The system calls alloc_hugepages() and free_hugepages() were introduced in Linux 2.5.36 and removed again in 2.5.54. They existed only on i386 and ia64 (when built with CONFIG_HUGETLB_PAGE). In Linux 2.4.20 the syscall numbers exist, but the calls fail with the error ENOSYS.

On i386 the memory management hardware knows about ordinary pages (4 KiB) and huge pages (2 or 4 MiB). Similarly ia64 knows about huge pages of several sizes. These system calls serve to map huge pages into the process' memory or to free them again. Huge pages are locked into memory, and are not swapped.

The key parameter is an identifier. When zero the pages are private, and not inherited by children. When positive the pages are shared with other applications using the same key, and inherited by child processes.

The addr parameter of free_hugepages() tells which page is being freed: it was the return value of a call to alloc_hugepages(). (The memory is first actually freed when all users have released it.) The addr parameter of alloc_hugepages() is a hint, that the kernel may or may not follow. Addresses must be properly aligned.

The len parameter is the length of the required segment. It must be a multiple of the huge page size.

The prot parameter specifies the memory protection of the segment. It is one of PROT_READ, PROT_WRITE, PROT_EXEC.

The flag parameter is ignored, unless key is positive. In that case, if flag is IPC_CREAT, then a new huge page segment is created when none with the given key existed. If this flag is not set, then ENOENT is returned when no segment with the given key exists. .SHRETURN VALUE On success, alloc_hugepages() returns the allocated virtual address, and free_hugepages() returns zero. On error, -1 is returned, and errno is set appropriately.

ERRORS

ENOSYS
The system call is not supported on this kernel.

FILES

/proc/sys/vm/nr_hugepages Number of configured hugetlb pages. This can be read and written.

/proc/meminfo Gives info on the number of configured hugetlb pages and on their size in the three variables HugePages_Total, HugePages_Free, Hugepagesize.

CONFORMING TO

These calls are specific to Linux on Intel processors, and should not be used in programs intended to be portable.

NOTES

These system calls are gone; they existed only in Linux 2.5.36 through to 2.5.54. Now the hugetlbfs filesystem can be used instead. Memory backed by huge pages (if the CPU supports them) is obtained by using mmap(2) to map files in this virtual filesystem.

The maximal number of huge pages can be specified using the hugepages= boot parameter.


tkill(2)

TKILL

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

tkill, tgkill - send a signal to a single process

SYNOPSIS

int tkill(int tid, int sig);

int tgkill(int tgid, int tid, int sig);

DESCRIPTION

The tkill() system call is analogous to kill(2), except when the specified process is part of a thread group (created by specifying the CLONE_THREAD flag in the call to clone). Since all the processes in a thread group have the same PID, they cannot be individually signaled with kill(2). With tkill(), however, one can address each process by its unique TID.

The tgkill() call improves on tkill() by allowing the caller to specify the thread group ID of the thread to be signaled, protecting against TID reuse. If the tgid is specified as -1, tgkill() degenerates into tkill().

These are the raw system call interfaces, meant for internal thread library use.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
An invalid TID or signal was specified.
EPERM
Permission denied. For the required permissions, see kill(2).
ESRCH
No process with the specified thread ID (and thread group ID) exists.

VERSIONS

tkill() is supported since Linux 2.4.19 / 2.5.4. tgkill() was added in Linux 2.5.75.

CONFORMING TO

tkill() and tgkill() are Linux specific and should not be used in programs that are intended to be portable.

NOTES

Glibc does not provide wrapper for these system calls; call them using syscall(2).

SEE ALSO

gettid(2), kill(2)


arch_prctl(2)

ARCH_PRCTL

Section: Linux Programmer's Manual (2)
Updated: 2003-02-02 Return to Main Contents

NAME

arch_prctl - set architecture specific thread state

SYNOPSIS

#include <asm/prctl.h> #include <sys/prctl.h>

int arch_prctl(int code, unsigned long addr)

DESCRIPTION

The arch_prctl() function sets architecture specific process or thread state. code selects a subfunction and passes argument addr to it.

Sub functions for x86-64 are:

ARCH_SET_FS
Set the 64bit base for the FS register to addr.
ARCH_GET_FS
Return the 64bit base value for the FS register of the current thread in the unsigned long pointed to by the address parameter
ARCH_SET_GS
Set the 64bit base for the GS register to addr.
ARCH_GET_GS
Return the 64bit base value for the GS register of the current thread in the unsigned long pointed to by the address parameter.

RETURN VALUE

On sucess, arch_prctl() returns 0; on error, -1 is returned, and errno is set to indicate the error.

ERRORS

EFAULT
addr points to an unmapped address or is outside the process address space.
EINVAL
code is not a valid subcommand.
EPERM
addr is outside the process address space.

CONFORMING TO

arch_prctl() is a Linux/x86-64 extension and should not be used in programs intended to be portable.

NOTES

arch_prctl() is only supported on Linux/x86-64 for 64bit programs currently.

The 64bit base changes when a new 32bit segment selector is loaded.

ARCH_SET_GS is disabled in some kernels.

Context switches for 64bit segment bases are rather expensive. It may be a faster alternative to set a 32bit base using a segment selector by setting up an LDT with modify_ldt(2) or using the set_thread_area(2) system call in a 2.5 kernel. arch_prctl() is only needed when you want to set bases that are larger than 4GB. Memory in the first 2GB of address space can be allocated by using mmap(2) with the MAP_32BIT flag.

As of version 2.3.5, glibc provides no prototype for arch_prctl(). You have to declare it yourself for now. This may be fixed in future glibc versions.

FS may be already used by the threading library.

SEE ALSO

mmap(2), modify_ldt(2), prctl(2), set_thread_area(2)

AMD X86-64 Programmer's manual


free_hugepages (2)

 Continue to this page.


io_submit(2)

IO_SUBMIT

Section: Linux Programmer's Manual (2)
Updated: 2003-02-21 Return to Main Contents

NAME

io_submit - submit asynchronous I/O blocks for processing

SYNOPSIS

#include <linux/aio.h>

int io_submit(aio_context_t ctx_id, long nr, struct iocb **iocbpp);

DESCRIPTION

io_submit() queues nr I/O request blocks for processing in the AIO context ctx_id. iocbpp should be an array of nr AIO request blocks, which will be submitted to context ctx_id.

RETURN VALUE

On success, io_submit() returns the number of iocbs submitted (which may be 0 if nr is zero); on failure, it returns one of the errors listed under ERRORS.

ERRORS

EINVAL
The aio_context specified by ctx_id is invalid. nr is less than 0. The iocb at *iocbpp[0] is not properly initialized, or the operation specified is invalid for the file descriptor in the iocb.
EFAULT
One of the data structures points to invalid data.
EBADF
The file descriptor specified in the first iocb is invalid.
EAGAIN
Insufficient resources are available to queue any iocbs.
ENOSYS
io_submit() is not implemented on this architecture.

VERSIONS

The asynchronous I/O system calls first appeared in Linux 2.5, August 2002.

CONFORMING TO

io_submit() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO

io_setup(2),

io_destroy(2),

io_getevents(2),

io_cancel(2)


setxattr(2)

SETXATTR

Section: Linux Programmer's Manual (2)
Updated: 2001-12-31 Return to Main Contents

NAME

setxattr, lsetxattr, fsetxattr - set an extended attribute value

SYNOPSIS

#include <sys/types.h>
#include <attr/xattr.h>

int setxattr(const char *path, const char *name,
              const void *value, size_t size, int flags);
int lsetxattr(const char *path, const char *name,
              const void *value, size_t size, int flags);
int fsetxattr(int filedes, const char *name,
              const void *value, size_t size, int flags);

DESCRIPTION

Extended attributes are name:value pairs associated with inodes (files, directories, symbolic links, etc). They are extensions to the normal attributes which are associated with all inodes in the system (i.e., the stat(2) data). A complete overview of extended attributes concepts can be found in attr(5).

setxattr() sets the value of the extended attribute identified by name and associated with the given path in the filesystem. The size of the value must be specified.

lsetxattr() is identical to setxattr(), except in the case of a symbolic link, where the extended attribute is set on the link itself, not the file that it refers to.

fsetxattr() is identical to setxattr(), only the extended attribute is set on the open file pointed to by filedes (as returned by open(2)) in place of path.

An extended attribute name is a simple null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode. The value of an extended attribute is a chunk of arbitrary textual or binary data of specified length.

The flags parameter can be used to refine the semantics of the operation. XATTR_CREATE specifies a pure create, which fails if the named attribute exists already. XATTR_REPLACE specifies a pure replace operation, which fails if the named attribute does not already exist. By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.

RETURN VALUE

On success, zero is returned. On failure, -1 is returned and errno is set appropriately.

If XATTR_CREATE is specified, and the attribute exists already, errno is set to EEXIST. If XATTR_REPLACE is specified, and the attribute does not exist, errno is set to ENOATTR.

If there is insufficient space remaining to store the extended attribute, errno is set to either ENOSPC, or EDQUOT if quota enforcement was the cause.

If extended attributes are not supported by the filesystem, or are disabled, errno is set to ENOTSUP.

The errors documented for the stat(2) system call are also applicable here.

VERSIONS

These system calls have been available on Linux since kernel 2.4; glibc support is provided since version 2.3.

CONFORMING TO

These system calls are Linux specific.

SEE ALSO

getfattr(1), setfattr(1), getxattr(2), listxattr(2), open(2), removexattr(2), stat(2), attr(5)


path_resolution (2)

 Continue to this page.


lookup_dcookie(2)

LOOKUP_DCOOKIE

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

lookup_dcookie - return a directory entry's path

SYNOPSIS

int lookup_dcookie(u64 cookie, char *buffer, size_t len);

DESCRIPTION

Look up the full path of the directory entry specified by the value cookie The cookie is an opaque identifier uniquely identifying a particular directory entry. The buffer given is filled in with the full path of the directory entry.

For lookup_dcookie() to return successfully, the kernel must still hold a cookie reference to the directory entry.

RETURN VALUE

On success, lookup_dcookie() returns the length of the path string copied into the buffer. On error, -1 is returned, and errno is set appropriately.

ERRORS

EFAULT
The buffer was not valid.
EINVAL
The kernel has no registered cookie/directory entry mappings at the time of lookup, or the cookie does not refer to a valid directory entry.
ENAMETOOLONG
The name could not fit in the buffer.
ENOMEM
The kernel could not allocate memory for the temporary buffer holding the path.
EPERM
The process does not have the capability CAP_SYS_ADMIN required to look up cookie values.
ERANGE
The buffer was not large enough to hold the path of the directory entry.

VERSIONS

Available since Linux 2.5.43. The ENAMETOOLONG error return was added in 2.5.70.

CONFORMING TO

lookup_dcookie() is Linux specific.

NOTES

lookup_dcookie() is a special-purpose system call, currently used only by the oprofile profiler. It relies on a kernel driver to register cookies for directory entries.

The path returned may be suffixed by the string " (deleted)" if the directory entry has been removed.


llistxattr (2)

 Continue to this page.


listxattr(2)

LISTXATTR

Section: Linux Programmer's Manual (2)
Updated: 2001-12-01 Return to Main Contents

NAME

listxattr, llistxattr, flistxattr - list extended attribute names

SYNOPSIS

#include <sys/types.h>
#include <attr/xattr.h>

ssize_t listxattr(const char *path, char *list, size_t size);
ssize_t llistxattr(const char *path, char *list, size_t size);
ssize_t flistxattr(int filedes, char *list, size_t size);

DESCRIPTION

Extended attributes are name:value pairs associated with inodes (files, directories, symbolic links, etc). They are extensions to the normal attributes which are associated with all inodes in the system (i.e., the stat(2) data). A complete overview of extended attributes concepts can be found in attr(5).

listxattr() retrieves the list of extended attribute names associated with the given path in the filesystem. The list is the set of (null-terminated) names, one after the other. Names of extended attributes to which the calling process does not have access may be omitted from the list. The length of the attribute name list is returned.

llistxattr() is identical to listxattr(), except in the case of a symbolic link, where the list of names of extended attributes associated with the link itself is retrieved, not the file that it refers to.

flistxattr() is identical to listxattr(), only the open file pointed to by filedes (as returned by open(2)) is interrogated in place of path.

A single extended attribute name is a simple null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode.

An empty buffer of size zero can be passed into these calls to return the current size of the list of extended attribute names, which can be used to estimate the size of a buffer which is sufficiently large to hold the list of names.

Example

The list of names is returned as an unordered array of null-terminated character strings (attribute names are separated by null bytes ('\0')), like this:

user.name1\0system.name1\0user.name2\0
Filesystems like ext2, ext3 and XFS which implement POSIX ACLs using extended attributes, might return a list like this:

system.posix_acl_access\0system.posix_acl_default\0

RETURN VALUE

On success, a positive number is returned indicating the size of the extended attribute name list. On failure, -1 is returned and errno is set appropriately.

If the size of the list buffer is too small to hold the result, errno is set to ERANGE.

If extended attributes are not supported by the filesystem, or are disabled, errno is set to ENOTSUP.

The errors documented for the stat(2) system call are also applicable here.

VERSIONS

These system calls have been available on Linux since kernel 2.4; glibc support is provided since version 2.3.

CONFORMING TO

These system calls are Linux specific.

SEE ALSO

getfattr(1), setfattr(1), getxattr(2), open(2), removexattr(2), setxattr(2), stat(2), attr(5)


pciconfig_write (2)

 Continue to this page.


fgetxattr (2)

 Continue to this page.


readahead(2)

READAHEAD

Section: Linux Programmer's Manual (2)
Updated: 2004-10-05 Return to Main Contents

NAME

readahead - perform file readahead into page cache

SYNOPSIS

#include <fcntl.h>

ssize_t readahead(int fd, off64_t *offset, size_t count);

DESCRIPTION

readahead() populates the page cache with data from a file so that subsequent reads from that file will not block on disk I/O. The fd argument is a file descriptor identifying the file which is to be read. The offset argument specifies the starting point from which data is to be read and count specifies the number of bytes to be read. I/O is performed in whole pages, so that offset is effectively rounded down to a page boundary and bytes are read up to the next page boundary greater than or equal to (offset+count). readahead() does not read beyond the end of the file. readahead() blocks until the specified data has been read. The current file offset of the open file referred to by fd is left unchanged.

RETURN VALUE

On success, readahead() returns 0; on failure, -1 is returned, with errno set to indicate the cause of the error.

ERRORS

EBADF
fd is not a valid file descriptor or is not open for reading.
EINVAL
fd does not refer to a file type to which readahead() can be applied.

VERSIONS

The readahead() system call appeared in Linux 2.4.13; glibc support has been provided since version 2.3.

CONFORMING TO

The readahead() system call is Linux specific, and its use should be avoided in portable applications.

SEE ALSO

fadvise(2), lseek(2), madvise(2), mmap(2), posix_fadvise(2), read(2)


io_destroy(2)

IO_DESTROY

Section: Linux Programmer's Manual (2)
Updated: 2003-02-21 Return to Main Contents

NAME

io_destroy - destroy an asynchronous I/O context

SYNOPSIS

#include <libaio.h>

int io_destroy(aio_context_t ctx);

DESCRIPTION

io_destroy() removes the asynchronous I/O context from the list of I/O contexts and then destroys it. io_destroy() can also cancel any outstanding asynchronous I/O actions on ctx and block on completion.

RETURN VALUE

io_destroy() returns 0 on success; on failure, it returns one of the errors listed under ERRORS.

ERRORS

EINVAL
The AIO context specified by ctx is invalid.
EFAULT
The context pointed to is invalid.
ENOSYS
io_destroy() is not implemented on this architecture.

VERSIONS

The asynchronous I/O system calls first appeared in Linux 2.5, August 2002.

CONFORMING TO

io_destroy() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO

io_setup(2),

io_submit(2),

io_getevents(2),

io_cancel(2)


pciconfig_read(2)

PCICONFIG_READ

Section: Linux Programmer's Manual (2)
Updated: 2003-07-14 Return to Main Contents

NAME

pciconfig_read, pciconfig_write, pciconfig_iobase - pci device information handling

SYNOPSIS

#include <pci.h>

int pciconfig_read(unsigned long bus, unsigned long dfn,
     unsigned long off, unsigned long len, void *buf);
int pciconfig_write(unsigned long bus, unsigned long dfn,
     unsigned long off, unsigned long len, void *buf);
int pciconfig_iobase(long which, unsigned long bus,
     unsigned long devfn);

DESCRIPTION

Most of the interaction with PCI devices is already handled by the kernel PCI layer, and thus these calls should not normally need to be accessed from userspace.

pciconfig_read()
Reads to buf from device dev at offset off value.
pciconfig_write()
Writes from buf to device dev at offset off value.
pciconfig_iobase()
You pass it a bus/devfn pair and get a physical address for either the memory offset (for things like prep, this is 0xc0000000), the IO base for PIO cycles, or the ISA holes if any.

RETURN VALUE

pciconfig_read()
On success zero is returned. On error, -1 is returned and errno is set appropriately.
pciconfig_write()
On success zero is returned. On error, -1 is returned and errno is set appropriately.
pciconfig_iobase()
Returns information on locations of various I/O regions in physical memory according to the which value. Values for which are: IOBASE_BRIDGE_NUMBER, IOBASE_MEMORY, IOBASE_IO, IOBASE_ISA_IO, IOBASE_ISA_MEM.

ERRORS

EINVAL
len value is invalid. This does not apply to pciconfig_iobase().
EIO
I/O error.
ENODEV
For pciconfig_iobase(), "hose" value is NULL? For the other calls, could not find a slot.
ENOSYS
The system has not implemented these calls (CONFIG_PCI not defined).
EOPNOTSUPP
This return value is only valid for pciconfig_iobase().
It is returned if the value for
which is invalid.
EPERM
User does not have the CAP_SYS_ADMIN capability. This does not apply to pciconfig_iobase().

CONFORMING TO

These calls are Linux specific, available since Linux 2.0.26/2.1.11.

SEE ALSO

capabilities(7)


fsetxattr (2)

 Continue to this page.


putpmsg (2)

 Continue to this page.


fremovexattr (2)

 Continue to this page.


epoll_wait(2)

EPOLL_WAIT

Section: Linux Programmer's Manual (2)
Updated: 2007-04-30 Return to Main Contents

NAME

epoll_wait, epoll_pwait - wait for an I/O event on an epoll file descriptor

SYNOPSIS

#include <sys/epoll.h>

int epoll_wait(int epfd, struct epoll_event *events,
               int maxevents, int timeout);
int epoll_pwait(int epfd, struct epoll_event *events,
               int maxevents, int timeout,
               const sigset_t *sigmask);

DESCRIPTION

The epoll_wait() system call waits for events on the epoll file descriptor epfd for a maximum time of timeout milliseconds. The memory area pointed to by events will contain the events that will be available for the caller. Up to maxevents are returned by epoll_wait(2). The maxevents parameter must be greater than zero. Specifying a timeout of -1 makes epoll_wait(2) wait indefinitely, while specifying a timeout equal to zero makes epoll_wait(2) to return immediately even if no events are available (return code equal to zero). The struct epoll_event is defined as :

typedef union epoll_data {
    void *ptr;
    int fd;
    __uint32_t u32;
    __uint64_t u64;
} epoll_data_t;

struct epoll_event {
    __uint32_t events;      /* Epoll events */
    epoll_data_t data;      /* User data variable */
};

The data of each returned structure will contain the same data the user set with a epoll_ctl(2) (EPOLL_CTL_ADD,EPOLL_CTL_MOD) while the events member will contain the returned event bit field.

epoll_pwait()

The relationship between epoll_wait() and epoll_pwait() is analogous to the relationship between select(2) and pselect(2): like pselect(2), epoll_pwait() allows an application to safely wait until either a file descriptor becomes ready or until a signal is caught.

The following epoll_pwait() call:

    ready = epoll_pwait(epfd, &events, maxevents, timeout, &sigmask);
is equivalent to atomically executing the following calls:

    sigset_t origmask;

    sigprocmask(SIG_SETMASK, &sigmask, &origmask);
    ready = epoll_wait(epfd, &events, maxevents, timeout);
    sigprocmask(SIG_SETMASK, &origmask, NULL);

RETURN VALUE

When successful, epoll_wait(2) returns the number of file descriptors ready for the requested I/O, or zero if no file descriptor became ready during the requested timeout milliseconds. When an error occurs, epoll_wait(2) returns -1 and errno is set appropriately.

ERRORS

EBADF
epfd is not a valid file descriptor.
EFAULT
The memory area pointed to by events is not accessible with write permissions.
EINTR
The call was interrupted by a signal handler before any of the requested events occurred or the timeout expired.
EINVAL
epfd is not an epoll file descriptor, or maxevents is less than or equal to zero.

VERSIONS

epoll_pwait() was added to Linux in kernel 2.6.19.

Glibc support for epoll_pwait() is provided starting with version 2.6.

CONFORMING TO

epoll_wait(2) is Linux specific, and was introduced in kernel 2.5.44.

SEE ALSO

epoll_create(2), epoll_ctl(2), epoll(7)


waitid (2)

 Continue to this page.


remap_file_pages(2)

REMAP_FILE_PAGES

Section: Linux Programmer's Manual (2)
Updated: 2004-10-28 Return to Main Contents

NAME

remap_file_pages - create a non-linear file mapping

SYNOPSIS

#define _GNU_SOURCE
#include <sys/mman.h>

int remap_file_pages(void *start, size_t size, int prot,
                     ssize_t pgoff, int flags);

DESCRIPTION

The remap_file_pages() system call is used to create a non-linear mapping, that is, a mapping in which the pages of the file are mapped into a non-sequential order in memory. The advantage of using remap_file_pages() over using repeated calls to mmap(2) is that the former approach does not require the kernel to create additional VMA (Virtual Memory Area) data structures.

To create a non-linear mapping we perform the following steps:

1.
Use mmap(2) to create a mapping (which is initially linear). This mapping must be created with the MAP_SHARED flag.
2.
Use one or more calls to remap_file_pages() to rearrange the correspondence between the pages of the mapping and the pages of the file. It is possible to map the same page of a file into multiple locations within the mapped region.

The pgoff and size arguments specify the region of the file that is to be relocated within the mapping: pgoff is a file offset in units of the system page size; size is the length of the region in bytes.

The start argument serves two purposes. First, it identifies the mapping whose pages we want to rearrange. Thus, start must be an address that falls within a region previously mapped by a call to mmap(2). Second, start specifies the address at which the file pages identified by pgoff and size will be placed.

The values specified in start and size should be multiples of the system page size. If they are not, then the kernel rounds both values down to the nearest multiple of the page size.

The prot argument must be specified as 0.

The flags argument has the same meaning as for mmap(2), but all flags other than MAP_NONBLOCK are ignored.

RETURN VALUE

On success, remap_file_pages() returns 0. On error, -1 is returned, and errno is set appropriately.

ERRORS

EINVAL
start does not refer to a valid mapping created with the MAP_SHARED flag.
EINVAL
start, size, prot, or pgoff is invalid.

VERSIONS

The remap_file_pages() system call appeared in Linux 2.5.46; glibc support was added in version 2.3.3.

CONFORMING TO

The remap_file_pages() system call is Linux specific.

SEE ALSO

getpagesize(2), mmap(2), mmap2(2), mprotect(2), mremap(2), msync(2), feature_test_macros(7)


tgkill (2)

 Continue to this page.


epoll_create(2)

EPOLL_CREATE

Section: Linux Programmer's Manual (2)
Updated: 2004-06-17 Return to Main Contents

NAME

epoll_create - open an epoll file descriptor

SYNOPSIS

#include <sys/epoll.h>

int epoll_create(int size)

DESCRIPTION

Open an epoll file descriptor by requesting the kernel allocate an event backing store dimensioned for size descriptors. The size is not the maximum size of the backing store but just a hint to the kernel about how to dimension internal structures. The returned file descriptor will be used for all the subsequent calls to the epoll interface. The file descriptor returned by epoll_create(2) must be closed by using close(2).

RETURN VALUE

When successful, epoll_create(2) returns a non-negative integer identifying the descriptor. When an error occurs, epoll_create(2) returns -1 and errno is set appropriately.

ERRORS

EINVAL
size is not positive.
ENFILE
The system limit on the total number of open files has been reached.
ENOMEM
There was insufficient memory to create the kernel object.

CONFORMING TO

epoll_create(2) is Linux specific, and was introduced in kernel 2.5.44.

SEE ALSO

close(2), epoll_ctl(2), epoll_wait(2), epoll(7)


getpmsg (2)

 Continue to this page.


security (2)

 Continue to this page.


flistxattr (2)

 Continue to this page.


pciconfig_iobase (2)

 Continue to this page.


io_getevents(2)

IO_GETEVENTS

Section: Linux Programmer's Manual (2)
Updated: 2003-02-21 Return to Main Contents

NAME

io_getevents - read asynchronous I/O events from the completion queue

SYNOPSIS

#include <linux/time.h>
#include <libaio.h>

int io_getevents(aio_context_t ctx_id, long min_nr, long nr,
                 struct io_event *events, struct timespec *timeout);

DESCRIPTION

io_getevents() attempts to read at least min_nr events and up to nr events from the completion queue of the AIO context specified by ctx_id. timeout specifies the amount of time to wait for events, where a NULL timeout waits until at least min_nr events have been seen. Note that timeout is relative and will be updated if not NULL and the operation blocks.

RETURN VALUE

On success, io_getevents() returns the number of events read: 0 if no events are available or < min_nr if the timeout has elapsed; on failure, it returns one of the errors listed under ERRORS.

ERRORS

EINVAL
ctx_id is invalid. min_nr is out of range or nr is out of range.
EFAULT
Either events or timeout is an invalid pointer.
ENOSYS
io_getevents() is not implemented on this architecture.

VERSIONS

The asynchronous I/O system calls first appeared in Linux 2.5, August 2002.

CONFORMING TO

io_getevents() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO

io_setup(2),

io_submit(2),

io_getevents(2),

io_cancel(2),

io_destroy(2)


io_cancel(2)

IO_CANCEL

Section: Linux Programmer's Manual (2)
Updated: 2003-02-21 Return to Main Contents

NAME

io_cancel - cancel an outstanding asynchronous I/O operation

SYNOPSIS

#include <libaio.h>

int io_cancel(aio_context_t ctx_id, struct iocb *iocb,
              struct io_event *result);

DESCRIPTION

io_cancel() attempts to cancel an asynchronous I/O operation previously submitted with io_submit(2). ctx_id is the AIO context ID of the operation to be canceled. If the AIO context is found, the event will be canceled and then copied into the memory pointed to by result without being placed into the completion queue.

RETURN VALUE

io_cancel() returns 0 on success; on failure, it returns one of the errors listed under ERRORS.

ERRORS

EINVAL
The AIO context specified by ctx_id is invalid.
EFAULT
One of the data structures points to invalid data.
EAGAIN
The iocb specified was not canceled.
ENOSYS
io_cancel() is not implemented on this architecture.

VERSIONS

The asynchronous I/O system calls first appeared in Linux 2.5, August 2002.

CONFORMING TO

io_cancel() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO

io_setup(2),

io_destroy(2),

io_getevents(2),

io_submit(2)


set_thread_area(2)

SET_THREAD_AREA

Section: Linux Programmer's Manual (2)
Updated: 2003-02-21 Return to Main Contents

NAME

set_thread_area - Set a Thread Local Storage (TLS) area

SYNOPSIS

#include <linux/unistd.h>
#include <asm/ldt.h>

int set_thread_area(struct user_desc *u_info);

DESCRIPTION

set_thread_area() sets an entry in the current thread's Thread Local Storage (TLS) array. The TLS array entry set by set_thread_area() corresponds to the value of u_info->entry_number passed in by the user. If this value is in bounds, set_thread_area() copies the TLS descriptor pointed to by u_info into the thread's TLS array.

When set_thread_area() is passed an entry_number of -1, it uses a free TLS entry. If set_thread_area() finds a free TLS entry, the value of u_info->entry_number is set upon return to show which entry was changed.

RETURN VALUE

set_thread_area() returns 0 on success, and -1 on failure, with errno set appropriately.

ERRORS

EINVAL
u_info->entry_number is out of bounds.
EFAULT
u_info is an invalid pointer.
ESRCH
A free TLS entry could not be located.

VERSIONS

A version of set_thread_area() first appeared in Linux 2.5.29.

CONFORMING TO

set_thread_area() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO

get_thread_area(2)


semtimedop (2)

 Continue to this page.


fstatvfs (2)

 Continue to this page.


sstk(2)

SSTK

Section: BSD planned (2)
Updated: 2003-11-11 Return to Main Contents

NAME

sstk - change stack size

SYNOPSIS

caddr_t sstk(int incr);

DESCRIPTION

(From the 4.3BSD Architecture Manual)

Each process begins execution with three logical areas of memories called text, data and stack. The text area is read-only and shared, while the data and stack areas are private to the process. Both the data and stack areas may be extended and contracted on program request. The call

caddr_t addr = sbrk(incr);

changes the size of the data area by incr bytes and returns the new end of the data area, while

caddr_t addr = sstk(incr);

changes the size of the stack area. The stack area is also automatically extended as needed. On the VAX the text and data areas are adjacent in the P0 region, while the stack section is in the P1 region, and grows downward.

NOTE

This call is not supported in 4.3BSD or 4.4BSD or glibc or Linux or any other known Unix-like system. Some systems have a routine of this name that returns ENOSYS.

SEE ALSO

sbrk(2)


posix_fadvise(2)

POSIX_FADVISE

Section: Linux Programmer's Manual (2)
Updated: 2003-02-14 Return to Main Contents

NAME

posix_fadvise - predeclare an access pattern for file data

SYNOPSIS

#define _XOPEN_SOURCE 600
#include <fcntl.h>

int posix_fadvise(int fd, off_t offset, off_t len, int advice);

DESCRIPTION

Programs can use posix_fadvise() to announce an intention to access file data in a specific pattern in the future, thus allowing the kernel to perform appropriate optimizations.

The advice applies to a (not necessarily existent) region starting at offset and extending for len bytes (or until the end of the file if len is 0) within the file referred to by fd. The advice is not binding; it merely constitutes an expectation on behalf of the application.

Permissible values for advice include:

POSIX_FADV_NORMAL
Indicates that the application has no advice to give about its access pattern for the specified data. If no advice is given for an open file, this is the default assumption.
POSIX_FADV_SEQUENTIAL
The application expects to access the specified data sequentially (with lower offsets read before higher ones).
POSIX_FADV_RANDOM
The specified data will be accessed in random order.
POSIX_FADV_NOREUSE
The specified data will be accessed only once.
POSIX_FADV_WILLNEED
The specified data will be accessed in the near future.
POSIX_FADV_DONTNEED
The specified data will not be accessed in the near future.

RETURN VALUE

On success, zero is returned. On error, an error number is returned.

ERRORS

EBADF
The fd argument was not a valid file descriptor.
EINVAL
An invalid value was specified for advice.
ESPIPE
The specified file descriptor refers to a pipe or FIFO. (Linux actually returns EINVAL in this case.)

VERSIONS

posix_fadvise() appeared in kernel 2.5.60. Glibc support has been provided since version 2.2.

CONFORMING TO

POSIX.1-2001. Note that the type of the len parameter was changed from size_t to off_t in POSIX.1-2003 TC1.

NOTES

Under Linux, POSIX_FADV_NORMAL sets the readahead window to the default size for the backing device; POSIX_FADV_SEQUENTIAL doubles this size, and POSIX_FADV_RANDOM disables file readahead entirely. These changes affect the entire file, not just the specified region (but other open file handles to the same file are unaffected).

POSIX_FADV_WILLNEED initiates a non-blocking read of the specified region into the page cache. The amount of data read may be decreased by the kernel depending on virtual memory load. (A few megabytes will usually be fully satisfied, and more is rarely useful.)

In kernels before 2.6.18, POSIX_FADV_NOREUSE had the same semantics as POSIX_FADV_WILLNEED. This was probably a bug; since kernel 2.6.18, this flag is a no-op.

POSIX_FADV_DONTNEED attempts to free cached pages associated with the specified region. This is useful, for example, while streaming large files. A program may periodically request the kernel to free cached data that has already been used, so that more useful cached pages are not discarded instead.

Pages that have not yet been written out will be unaffected, so if the application wishes to guarantee that pages will be released, it should call fsync(2) or fdatasync(2) first.

BUGS

In kernels before 2.6.6, if len was specified as 0, then this was interpreted literally as "zero bytes", rather than as meaning "all bytes through to the end of the file".

SEE ALSO

posix_madvise(2), readahead(2), posix_fallocate(3), feature_test_macros(7)


io_setup(2)

IO_SETUP

Section: Linux Programmer's Manual (2)
Updated: 2003-02-21 Return to Main Contents

NAME

io_setup - create an asynchronous I/O context

SYNOPSIS

#include <libaio.h>

int io_setup(unsigned nr_events, aio_context_t *ctxp);

DESCRIPTION

io_setup() creates an asynchronous I/O context capable of receiving at least nr_events. ctxp must not point to an AIO context that already exists, and must be initialized to 0 prior to the call. On successful creation of the AIO context, *ctxp is filled in with the resulting handle.

RETURN VALUE

io_setup() returns 0 on success; on failure, it returns one of the errors listed under ERRORS.

ERRORS

EINVAL
ctxp is not initialized, or the specified nr_events exceeds internal limits. nr_events should be greater than 0.
EFAULT
An invalid pointer is passed for ctxp.
ENOMEM
Insufficient kernel resources are available.
EAGAIN
The specified nr_events exceeds the user's limit of available events.
ENOSYS
io_setup() is not implemented on this architecture.

VERSIONS

The asynchronous I/O system calls first appeared in Linux 2.5, August 2002.

CONFORMING TO

io_setup() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO

io_destroy(2),

io_getevents(2),

io_submit(2),

io_cancel(2)


exit_group(2)

EXIT_GROUP

Section: Linux Programmer's Manual (2)
Updated: 2004-10-12 Return to Main Contents

NAME

exit_group - exit all threads in a process

SYNOPSIS

#include <linux/unistd.h>

void exit_group(int status);

DESCRIPTION

This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's thread group.

RETURN VALUE

This system call does not return.

VERSIONS

This call is present since Linux 2.5.35.

CONFORMING TO

This call is Linux specific.

SEE ALSO

exit(2)


lgetxattr (2)

 Continue to this page.


statvfs(2)

STATVFS

Section: Linux Programmer's Manual (2)
Updated: 2003-08-22 Return to Main Contents

NAME

statvfs, fstatvfs - get file system statistics

SYNOPSIS

#include <sys/statvfs.h>

int statvfs(const char *path, struct statvfs *buf);
int fstatvfs(int fd, struct statvfs *buf);

DESCRIPTION

The function statvfs() returns information about a mounted file system. path is the pathname of any file within the mounted filesystem. buf is a pointer to a statvfs structure defined approximately as follows:

struct statvfs {
    unsigned long  f_bsize;    /* file system block size */
    unsigned long  f_frsize;   /* fragment size */
    fsblkcnt_t     f_blocks;   /* size of fs in f_frsize units */
    fsblkcnt_t     f_bfree;    /* # free blocks */
    fsblkcnt_t     f_bavail;   /* # free blocks for non-root */
    fsfilcnt_t     f_files;    /* # inodes */
    fsfilcnt_t     f_ffree;    /* # free inodes */
    fsfilcnt_t     f_favail;   /* # free inodes for non-root */
    unsigned long  f_fsid;     /* file system ID */
    unsigned long  f_flag;     /* mount flags */
    unsigned long  f_namemax;  /* maximum filename length */
};

Here the types fsblkcnt_t and fsfilcnt_t are defined in <sys/types.h>. Both used to be unsigned long.

The field f_flag is a bit mask (of mount flags, see mount(8)). Bits defined by POSIX are

ST_RDONLY
Read-only file system.
ST_NOSUID
Set-user-ID/set-group-ID bits are ignored by exec(3).

It is unspecified whether all members of the returned struct have meaningful values on all filesystems.

fstatvfs() returns the same information about an open file referenced by descriptor fd.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES
(statvfs()) Search permission is denied for a component of the path prefix of path. (See also path_resolution(7).)
EBADF
(fstatvfs()) fd is not a valid open file descriptor.
EFAULT
Buf or path points to an invalid address.
EINTR
This call was interrupted by a signal.
EIO
An I/O error occurred while reading from the file system.
ELOOP
(statvfs()) Too many symbolic links were encountered in translating path.
ENAMETOOLONG
(statvfs()) path is too long.
ENOENT
(statvfs()) The file referred to by path does not exist.
ENOMEM
Insufficient kernel memory was available.
ENOSYS
The file system does not support this call.
ENOTDIR
(statvfs()) A component of the path prefix of path is not a directory.
EOVERFLOW
Some values were too large to be represented in the returned struct.

CONFORMING TO

POSIX.1-2001

NOTES

The Linux kernel has system calls statfs(2) and fstatfs(2) to support this library call.

The current glibc implementations of

   pathconf(path, _PC_REC_XFER_ALIGN);
   pathconf(path, _PC_ALLOC_SIZE_MIN);
   pathconf(path, _PC_REC_MIN_XFER_SIZE);

respectively use the f_frsize, f_frsize, and f_bsize fields of the return value of statvfs(path,buf).

SEE ALSO

statfs(2)


lsetxattr (2)

 Continue to this page.


lremovexattr (2)

 Continue to this page.


epoll_ctl(2)

EPOLL_CTL

Section: Linux Programmer's Manual (2)
Updated: 2002-10-23 Return to Main Contents

NAME

epoll_ctl - control interface for an epoll descriptor

SYNOPSIS

#include <sys/epoll.h>

int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)

DESCRIPTION

Control an epoll descriptor, epfd, by requesting that the operation op be performed on the target file descriptor, fd. The event describes the object linked to the file descriptor fd. The struct epoll_event is defined as :

typedef union epoll_data {
    void *ptr;
    int fd;
    __uint32_t u32;
    __uint64_t u64;
} epoll_data_t;

struct epoll_event {
    __uint32_t events;      /* Epoll events */
    epoll_data_t data;      /* User data variable */
};

The events member is a bit set composed using the following available event types :

EPOLLIN
The associated file is available for read(2) operations.
EPOLLOUT
The associated file is available for write(2) operations.
EPOLLRDHUP (since kernel 2.6.17)
Stream socket peer closed connection, or shut down writing half of connection. (This flag is especially useful for writing simple code to detect peer shutdown when using Edge Triggered monitoring.)
EPOLLPRI
There is urgent data available for read(2) operations.
EPOLLERR
Error condition happened on the associated file descriptor. epoll_wait(2) will always wait for this event; it is not necessary to set it in events.
EPOLLHUP
Hang up happened on the associated file descriptor. epoll_wait(2) will always wait for this event; it is not necessary to set it in events.
EPOLLET
Sets the Edge Triggered behavior for the associated file descriptor. The default behavior for epoll is Level Triggered. See epoll(7) for more detailed information about Edge and Level Triggered event distribution architectures.
EPOLLONESHOT (since kernel 2.6.2)
Sets the one-shot behavior for the associated file descriptor. This means that after an event is pulled out with epoll_wait(2) the associated file descriptor is internally disabled and no other events will be reported by the epoll interface. The user must call epoll_ctl(2) with EPOLL_CTL_MOD to re-enable the file descriptor with a new event mask.

The epoll interface supports all file descriptors that support poll(2). Valid values for the op parameter are :

EPOLL_CTL_ADD
Add the target file descriptor fd to the epoll descriptor epfd and associate the event event with the internal file linked to fd.
EPOLL_CTL_MOD
Change the event event associated with the target file descriptor fd.
EPOLL_CTL_DEL
Remove the target file descriptor fd from the epoll file descriptor, epfd. The event is ignored and can be NULL (but see BUGS below).

RETURN VALUE

When successful, epoll_ctl(2) returns zero. When an error occurs, epoll_ctl(2) returns -1 and errno is set appropriately.

ERRORS

EBADF
epfd or fd is not a valid file descriptor.
EEXIST
op was EPOLL_CTL_ADD, and the supplied file descriptor fd is already in epfd.
EINVAL
epfd is not an epoll file descriptor, or fd is the same as epfd, or the requested operation op is not supported by this interface.
ENOENT
op was EPOLL_CTL_MOD or EPOLL_CTL_DEL, and fd is not in epfd.
ENOMEM
There was insufficient memory to handle the requested op control operation.
EPERM
The target file fd does not support epoll.

CONFORMING TO

epoll_ctl(2) is Linux specific, and was introduced in kernel 2.5.44.

BUGS

In kernel versions before 2.6.9, the EPOLL_CTL_DEL operation required a non-NULL pointer in event, even though this argument is ignored. Since kernel 2.6.9, event can be specified as NULL when using EPOLL_CTL_DEL.

SEE ALSO

epoll_create(2), epoll_wait(2), poll(2), epoll(7)


set_tid_address(2)

SET_TID_ADDRESS

Section: Linux Programmer's Manual (2)
Updated: 2004-09-10 Return to Main Contents

NAME

set_tid_address - set pointer to thread ID

SYNOPSIS

#include <linux/unistd.h>

long set_tid_address(int *tidptr);

DESCRIPTION

The kernel keeps for each process two values called set_child_tid and clear_child_tid that are NULL by default.

set_child_tid

If a process is started using clone(2) with the CLONE_CHILD_SETTID flag, set_child_tid is set to child_tidptr, the fifth parameter of that system call.

When set_child_tid is set, the very first thing the new process does is writing its PID at this address.

clear_child_tid

If a process is started using clone(2) with the CLONE_CHILD_CLEARTID flag, clear_child_tid is set to child_tidptr, the fifth parameter of that system call.

The system call set_tid_address() sets the clear_child_tid value for the calling process to tidptr.

When clear_child_tid is set, and the process exits, and the process was sharing memory with other processes or threads, then 0 is written at this address, and a futex(child_tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); call is done. (That is, wake a single process waiting on this futex.) Errors are ignored.

RETURN VALUE

set_tid_address() always returns the PID of the calling process.

ERRORS

set_tid_address() always succeeds.

VERSIONS

This call is present since Linux 2.5.48. Details as given here are valid since Linux 2.5.49.

CONFORMING TO

This system call is Linux specific.

SEE ALSO

clone(2), futex(2)


getxattr(2)

GETXATTR

Section: Linux Programmer's Manual (2)
Updated: 2001-12-01 Return to Main Contents

NAME

getxattr, lgetxattr, fgetxattr - retrieve an extended attribute value

SYNOPSIS

#include <sys/types.h>
#include <attr/xattr.h>

ssize_t getxattr(const char *path, const char *name,
                 void *value, size_t size);
ssize_t lgetxattr(const char *path, const char *name,
                 void *value, size_t size);
ssize_t fgetxattr(int filedes, const char *name,
                 void *value, size_t size);

DESCRIPTION

Extended attributes are name:value pairs associated with inodes (files, directories, symbolic links, etc). They are extensions to the normal attributes which are associated with all inodes in the system (i.e., the stat(2) data). A complete overview of extended attributes concepts can be found in attr(5).

getxattr() retrieves the value of the extended attribute identified by name and associated with the given path in the filesystem. The length of the attribute value is returned.

lgetxattr() is identical to getxattr(), except in the case of a symbolic link, where the link itself is interrogated, not the file that it refers to.

fgetxattr() is identical to getxattr(), only the open file pointed to by filedes (as returned by open(2)) is interrogated in place of path.

An extended attribute name is a simple null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode. The value of an extended attribute is a chunk of arbitrary textual or binary data of specified length.

An empty buffer of size zero can be passed into these calls to return the current size of the named extended attribute, which can be used to estimate the size of a buffer which is sufficiently large to hold the value associated with the extended attribute.

The interface is designed to allow guessing of initial buffer sizes, and to enlarge buffers when the return value indicates that the buffer provided was too small.

RETURN VALUE

On success, a positive number is returned indicating the size of the extended attribute value. On failure, -1 is returned and errno is set appropriately.

If the named attribute does not exist, or the process has no access to this attribute, errno is set to ENOATTR.

If the size of the value buffer is too small to hold the result, errno is set to ERANGE.

If extended attributes are not supported by the filesystem, or are disabled, errno is set to ENOTSUP.

The errors documented for the stat(2) system call are also applicable here.

VERSIONS

These system calls have been available on Linux since kernel 2.4; glibc support is provided since version 2.3.

CONFORMING TO

These system calls are Linux specific.

SEE ALSO

getfattr(1), setfattr(1), listxattr(2), open(2), removexattr(2), setxattr(2), stat(2), attr(5)


get_thread_area(2)

GET_THREAD_AREA

Section: Linux Programmer's Manual (2)
Updated: 2003-02-21 Return to Main Contents

NAME

get_thread_area - Get a Thread Local Storage (TLS) area

SYNOPSIS

#include <linux/unistd.h>
#include <asm/ldt.h>

int get_thread_area(struct user_desc *u_info);

DESCRIPTION

get_thread_area() returns an entry in the current thread's Thread Local Storage (TLS) array. The index of the entry corresponds to the value of u_info->entry_number, passed in by the user. If the value is in bounds, get_thread_area() copies the corresponding TLS entry into the area pointed to by u_info.

RETURN VALUE

get_thread_area() returns 0 on success. Otherwise, it returns -1 and sets errno appropriately.

ERRORS

EFAULT
u_info is an invalid pointer.
EINVAL
u_info->entry_number is out of bounds.

VERSIONS

A version of get_thread_area() first appeared in Linux 2.5.32.

CONFORMING TO

get_thread_area() is Linux specific and should not be used in programs that are intended to be portable.

SEE ALSO

modify_ldt(2), set_thread_area(2)


removexattr(2)

REMOVEXATTR

Section: Linux Programmer's Manual (2)
Updated: 2001-12-01 Return to Main Contents

NAME

removexattr, lremovexattr, fremovexattr - remove an extended attribute

SYNOPSIS

#include <sys/types.h>
#include <attr/xattr.h>

int removexattr(const char *path, const char *name);
int lremovexattr(const char *path, const char *name);
int fremovexattr(int filedes, const char *name);

DESCRIPTION

Extended attributes are name:value pairs associated with inodes (files, directories, symbolic links, etc). They are extensions to the normal attributes which are associated with all inodes in the system (i.e., the stat(2) data). A complete overview of extended attributes concepts can be found in attr(5).

removexattr() removes the extended attribute identified by name and associated with the given path in the filesystem.

lremovexattr() is identical to removexattr(), except in the case of a symbolic link, where the extended attribute is removed from the link itself, not the file that it refers to.

fremovexattr() is identical to removexattr(), only the extended attribute is removed from the open file pointed to by filedes (as returned by open(2)) in place of path.

An extended attribute name is a simple null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode.

RETURN VALUE

On success, zero is returned. On failure, -1 is returned and errno is set appropriately.

If the named attribute does not exist, errno is set to ENOATTR.

If extended attributes are not supported by the filesystem, or are disabled, errno is set to ENOTSUP.

The errors documented for the stat(2) system call are also applicable here.

VERSIONS

These system calls have been available on Linux since kernel 2.4; glibc support is provided since version 2.3.

CONFORMING TO

These system calls are Linux specific.

SEE ALSO

getfattr(1), setfattr(1), getxattr(2), listxattr(2), open(2), setxattr(2), stat(2), attr(5)


rt_sigreturn (2)

 Continue to this page.


get_kernel_syms(2)

GET_KERNEL_SYMS

Section: Linux Programmer's Manual (2)
Updated: 2007-06-03 Return to Main Contents

NAME

get_kernel_syms - retrieve exported kernel and module symbols

SYNOPSIS

#include <linux/module.h>

int get_kernel_syms(struct kernel_sym *table);

DESCRIPTION

If table is NULL, get_kernel_syms() returns the number of symbols available for query. Otherwise it fills in a table of structures:

struct kernel_sym {
    unsigned long value;
    char          name[60];
};

The symbols are interspersed with magic symbols of the form #module-name with the kernel having an empty name. The value associated with a symbol of this form is the address at which the module is loaded.

The symbols exported from each module follow their magic module tag and the modules are returned in the reverse of the order in which they were loaded.

RETURN VALUE

On success, returns the number of symbols copied to table. On error, -1 is returned and errno is set appropriately.

ERRORS

There is only one possible error return:
ENOSYS
get_kernel_syms() is not supported in this version of the kernel.

VERSIONS

This system call is only present on Linux up until kernel 2.4; it was removed in Linux 2.6.

CONFORMING TO

get_kernel_syms() is Linux specific.

BUGS

There is no way to indicate the size of the buffer allocated for table. If symbols have been added to the kernel since the program queried for the symbol table size, memory will be corrupted.

The length of exported symbol names is limited to 59 characters.

Because of these limitations, this system call is deprecated in favor of query_module(2) (which is itself nowadays deprecated in favor of other interfaces described on its manual page).

SEE ALSO

create_module(2), delete_module(2), init_module(2), query_module(2)


rt_sigsuspend (2)

 Continue to this page.


mkdirat(2)

MKDIRAT

Section: Linux Programmer's Manual (2)
Updated: 2006-04-06 Return to Main Contents

NAME

mkdirat - create a directory relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <sys/stat.h>

int mkdirat(int dirfd, const char *pathname, mode_t mode);

DESCRIPTION

The mkdirat() system call operates in exactly the same way as mkdir(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by mkdir(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like mkdir(2)).

If pathname is absolute, then dirfd is ignored.

RETURN VALUE

On success, mkdirat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for mkdir(2) can also occur for mkdirat(). The following additional errors can occur for mkdirat():
EBADF
dirfd is not a valid file descriptor.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

mkdirat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for mkdirat().

SEE ALSO

mkdir(2), openat(2), path_resolution(7)


sync_file_range(2)

SYNC_FILE_RANGE

Section: Linux Programmer's Manual (2)
Updated: 2006-07-05 Return to Main Contents

NAME

sync_file_range - sync a file segment with disk

SYNOPSIS

#define _GNU_SOURCE
#include <fcntl.h>

int sync_file_range(int fd, off64_t offset, off64_t nbytes,
                    unsigned int flags);

DESCRIPTION

sync_file_range() permits fine control when synchronising the open file referred to by the file descriptor fd with disk.

offset is the starting byte of the file range to be synchronized. nbytes specifies the length of the range to be synchronized, in bytes; if nbytes is zero, then all bytes from offset through to the end of file are synchronized. Synchronization is in units of the system page size: offset is rounded down to a page boundary; (offset+nbytes-1) is rounded up to a page boundary.

The flags bit-mask argument can include any of the following values:

SYNC_FILE_RANGE_WAIT_BEFORE
Wait upon write-out of all pages in the specified range that have already been submitted to the device driver for write-out before performing any write.
SYNC_FILE_RANGE_WRITE
Initiate write-out of all dirty pages in the specified range which are not presently submitted write-out.
SYNC_FILE_RANGE_WAIT_AFTER
Wait upon write-out of all pages in the range after performing any write.

Specifying flags as 0 is permitted, as a no-op.

Some details

None of these operations write out the file's metadata. Therefore, unless the application is strictly performing overwrites of already-instantiated disk blocks, there are no guarantees that the data will be available after a crash.

SYNC_FILE_RANGE_WAIT_BEFORE and SYNC_FILE_RANGE_WAIT_AFTER will detect any I/O errors or ENOSPC conditions and will return these to the caller.

Useful combinations of the flags bits are:

SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE
Ensures that all pages in the specified range which were dirty when sync_file_range() was called are placed under write-out. This is a start-write-for-data-integrity operation.
SYNC_FILE_RANGE_WRITE
Start write-out of all dirty pages in the specified range which are not presently under write-out. This is an asynchronous flush-to-disk operation. This is not suitable for data integrity operations.
SYNC_FILE_RANGE_WAIT_BEFORE (or SYNC_FILE_RANGE_WAIT_AFTER)
Wait for completion of write-out of all pages in the specified range. This can be used after an earlier SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE operation to wait for completion of that operation, and obtain its result.
SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER
This is a traditional fdatasync(2) operation. It is a write-for-data-integrity operation that will ensure that all pages in the specified range which were dirty when sync_file_range() was called are committed to disk.

RETURN VALUE

On success, sync_file_range() returns 0; on failure -1 is returned and errno is set to indicate the error.

ERRORS

EBADF
fd is not a valid file descriptor.
EIO
I/O error.
EINVAL
flags specifies an invalid bit; or offset or nbytes is invalid.
ENOMEM
Out of memory.
ENOSPC
Out of disk space.
ESPIPE
fd refers to something other than a regular file, a block device, a directory, or a symbolic link.

VERSIONS

sync_file_range() appeared on Linux in kernel 2.6.17.

CONFORMING TO

This system call is Linux specific, and should be avoided in portable programs.

SEE ALSO

fdatasync(2), fsync(2), msync(2), sync(2), feature_test_macros(7)


tee(2)

TEE

Section: Linux Programmer's Manual (2)
Updated: 2006-04-28 Return to Main Contents

NAME

tee - duplicating pipe content

SYNOPSIS

#define _GNU_SOURCE
#include <fcntl.h>

long tee(int fd_in, int fd_out, size_t len, unsigned int flags);

DESCRIPTION

tee() duplicates up to len bytes of data from the pipe referred to by the file descriptor fd_in to the pipe referred to by the file descriptor fd_out. It does not consume the data that is duplicated from fd_in; therefore, that data can be copied by a subsequent splice(2).

flags is a series of modifier flags, which share the name space with splice(2) and vmsplice(2):

SPLICE_F_MOVE
Currently has no effect for tee(); see splice(2).
SPLICE_F_NONBLOCK
Do not block on I/O; see splice(2) for further details.
SPLICE_F_MORE
Currently has no effect for tee(), but may be implemented in the future; see splice(2).
SPLICE_F_GIFT
Unused for tee(); see vmsplice(2).

RETURN VALUE

Upon successful completion, tee() returns the number of bytes that were duplicated between the input and output. A return value of 0 means that there was no data to transfer, and it would not make sense to block, because there are no writers connected to the write end of the pipe referred to by fd_in.

On error, tee() returns -1 and errno is set to indicate the error.

ERRORS

EINVAL
fd_in or fd_out does not refer to a pipe; or fd_in and fd_out refer to the same pipe.
ENOMEM
Out of memory.

VERSIONS

The tee(2) system call first appeared in Linux 2.6.17.

CONFORMING TO

This system call is Linux specific.

NOTES

Conceptually, tee() copies the data between the two pipes. In reality no real data copying takes place though: under the covers, tee() assigns data in the output by merely grabbing a reference to the input.

EXAMPLE

The following example implements a basic tee(1) program using the tee(2) system call.

#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>

int
main(int argc, char *argv[])
{
    int fd;
    int len, slen;

    assert(argc == 2);

    fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    do {
        /*
         * tee stdin to stdout.
         */
        len = tee(STDIN_FILENO, STDOUT_FILENO,
                  INT_MAX, SPLICE_F_NONBLOCK);

        if (len < 0) {
            if (errno == EAGAIN)
                continue;
            perror("tee");
            exit(EXIT_FAILURE);
        } else
            if (len == 0)
                break;

        /*
         * Consume stdin by splicing it to a file.
         */
        while (len > 0) {
            slen = splice(STDIN_FILENO, NULL, fd, NULL,
                          len, SPLICE_F_MOVE);
            if (slen < 0) {
                perror("splice");
                break;
            }
            len -= slen;
        }
    } while (1);

    close(fd);
    exit(EXIT_SUCCESS);
}

SEE ALSO

splice(2), vmsplice(2), feature_test_macros(7)


mq_getsetattr(2)

MQ_GETSETATTR

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

mq_getsetattr - get/set message queue attributes

SYNOPSIS

#include <sys/types.h>
#include <mqueue.h>

mqd_t mq_getsetattr(mqd_t mqdes, struct mq_attr *newattr,
                 struct mq_attr *oldattr);

DESCRIPTION

Do not use this system call.

This is the low-level system call used to implement mq_getattr(3) and mq_setattr(3). For an explanation of how this system call operates, see the description of mq_setattr(3).

CONFORMING TO

This interface is non-standard; avoid its use.

NOTES

Glibc does not provide a wrapper for this system call; call it using syscall(2). (Actually, never call it unless you are writing a libc!)

SEE ALSO

mq_getattr(3), mq_overview(7)


fstatat(2)

FSTATAT

Section: Linux Programmer's Manual (2)
Updated: 2006-04-30 Return to Main Contents

NAME

fstatat - get file status relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <sys/stat.h>

int fstatat(int dirfd, const char *pathname, struct stat *buf,
            int flags);

DESCRIPTION

The fstatat() system call operates in exactly the same way as stat(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by stat(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like stat(2)).

If pathname is absolute, then dirfd is ignored.

flags can either be 0, or include the following flag:

AT_SYMLINK_NOFOLLOW
If pathname is a symbolic link, do not dereference it: instead return information about the link itself, like lstat(2). (By default, fstatat() dereferences symbolic links, like stat(2).)

RETURN VALUE

On success, fstatat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for stat(2) can also occur for fstatat(). The following additional errors can occur for fstatat():
EBADF
dirfd is not a valid file descriptor.
EINVAL
Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

fstatat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris.

NOTES

See openat(2) for an explanation of the need for fstatat().

SEE ALSO

openat(2), stat(2), path_resolution(7)


splice(2)

SPLICE

Section: Linux Programmer's Manual (2)
Updated: 2006-04-28 Return to Main Contents

NAME

splice - splice data to/from a pipe

SYNOPSIS

#define _GNU_SOURCE
#include <fcntl.h>

long splice(int fd_in, off_t *off_in, int fd_out,
            off_t *off_out, size_t len, unsigned int flags);

DESCRIPTION

splice() moves data between two file descriptors without copying between kernel address space and user address space. It transfers up to len bytes of data from the file descriptor fd_in to the file descriptor fd_out, where one of the descriptors must refer to a pipe.

If fd_in refers to a pipe, then off_in must be NULL. If fd_in does not refer to a pipe and off_in is NULL, then bytes are read from fd_in starting from the current file offset, and the current file offset is adjusted appropriately. If fd_in does not refer to a pipe and off_in is not NULL, then off_in must point to a buffer which specifies the starting offset from which bytes will be read from fd_in; in this case, the current file offset of fd_in is not changed. Analogous statements apply for out_fd and off_out.

The flags argument is a bit mask that is composed by ORing together zero or more of the following values:

SPLICE_F_MOVE
Attempt to move pages instead of copying. This is only a hint to the kernel: pages may still be copied if the kernel cannot move the pages from the pipe, or if the pipe buffers don't refer to full pages.
SPLICE_F_NONBLOCK
Do not block on I/O. This makes the splice pipe operations non-blocking, but splice() may nevertheless block because the file descriptors that are spliced to/from may block (unless they have the O_NONBLOCK flag set).
SPLICE_F_MORE
More data will be coming in a subsequent splice. This is a helpful hint when the fd_out refers to a socket (see also the description of MSG_MORE in send(2), and the description of TCP_CORK in tcp(7))
SPLICE_F_GIFT
Unused for splice(); see vmsplice(2).

RETURN VALUE

Upon successful completion, splice() returns the number of bytes spliced to or from the pipe. A return value of 0 means that there was no data to transfer, and it would not make sense to block, because there are no writers connected to the write end of the pipe referred to by fd_in.

On error, splice() returns -1 and errno is set to indicate the error.

ERRORS

EBADF
One or both file descriptors are not valid, or do not have proper read-write mode.
EINVAL
Target file system doesn't support splicing; neither of the descriptors refers to a pipe; or offset given for non-seekable device.
ENOMEM
Out of memory.
ESPIPE
Either off_in or off_out was not NULL, but the corresponding file descriptor refers to a pipe.

VERSIONS

The splice(2) system call first appeared in Linux 2.6.17.

CONFORMING TO

This system call is Linux specific.

NOTES

The three system calls splice(2), vmsplice(2), and tee(2)), provide userspace programs with full control over an arbitrary kernel buffer, implemented within the kernel using the same type of buffer that is used for a pipe. In overview, these system calls perform the following tasks:
splice()
moves data from the buffer to an arbitrary file descriptor, or vice versa, or from one buffer to another.
tee(2)
"copies" the data from one buffer to another.
vmsplice(2)
"copies" data from user space into the buffer.

Though we talk of copying, actual copies are generally avoided. The kernel does this by implementing a pipe buffer as a set of reference-counted pointers to pages of kernel memory. The kernel creates "copies" of pages in a buffer by creating new pointers (for the output buffer) referring to the pages, and increasing the reference counts for the pages: only pointers are copied, not the pages of the buffer.

EXAMPLE

See tee(2).

SEE ALSO

sendfile(2), splice(2), tee(2), feature_test_macros(7)


fchownat(2)

FCHOWNAT

Section: Linux Programmer's Manual (2)
Updated: 2006-05-05 Return to Main Contents

NAME

fchownat - change ownership of a file relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <unistd.h>

int fchownat(int dirfd, const char *pathname,
             uid_t owner, gid_t group, int flags);

DESCRIPTION

The fchownat() system call operates in exactly the same way as chown(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by chown(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like chown(2)).

If pathname is absolute, then dirfd is ignored.

flags can either be 0, or include the following flag:

AT_SYMLINK_NOFOLLOW
If pathname is a symbolic link, do not dereference it: instead operate on the link itself, like lchown(2). (By default, fchownat() dereferences symbolic links, like chown(2).)

RETURN VALUE

On success, fchownat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for chown(2) can also occur for fchownat(). The following additional errors can occur for fchownat():
EBADF
dirfd is not a valid file descriptor.
EINVAL
Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

fchownat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris.

NOTES

See openat(2) for an explanation of the need for fchownat().

SEE ALSO

chown(2), openat(2), path_resolution(7)


futimesat(2)

FUTIMESAT

Section: Linux Programmer's Manual (2)
Updated: 2006-05-05 Return to Main Contents

NAME

futimesat - change timestamps of a file relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <fcntl.h>

int futimesat(int dirfd, const char *pathname,
              const struct timeval times[2]);

DESCRIPTION

The futimesat() system call operates in exactly the same way as utimes(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by utimes(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like utimes(2)).

If pathname is absolute, then dirfd is ignored.

RETURN VALUE

On success, futimesat() returns a 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for utimes(2) can also occur for futimesat(). The following additional errors can occur for futimesat():
EBADF
dirfd is not a valid file descriptor.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

futimesat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris.

NOTES

Glibc Notes

If pathname is NULL, then the glibc futimesat() wrapper function updates the times for the file referred to by dirfd.

SEE ALSO

stat(2), utimes(2), futimes(3), path_resolution(7)


mbind(2)

MBIND

Section: Linux Programmer's Manual (2)
Updated: 2006-02-07 Return to Main Contents

NAME

mbind - Set memory policy for a memory range

SYNOPSIS

#include <numaif.h>

int mbind(void *start, unsigned long len, int policy,
          unsigned long *nodemask, unsigned long maxnode,
          unsigned flags);

cc ... -lnuma

DESCRIPTION

mbind() sets the NUMA memory policy for the memory range starting with start and continuing for len bytes. The memory of a NUMA machine is divided into multiple nodes. The memory policy defines in which node memory is allocated. mbind() only has an effect for new allocations; if the pages inside the range have been already touched before setting the policy, then the policy has no effect.

Available policies are MPOL_DEFAULT, MPOL_BIND, MPOL_INTERLEAVE, and MPOL_PREFERRED. All policies except MPOL_DEFAULT require the caller to specify the nodes to which the policy applies in the nodemask parameter. nodemask is a bitmask of nodes containing up to maxnode bits. The actual number of bytes transferred via this argument is rounded up to the next multiple of sizeof(unsigned long), but the kernel will only use bits up to maxnode. A NULL argument means an empty set of nodes.

The MPOL_DEFAULT policy is the default and means to use the underlying process policy (which can be modified with set_mempolicy(2)). Unless the process policy has been changed this means to allocate memory on the node of the CPU that triggered the allocation. nodemask should be specified as NULL.

The MPOL_BIND policy is a strict policy that restricts memory allocation to the nodes specified in nodemask. There won't be allocations on other nodes.

MPOL_INTERLEAVE interleaves allocations to the nodes specified in nodemask. This optimizes for bandwidth instead of latency. To be effective the memory area should be fairly large, at least 1MB or bigger.

MPOL_PREFERRED sets the preferred node for allocation. The kernel will try to allocate in this node first and fall back to other nodes if the preferred nodes is low on free memory. Only the first node in the nodemask is used. If no node is set in the mask, then the memory is allocated on the node of the CPU that triggered the allocation allocation).

If MPOL_MF_STRICT is passed in flags and policy is not MPOL_DEFAULT, then the call will fail with the error EIO if the existing pages in the mapping don't follow the policy. In 2.6.16 or later the kernel will also try to move pages to the requested node with this flag.

If MPOL_MF_MOVE is passed in flags, then an attempt will be made to move all the pages in the mapping so that they follow the policy. Pages that are shared with other processes are not moved. If MPOL_MF_STRICT is also specified, then the call will fail with the error EIO if some pages could not be moved.

If MPOL_MF_MOVE_ALL is passed in flags, then all pages in the mapping will be moved regardless of whether other processes use the pages. The calling process must be privileged (CAP_SYS_NICE) to use this flag. If MPOL_MF_STRICT is also specified, then the call will fail with the error EIO if some pages could not be moved.

RETURN VALUE

On success, mbind() returns 0; on error, -1 is returned and errno is set to indicate the error.

ERRORS

EFAULT
There was a unmapped hole in the specified memory range or a passed pointer was not valid.
EINVAL
An invalid value was specified for flags or mode; or start + len was less than start; or policy was MPOL_DEFAULT and nodemask pointed to a non-empty set; or policy was MPOL_BIND or MPOL_INTERLEAVE and nodemask pointed to an empty set,
ENOMEM
System out of memory.
EIO
MPOL_MF_STRICT was specified and an existing page was already on a node that does not follow the policy.

CONFORMING TO

This system call is Linux specific.

NOTES

NUMA policy is not supported on file mappings.

MPOL_MF_STRICT is ignored on huge page mappings right now.

It is unfortunate that the same flag, MPOL_DEFAULT, has different effects for mbind(2) and set_mempolicy(2). To select "allocation on the node of the CPU that triggered the allocation" (like set_mempolicy(2) MPOL_DEFAULT) when calling mbind(), specify a policy of MPOL_PREFERRED with an empty nodemask.

Versions and Library Support

The mbind(), get_mempolicy(2), and set_mempolicy(2) system calls were added to the Linux kernel with version 2.6.7. They are only available on kernels compiled with CONFIG_NUMA.

Support for huge page policy was added with 2.6.16. For interleave policy to be effective on huge page mappings the policied memory needs to be tens of megabytes or larger.

MPOL_MF_MOVE and MPOL_MF_MOVE_ALL are only available on Linux 2.6.16 and later.

These system calls should not be used directly. Instead, the higher level interface provided by the numa(3) functions in the numactl package is recommended. The numactl package is available at ftp://ftp.suse.com/pub/people/ak/numa/.

You can link with -lnuma to get system call definitions. libnuma is available in the numactl package. This package also has the numaif.h header.

SEE ALSO

numa(3), numactl(8), set_mempolicy(2), get_mempolicy(2), mmap(2)


ioprio_get (2)

 Continue to this page.


ioprio_set(2)

IOPRIO_GET

Section: Linux Programmer's Manual (2)
Updated: 2007-06-01 Return to Main Contents

NAME

ioprio_get, ioprio_set - get/set I/O scheduling class and priority

SYNOPSIS

int ioprio_get(int which, int who);
int ioprio_set(int which, int who, int ioprio);

DESCRIPTION

The ioprio_get() and ioprio_set() system calls respectively get and set the I/O scheduling class and priority of one or more processes.

The which and who arguments identify the process(es) on which the system calls operate. The which argument determines how who is interpreted, and has one of the following values:

IOPRIO_WHO_PROCESS
who is a process ID identifying a single process.
IOPRIO_WHO_PGRP
who is a process group ID identifying all the members of a process group.
IOPRIO_WHO_USER
who is a user ID identifying all of the processes that have a matching real UID.

If which is specified as IOPRIO_WHO_PGRP or IOPRIO_WHO_USER when calling ioprio_get(), and more than one process matches who, then the returned priority will be the highest one found among all of the matching processes. One priority is said to be higher than another one if it belongs to a higher priority class (IOPRIO_CLASS_RT is the highest priority class; IOPRIO_CLASS_IDLE is the lowest) or if it belongs to the same priority class as the other process but has a higher priority level (a lower priority number means a higher priority level).

The ioprio argument given to ioprio_set() is a bit mask that specifies both the scheduling class and the priority to be assigned to the target process(es). The following macros are used for assembling and dissecting ioprio values:

IOPRIO_PRIO_VALUE(class, data)
Given a scheduling class and priority (data), this macro combines the two values to produce an ioprio value, which is returned as the result of the macro.
IOPRIO_PRIO_CLASS(mask)
Given mask (an ioprio value), this macro returns its I/O class component, that is, one of the values IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, or IOPRIO_CLASS_IDLE.
IOPRIO_PRIO_DATA(mask)
Given mask (an ioprio value), this macro returns its priority (data) component.

See the NOTES section for more information on scheduling classes and priorities.

I/O priorities are supported for reads and for synchronous (O_DIRECT, O_SYNC) writes. I/O priorities are not supported for asynchronous writes because they are issued outside the context of the program dirtying the memory, and thus program-specific priorities do not apply.

RETURN VALUE

On success, ioprio_get() returns the ioprio value of the process with highest I/O priority of any of the processes that match the criteria specified in which and who. On error, -1 is returned, and errno is set to indicate the error.

On success, ioprio_set() returns 0. On error, -1 is returned, and errno is set to indicate the error.

ERRORS

EPERM
The calling process does not have the privilege needed to assign this ioprio to the specified process(es). See the NOTES section for more information on required privileges for ioprio_set().
ESRCH
No process(es) could be found that matched the specification in which and who.
EINVAL
Invalid value for which or ioprio. Refer to the NOTES section for available scheduler classes and priority levels for ioprio.

VERSIONS

These system calls have been available on Linux since kernel 2.6.13.

CONFORMING TO

These system calls are Linux specific.

NOTES

Glibc does not provide wrapper for these system calls; call them using syscall(2).

These system calls only have an effect when used in conjunction with an I/O scheduler that supports I/O priorities. As at kernel 2.6.17 the only such scheduler is the Completely Fair Queuing (CFQ) I/O scheduler.

Selecting an I/O Scheduler

I/O Schedulers are selected on a per-device basis via the special file /sys/block/<device>/queue/scheduler.

One can view the current I/O scheduler via the /sys file system. For example, the following command displays a list of all schedulers currently loaded in the kernel:

$ cat /sys/block/hda/queue/scheduler
noop anticipatory deadline [cfq]

The scheduler surrounded by brackets is the one actually in use for the device (hda in the example). Setting another scheduler is done by writing the name of the new scheduler to this file. For example, the following command will set the scheduler for the hda device to cfq:

$ su
Password:
# echo cfq > /sys/block/hda/queue/scheduler

The Completely Fair Queuing (CFQ) I/O Scheduler

Since v3 (aka CFQ Time Sliced) CFQ implements I/O nice levels similar to those of CPU scheduling. These nice levels are grouped in three scheduling classes each one containing one or more priority levels:
IOPRIO_CLASS_RT (1)
This is the real-time I/O class. This scheduling class is given higher priority than any other class: processes from this class are given first access to the disk every time. Thus this I/O class needs to be used with some care: one I/O real-time process can starve the entire system. Within the real-time class, there are 8 levels of class data (priority) that determine exactly how much time this process needs the disk for on each service. The highest real-time priority level is 0; the lowest is 7. In the future this might change to be more directly mappable to performance, by passing in a desired data rate instead.
IOPRIO_CLASS_BE (2)
This is the best-effort scheduling class, which is the default for any process that hasn't set a specific I/O priority. The class data (priority) determines how much I/O bandwidth the process will get. Best-effort priority levels are analogous to CPU nice values (see getpriority(2)). The priority level determines a priority relative to other processes in the best-effort scheduling class. Priority levels range from 0 (highest) to 7 (lowest).
IOPRIO_CLASS_IDLE (3)
This is the idle scheduling class. Processes running at this level only get I/O time when no one else needs the disk. The idle class has no class data. Attention is required when assigning this priority class to a process, since it may become starved if higher priority processes are constantly accessing the disk.

Refer to Documentation/block/ioprio.txt for more information on the CFQ I/O Scheduler and an example program.

Required permissions to set I/O priorities

Permission to change a process's priority is granted or denied based on two assertions:
Process ownership
An unprivileged process may only set the I/O priority of a process whose real UID matches the real or effective UID of the calling process. A process which has the CAP_SYS_NICE capability can change the priority of any process.
What is the desired priority
Attempts to set very high priorities (IOPRIO_CLASS_RT) or very low ones (IOPRIO_CLASS_IDLE) require the CAP_SYS_ADMIN capability.

A call to ioprio_set() must follow both rules, or the call will fail with the error EPERM.

BUGS

Glibc does not yet provide a suitable header file defining the function prototypes and macros described on this page. Suitable definitions can be found in linux/ioprio.h.

SEE ALSO

getpriority(2), open(2), capabilities(7)

Documentation/block/ioprio.txt in the kernel source tree.


inotify_add_watch(2)

INOTIFY_ADD_WATCH

Section: Linux Programmer's Manual (2)
Updated: 2006-02-07 Return to Main Contents

NAME

inotify_add_watch - add a watch to an initialized inotify instance

SYNOPSIS

#include <sys/inotify.h>

int inotify_add_watch(int fd, const char *pathname, uint32_t mask);

DESCRIPTION

inotify_add_watch() adds a new watch, or modifies an existing watch, for the file whose location is specified in pathname; the caller must have read permission for this file. The fd argument is a file descriptor referring to the inotify instance whose watch list is to be modified. The events to be monitored for pathname are specified in the mask bit-mask argument. See inotify(7) for a description of the bits that can be set in mask.

A successful call to inotify_add_watch() returns the unique watch descriptor associated with pathname for this inotify instance. If pathname was not previously being watched by this inotify instance, then the watch descriptor is newly allocated. If pathname was already being watched, then the descriptor for the existing watch is returned.

The watch descriptor is returned by later read(2)s from the inotify file descriptor. These reads fetch inotify_event structures indicating file system events; the returned watch descriptor identifies the object for which the event occurred.

RETURN VALUE

On success, inotify_add_watch() returns a non-negative watch descriptor. On error -1 is returned and errno is set appropriately.

ERRORS

EACCES
Read access to the given file is not permitted.
EBADF
The given file descriptor is not valid.
EFAULT
pathname points outside of the process's accessible address space.
EINVAL
The given event mask contains no legal events; or fd is not an inotify file descriptor.
ENOMEM
Insufficient kernel memory was available.
ENOSPC
The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource.

VERSIONS

Inotify was merged into the 2.6.13 Linux kernel.

CONFORMING TO

This system call is Linux specific.

SEE ALSO

inotify_init(2), inotify_rm_watch(2), inotify(7)


vm86old (2)

 Continue to this page.


query_module(2)

QUERY_MODULE

Section: Linux Programmer's Manual (2)
Updated: 2007-06-03 Return to Main Contents

NAME

query_module - query the kernel for various bits pertaining to modules

SYNOPSIS

#include <linux/module.h>

int query_module(const char *name, int which, void *buf,
                 size_t bufsize, size_t *ret);

DESCRIPTION

query_module() requests information from the kernel about loadable modules. The returned information is placed in the buffer pointed to by buf. The caller must specify the size of buf in bufsize. The precise nature and format of the returned information depend on the operation specified by which. Some operations require name to identify a currently loaded module, some allow name to be NULL, indicating the kernel proper.

The following values can be specified for which:

0
Returns success, if the kernel supports query_module(). Used to probe for availability of the system call.
QM_MODULES
Returns the names of all loaded modules. The returned buffer consists of a sequence of null-terminated strings; ret is set to the number of modules.
QM_DEPS
Returns the names of all modules used by the indicated module. The returned buffer consists of a sequence of null-terminated strings; ret is set to the number of modules.
QM_REFS
Returns the names of all modules using the indicated module. This is the inverse of QM_DEPS. The returned buffer consists of a sequence of null-terminated strings; ret is set to the number of modules.
QM_SYMBOLS
Returns the symbols and values exported by the kernel or the indicated module. The returned buffer is an array of structures of the following form

struct module_symbol {
    unsigned long value;
    unsigned long name;
};

followed by null-terminated strings. The value of name is the character offset of the string relative to the start of buf; ret is set to the number of symbols.

QM_INFO
Returns miscellaneous information about the indicated module. The output buffer format is:

struct module_info {
    unsigned long address;
    unsigned long size;
    unsigned long flags;
};

where address is the kernel address at which the module resides, size is the size of the module in bytes, and flags is a mask of MOD_RUNNING, MOD_AUTOCLEAN, etc. that indicates the current status of the module (see the kernel source file include/linux/module.h). ret is set to the size of the module_info structure.

RETURN VALUE

On success, zero is returned. On error, -1 is returned and errno is set appropriately.

ERRORS

EFAULT
At least one of name, buf, or ret was outside the program's accessible address space.
EINVAL
Invalid which; or name is NULL (indicating "the kernel"), but this is not permitted with the specified value of which.
ENOENT
No module by that name exists.
ENOSPC
The buffer size provided was too small. ret is set to the minimum size needed.
ENOSYS
query_module() is not supported in this version of the kernel.

CONFORMING TO

query_module() is Linux specific.

NOTES

This system call is only present on Linux up until kernel 2.4; it was removed in Linux 2.6. Some of the information that was available via query_module() can be obtained from /proc/modules, /proc/kallsyms, and /sys/modules.

SEE ALSO

create_module(2), delete_module(2), get_kernel_syms(2), init_module(2)


init_module(2)

INIT_MODULE

Section: Linux Programmer's Manual (2)
Updated: 2006-02-09 Return to Main Contents

NAME

init_module - initialize a loadable module entry

SYNOPSIS

#include <linux/module.h>

int init_module(const char *name, struct module *image);

DESCRIPTION

init_module() loads the relocated module image into kernel space and runs the module's init function.

The module image begins with a module structure and is followed by code and data as appropriate. The module structure is defined as follows:

struct module {
    unsigned long         size_of_struct;
    struct module        *next;
    const char           *name;
    unsigned long         size;
    long                  usecount;
    unsigned long         flags;
    unsigned int          nsyms;
    unsigned int          ndeps;
    struct module_symbol *syms;
    struct module_ref    *deps;
    struct module_ref    *refs;
    int                 (*init)(void);
    void                (*cleanup)(void);
    const struct exception_table_entry *ex_table_start;
    const struct exception_table_entry *ex_table_end;
#ifdef __alpha__
    unsigned long gp;
#endif
};

All of the pointer fields, with the exception of next and refs, are expected to point within the module body and be initialized as appropriate for kernel space, that is, relocated with the rest of the module.

This system call requires privilege.

RETURN VALUE

On success, zero is returned. On error, -1 is returned and errno is set appropriately.

ERRORS

EBUSY
The module's initialization routine failed.
EFAULT
name or image is outside the program's accessible address space.
EINVAL
Some image slot is filled in incorrectly, image->name does not correspond to the original module name, some image->deps entry does not correspond to a loaded module, or some other similar inconsistency.
ENOENT
No module by that name exists.
EPERM
The caller was not privileged (did not have the CAP_SYS_MODULE capability).

CONFORMING TO

init_module() is Linux specific.

SEE ALSO

create_module(2), delete_module(2), query_module(2)


set_mempolicy(2)

SET_MEMPOLICY

Section: Linux Programmer's Manual (2)
Updated: 2006-02-07 Return to Main Contents

NAME

set_mempolicy - set default NUMA memory policy for a process and its children.

SYNOPSIS

#include <numaif.h>

int set_mempolicy(int policy, unsigned long *nodemask,
                  unsigned long maxnode);

DESCRIPTION

set_mempolicy() sets the NUMA memory policy of the calling process to policy.

A NUMA machine has different memory controllers with different distances to specific CPUs. The memory policy defines in which node memory is allocated for the process.

This system call defines the default policy for the process; in addition a policy can be set for specific memory ranges using mbind(2). The policy is only applied when a new page is allocated for the process. For anonymous memory this is when the page is first touched by the application.

Available policies are MPOL_DEFAULT, MPOL_BIND, MPOL_INTERLEAVE, MPOL_PREFERRED. All policies except MPOL_DEFAULT require the caller to specify the nodes to which the policy applies in the nodemask parameter. nodemask is pointer to a bit field of nodes that contains up to maxnode bits. The bit field size is rounded to the next multiple of sizeof(unsigned long), but the kernel will only use bits up to maxnode.

The MPOL_DEFAULT policy is the default and means to allocate memory locally, i.e., on the node of the CPU that triggered the allocation. nodemask should be specified as NULL.

The MPOL_BIND policy is a strict policy that restricts memory allocation to the nodes specified in nodemask. There won't be allocations on other nodes.

MPOL_INTERLEAVE interleaves allocations to the nodes specified in nodemask. This optimizes for bandwidth instead of latency. To be effective the memory area should be fairly large, at least 1MB or bigger.

MPOL_PREFERRED sets the preferred node for allocation. The kernel will try to allocate in this node first and fall back to other nodes if the preferred node is low on free memory. Only the first node in the nodemask is used. If no node is set in the mask, then the memory is allocated on the node of the CPU that triggered the allocation allocation (like MPOL_DEFAULT).

The memory policy is preserved across an execve(2), and is inherited by child processes created using fork(2) or clone(2).

RETURN VALUE

On success, set_mempolicy() returns 0; on error, -1 is returned and errno is set to indicate the error.

CONFORMING TO

This system call is Linux specific.

NOTES

Process policy is not remembered if the page is swapped out.

Versions and Library Support

See mbind(2).

SEE ALSO

mbind(2), get_mempolicy(2), numactl(8), numa(3)


inotify_rm_watch(2)

INOTIFY_RM_WATCH

Section: Linux Programmer's Manual (2)
Updated: 2006-02-07 Return to Main Contents

NAME

inotify_rm_watch - remove an existing watch from an inotify instance

SYNOPSIS

#include <sys/inotify.h>

int inotify_rm_watch(int fd, uint32_t wd);

DESCRIPTION

inotify_rm_watch() removes the watch associated with the watch descriptor wd from the inotify instance associated with the file descriptor fd.

Removing a watch causes an IN_IGNORED event to be generated for this watch descriptor. (See inotify(7).)

RETURN VALUE

On success, inotify_rm_watch() returns zero, or -1 if an error occurred (in which case, errno is set appropriately).

ERRORS

EBADF
fd is not a valid file descriptor.
EINVAL
The watch descriptor wd is not valid; or fd is not an inotify file descriptor.

VERSIONS

Inotify was merged into the 2.6.13 Linux kernel.

CONFORMING TO

This system call is Linux specific.

SEE ALSO

inotify_init(2), inotify_add_watch(2), inotify(7)


delete_module(2)

DELETE_MODULE

Section: Linux Programmer's Manual (2)
Updated: 2006-02-09 Return to Main Contents

NAME

delete_module - delete a loadable module entry

SYNOPSIS

#include <linux/module.h>

int delete_module(const char *name);

DESCRIPTION

delete_module() attempts to remove an unused loadable module entry. If name is NULL, all unused modules marked auto-clean will be removed. This system call requires privilege.

RETURN VALUE

On success, zero is returned. On error, -1 is returned and errno is set appropriately.

ERRORS

EBUSY
The module is in use.
EFAULT
name is outside the program's accessible address space.
EINVAL
name was an empty string.
ENOENT
No module by that name exists.
EPERM
The caller was not privileged (did not have the CAP_SYS_MODULE capability).

CONFORMING TO

delete_module() is Linux specific.

SEE ALSO

create_module(2), init_module(2), query_module(2)


mknodat(2)

MKNODAT

Section: Linux Programmer's Manual (2)
Updated: 2006-04-06 Return to Main Contents

NAME

mknodat - create a special or ordinary file relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <sys/stat.h>

int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);

DESCRIPTION

The mknodat() system call operates in exactly the same way as mknod(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by mknod(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like mknod(2)).

If pathname is absolute, then dirfd is ignored.

RETURN VALUE

On success, mknodat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for mknod(2) can also occur for mknodat(). The following additional errors can occur for mknodat():
EBADF
dirfd is not a valid file descriptor.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

mknodat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for mknodat().

SEE ALSO

mknod(2), openat(2), path_resolution(7)


create_module(2)

CREATE_MODULE

Section: Linux Programmer's Manual (2)
Updated: 2007-06-03 Return to Main Contents

NAME

create_module - create a loadable module entry

SYNOPSIS

#include <linux/module.h>

caddr_t create_module(const char *name, size_t size);

DESCRIPTION

create_module() attempts to create a loadable module entry and reserve the kernel memory that will be needed to hold the module. This system call requires privilege.

RETURN VALUE

On success, returns the kernel address at which the module will reside. On error -1 is returned and errno is set appropriately.

ERRORS

EEXIST
A module by that name already exists.
EFAULT
name is outside the program's accessible address space.
EINVAL
The requested size is too small even for the module header information.
ENOMEM
The kernel could not allocate a contiguous block of memory large enough for the module.
EPERM
The caller was not privileged (did not have the CAP_SYS_MODULE capability).
ENOSYS
create_module() is not supported in this version of the kernel.

VERSIONS

This system call is only present on Linux up until kernel 2.4; it was removed in Linux 2.6.

CONFORMING TO

create_module() is Linux specific.

SEE ALSO

init_module(2), delete_module(2), query_module(2)


vmsplice(2)

VMSPLICE

Section: Linux Programmer's Manual (2)
Updated: 2006-04-28 Return to Main Contents

NAME

vmsplice - splice user pages into a pipe

SYNOPSIS

#define _GNU_SOURCE
#include <fcntl.h>
#include <sys/uio.h>

long vmsplice(int fd, const struct iovec *iov,
              unsigned long nr_segs, unsigned int flags);

DESCRIPTION

The vmsplice() system call maps nr_segs ranges of user memory described by iov into a pipe. The file descriptor fd must refer to a pipe.

The pointer iov points to an array of iovec structures as defined in <sys/uio.h>:

struct iovec {
    void  *iov_base;            /* Starting address */
    size_t iov_len;             /* Number of bytes */
};

The flags argument is a bit mask that is composed by ORing together zero or more of the following values:

SPLICE_F_MOVE
Unused for vmsplice(); see splice(2).
SPLICE_F_NONBLOCK
Do not block on I/O; see splice(2) for further details.
SPLICE_F_MORE
Currently has no effect for vmsplice(), but may be implemented in the future; see splice(2).
SPLICE_F_GIFT
The user pages are a gift to the kernel. The application may not modify this memory ever, or page cache and on-disk data may differ. Gifting pages to the kernel means that a subsequent splice(2) SPLICE_F_MOVE can successfully move the pages; if this flag is not specified, then a subsequent splice(2) SPLICE_F_MOVE must copy the pages. Data must also be properly page aligned, both in memory and length.

RETURN VALUE

Upon successful completion, vmsplice() returns the number of bytes transferred to the pipe. On error, vmsplice() returns -1 and errno is set to indicate the error.

ERRORS

EBADF
fd either not valid, or doesn't refer to a pipe.
EINVAL
nr_segs is 0 or greater than IOV_MAX; or memory not aligned if SPLICE_F_GIFT set.
ENOMEM
Out of memory.

VERSIONS

The vmsplice(2) system call first appeared in Linux 2.6.17.

CONFORMING TO

This system call is Linux specific.

NOTES

vmsplice() follows the other vectorized read/write type functions when it comes to limitations on number of segments being passed in. This limit is IOV_MAX as defined in <limits.h>. At the time of this writing, that limit is 1024.

SEE ALSO

splice(2), tee(2), feature_test_macros(7)


openat(2)

OPENAT

Section: Linux Programmer's Manual (2)
Updated: 2006-03-06 Return to Main Contents

NAME

openat - open a file relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <fcntl.h>

int openat(int dirfd, const char *pathname, int flags);
int openat(int dirfd, const char *pathname, int flags, mode_t mode);

DESCRIPTION

The openat() system call operates in exactly the same way as open(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by open(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like open(2)).

If pathname is absolute, then dirfd is ignored.

RETURN VALUE

On success, openat() returns a new file descriptor. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for open(2) can also occur for openat(). The following additional errors can occur for openat():
EBADF
dirfd is not a valid file descriptor.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

openat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris.

NOTES

openat() and other similar system calls suffixed "at" are supported for two reasons.

First, openat() allows an application to avoid race conditions that could occur when using open(2) to open files in directories other than the current working directory. These race conditions result from the fact that some component of the directory prefix given to open(2) could be changed in parallel with the call to open(2). Such races can be avoided by opening a file descriptor for the target directory, and then specifying that file descriptor as the dirfd argument of openat().

Second, openat() allows the implementation of a per-thread "current working directory", via file descriptor(s) maintained by the application. (This functionality can also be obtained by tricks based on the use of /proc/self/fd/dirfd, but less efficiently.)

SEE ALSO

faccessat(2), fchmodat(2), fchownat(2), fstatat(2), futimesat(2), linkat(2), mkdirat(2), mknodat(2), open(2), readlinkat(2), renameat(2), symlinkat(2), unlinkat(2), mkfifoat(3) path_resolution(7)


readlinkat(2)

READLINKAT

Section: Linux Programmer's Manual (2)
Updated: 2006-07-21 Return to Main Contents

NAME

readlinkat - read value of a symbolic link relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <unistd.h>

int readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz);

DESCRIPTION

The readlinkat() system call operates in exactly the same way as readlink(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by readlink(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like readlink(2)).

If pathname is absolute, then dirfd is ignored.

RETURN VALUE

On success, readlinkat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for readlink(2) can also occur for readlinkat(). The following additional errors can occur for readlinkat():
EBADF
dirfd is not a valid file descriptor.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

readlinkat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for readlinkat().

SEE ALSO

openat(2), readlink(2), path_resolution(7)


unshare(2)

UNSHARE

Section: Linux Programmer's Manual (2)
Updated: 2005-03-10 Return to Main Contents

NAME

unshare - disassociate parts of the process execution context

SYNOPSIS

#include <sched.h>

int unshare(int flags);

DESCRIPTION

unshare() allows a process to disassociate parts of its execution context that are currently being shared with other processes. Part of the execution context, such as the namespace, is shared implicitly when a new process is created using fork(2) or vfork(2), while other parts, such as virtual memory, may be shared by explicit request when creating a process using clone(2).

The main use of unshare() is to allow a process to control its shared execution context without creating a new process.

The flags argument is a bit mask that specifies which parts of the execution context should be unshared. This argument is specified by ORing together zero or more of the following constants:

CLONE_FILES
Reverse the effect of the clone(2) CLONE_FILES flag. Unshare the file descriptor table, so that the calling process no longer shares its file descriptors with any other process.
CLONE_FS
Reverse the effect of the clone(2) CLONE_FS flag. Unshare file system attributes, so that the calling process no longer shares its root directory, current directory, or umask attributes with any other process. chroot(2), chdir(2), or umask(2)
CLONE_NEWNS
This flag has the same effect as the clone(2) CLONE_NEWNS flag. Unshare the namespace, so that the calling process has a private copy of its namespace which is not shared with any other process. Specifying this flag automatically implies CLONE_FS as well.

If flags is specified as zero, then unshare() is a no-op; no changes are made to the calling process's execution context.

RETURN VALUE

On success, zero returned. On failure, -1 is returned and errno is set to indicate the error.

ERRORS

EPERM
flags specified CLONE_NEWNS but the calling process was not privileged (did not have the CAP_SYS_ADMIN capability).
ENOMEM
Cannot allocate sufficient memory to copy parts of caller's context that need to be unshared.
EINVAL
An invalid bit was specified in flags.

VERSIONS

The unshare() system call was added to Linux in kernel 2.6.16.

CONFORMING TO

The unshare() system call is Linux specific.

NOTES

Not all of the process attributes that can be shared when a new process is created using clone(2) can be unshared using unshare(). In particular, as at kernel 2.6.16, unshare() does not implement flags that reverse the effects of CLONE_SIGHAND, CLONE_SYSVSEM, CLONE_THREAD, or CLONE_VM. Such functionality may be added in the future, if required.

SEE ALSO

clone(2), fork(2), vfork(2), Documentation/unshare.txt


unlinkat(2)

UNLINKAT

Section: Linux Programmer's Manual (2)
Updated: 2006-04-10 Return to Main Contents

NAME

unlinkat - remove a directory entry relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <fcntl.h>

int unlinkat(int dirfd, const char *pathname, int flags);

DESCRIPTION

The unlinkat() system call operates in exactly the same way as either unlink(2) or rmdir(2) (depending on whether or not flags includes the AT_REMOVEDIR flag) except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by unlink(2) and rmdir(2) for a relative pathname).

If the pathname given in pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like unlink(2) and rmdir(2)).

If the pathname given in pathname is absolute, then dirfd is ignored.

flags is a bit mask that can either be specified as 0, or by ORing together flag values that control the operation of unlinkat(). Currently only one such flags is defined:

AT_REMOVEDIR
By default, unlinkat() performs the equivalent of unlink(2) on pathname. If the AT_REMOVEDIR flag is specified, then performs the equivalent of rmdir(2) on pathname.

RETURN VALUE

On success, unlinkat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for unlink(2) and rmdir(2) can also occur for unlinkat(). The following additional errors can occur for unlinkat():
EBADF
dirfd is not a valid file descriptor.
EINVAL
An invalid flag value was specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

unlinkat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris.

NOTES

See openat(2) for an explanation of the need for unlinkat().

SEE ALSO

openat(2), rmdir(2), unlink(2), path_resolution(7)


inotify_init(2)

INOTIFY_INIT

Section: Linux Programmer's Manual (2)
Updated: 2006-02-07 Return to Main Contents

NAME

inotify_init - initialize an inotify instance

SYNOPSIS

#include <sys/inotify.h>

int inotify_init(void)

DESCRIPTION

inotify_init() initializes a new inotify instance and returns a file descriptor associated with a new inotify event queue.

RETURN VALUE

On success, inotify_init() returns a new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).

ERRORS

EMFILE
The user limit on the total number of inotify instances has been reached.
ENFILE
The system limit on the total number of file descriptors has been reached.
ENOMEM
Insufficient kernel memory is available.

VERSIONS

Inotify was merged into the 2.6.13 Linux kernel.

CONFORMING TO

This system call is Linux specific.

SEE ALSO

inotify_add_watch(2), inotify_rm_watch(2), inotify(7)


get_mempolicy(2)

GET_MEMPOLICY

Section: Linux Programmer's Manual (2)
Updated: 2006-02-07 Return to Main Contents

NAME

get_mempolicy - Retrieve NUMA memory policy for a process

SYNOPSIS

#include <numaif.h>

int get_mempolicy(int *policy, unsigned long *nodemask,
                  unsigned long maxnode, unsigned long addr,
                  unsigned long flags);

DESCRIPTION

get_mempolicy() retrieves the NUMA policy of the calling process or of a memory address, depending on the setting of flags.

A NUMA machine has different memory controllers with different distances to specific CPUs. The memory policy defines in which node memory is allocated for the process.

If flags is specified as 0, then information about the calling process's default policy (as set by set_mempolicy(2)) is returned.

If flags specifies MPOL_F_ADDR, then information is returned about the policy governing the memory address given in addr. This policy may be different from the process's default policy if set_mempolicy(2) has been used to establish a policy for the page containing addr.

If policy is not NULL, then it is used to return the policy. If nodemask is not NULL, then it is used to return the nodemask associated with the policy. maxnode is the maximum bit number plus one that can be stored into nodemask. The bit number is always rounded to a multiple of unsigned long.

For an overview of the possible policies see set_mempolicy(2).

RETURN VALUE

On success, get_mempolicy() returns 0; on error, -1 is returned and errno is set to indicate the error.

CONFORMING TO

This system call is Linux specific.

NOTES

This manual page is incomplete: it does not document the details the MPOL_F_NODE flag, which modifies the operation of get_mempolicy(). This is deliberate: this flag is not intended for application use, and its operation may change or it may be removed altogether in future kernel versions. Do not use it.

Versions and Library Support

See mbind(2).

SEE ALSO

mbind(2), set_mempolicy(2), numactl(8), numa(3)


fchmodat(2)

FCHMODAT

Section: Linux Programmer's Manual (2)
Updated: 2006-05-05 Return to Main Contents

NAME

fchmodat - change permissions of a file relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <sys/stat.h>

int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);

DESCRIPTION

The fchmodat() system call operates in exactly the same way as chmod(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by chmod(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like chmod(2)).

If pathname is absolute, then dirfd is ignored.

flags can either be 0, or include the following flag:

AT_SYMLINK_NOFOLLOW
If pathname is a symbolic link, do not dereference it: instead operate on the link itself. This flag is not currently implemented.

RETURN VALUE

On success, fchmodat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for chmod(2) can also occur for fchmodat(). The following additional errors can occur for fchmodat():
EBADF
dirfd is not a valid file descriptor.
EINVAL
Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.
ENOTSUP
flags specified AT_SYMLINK_NOFOLLOW, which is not supported.

VERSIONS

fchmodat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for fchmodat().

SEE ALSO

chmod(2), openat(2), path_resolution(7)


renameat(2)

RENAMEAT

Section: Linux Programmer's Manual (2)
Updated: 2006-04-10 Return to Main Contents

NAME

renameat - rename a file relative to directory file descriptors

SYNOPSIS

#define _ATFILE_SOURCE
#include <stdio.h>

int renameat(int olddirfd, const char *oldpath,
             int newdirfd, const char *newpath);

DESCRIPTION

The renameat() system call operates in exactly the same way as rename(2), except for the differences described in this manual page.

If the pathname given in oldpath is relative, then it is interpreted relative to the directory referred to by the file descriptor olddirfd (rather than relative to the current working directory of the calling process, as is done by rename(2) for a relative pathname).

If oldpath is relative and olddirfd is the special value AT_FDCWD, then oldpath is interpreted relative to the current working directory of the calling process (like rename(2)).

If oldpath is absolute, then olddirfd is ignored.

The interpretation of newpath is as for oldpath, except that a relative pathname is interpreted relative to the directory referred to by the file descriptor newdirfd.

RETURN VALUE

On success, renameat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for rename(2) can also occur for renameat(). The following additional errors can occur for renameat():
EBADF
olddirfd or newdirfd is not a valid file descriptor.
ENOTDIR
oldpath is relative and olddirfd is a file descriptor referring to a file other than a directory; or similar for newpath and newdirfd

VERSIONS

renameat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for renameat().

SEE ALSO

openat(2), rename(2), path_resolution(7)


epoll_pwait (2)

 Continue to this page.


faccessat(2)

FACCESSAT

Section: Linux Programmer's Manual (2)
Updated: 2007-02-28 Return to Main Contents

NAME

faccessat - check user's permissions of a file relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <fcntl.h>
#include <unistd.h>

int faccessat(int dirfd, const char *pathname, int mode, int flags);

DESCRIPTION

The faccessat() system call operates in exactly the same way as access(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by access(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like access(2)).

If pathname is absolute, then dirfd is ignored.

flags is constructed by ORing together zero or more of the following values:

AT_EACCESS
Perform access checks using the effective user and group IDs. By default, faccessat() uses the real IDs (like access(2)).
AT_SYMLINK_NOFOLLOW
If pathname is a symbolic link, do not dereference it: instead return information about the link itself.

RETURN VALUE

On success, (all requested permissions granted) faccessat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for access(2) can also occur for faccessat(). The following additional errors can occur for faccessat():
EBADF
dirfd is not a valid file descriptor.
EINVAL
Invalid flag specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

faccessat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for faccessat().

Glibc Notes

The AT_EACCESS and AT_SYMLINK_NOFOLLOW flags are actually implemented within the glibc wrapper function for faccessat(). If either of these flags are specified, then the wrapper function employs fstatat(2) to determine access permissions.

SEE ALSO

access(2), openat(2), euidaccess(3), credentials(7), path_resolution(7)


ppoll (2)

 Continue to this page.


linkat(2)

LINKAT

Section: Linux Programmer's Manual (2)
Updated: 2006-04-10 Return to Main Contents

NAME

linkat - create a file link relative to directory file descriptors

SYNOPSIS

#define _ATFILE_SOURCE
#include <unistd.h>

int linkat(int olddirfd, const char *oldpath,
           int newdirfd, const char *newpath, int flags);

DESCRIPTION

The linkat() system call operates in exactly the same way as link(2), except for the differences described in this manual page.

If the pathname given in oldpath is relative, then it is interpreted relative to the directory referred to by the file descriptor olddirfd (rather than relative to the current working directory of the calling process, as is done by link(2) for a relative pathname).

If oldpath is relative and olddirfd is the special value AT_FDCWD, then oldpath is interpreted relative to the current working directory of the calling process (like link(2)).

If oldpath is absolute, then olddirfd is ignored.

The interpretation of newpath is as for oldpath, except that a relative pathname is interpreted relative to the directory referred to by the file descriptor newdirfd.

By default, linkat(2), does not dereference oldpath if it is a symbolic link (like link(2)). Since Linux 2.6.18, the flag AT_SYMLINK_FOLLOW can be specified in flags to cause oldpath to be dereferenced if it is a symbolic link. Before kernel 2.6.18, the flags argument was unused, and had to be specified as 0.

RETURN VALUE

On success, linkat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for link(2) can also occur for linkat(). The following additional errors can occur for linkat():
EBADF
olddirfd or newdirfd is not a valid file descriptor.
ENOTDIR
oldpath is relative and olddirfd is a file descriptor referring to a file other than a directory; or similar for newpath and newdirfd

VERSIONS

linkat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for linkat().

SEE ALSO

link(2), openat(2), path_resolution(7)


symlinkat(2)

SYMLINKAT

Section: Linux Programmer's Manual (2)
Updated: 2006-04-10 Return to Main Contents

NAME

symlinkat - create a symbolic link relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <stdio.h>

int symlinkat(const char *oldpath, int newdirfd, const char *newpath);

DESCRIPTION

The symlinkat() system call operates in exactly the same way as symlink(2), except for the differences described in this manual page.

If the pathname given in newpath is relative, then it is interpreted relative to the directory referred to by the file descriptor newdirfd (rather than relative to the current working directory of the calling process, as is done by symlink(2) for a relative pathname).

If newpath is relative and newdirfd is the special value AT_FDCWD, then newpath is interpreted relative to the current working directory of the calling process (like symlink(2)).

If newpath is absolute, then newdirfd is ignored.

RETURN VALUE

On success, symlinkat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for symlink(2) can also occur for symlinkat(). The following additional errors can occur for symlinkat():
EBADF
newdirfd is not a valid file descriptor.
ENOTDIR
newpath is relative and newdirfd is a file descriptor referring to a file other than a directory.

VERSIONS

symlinkat() was added to Linux in kernel 2.6.16.

CONFORMING TO

This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for symlinkat().

SEE ALSO

openat(2), symlink(2), path_resolution(7)


bcmp(3)

BCMP

Section: Linux Programmer's Manual (3)
Updated: 2002-12-31 Return to Main Contents

NAME

bcmp - compare byte sequences

SYNOPSIS

#include <strings.h>

int bcmp(const void *s1, const void *s2, size_t n);

DESCRIPTION

The bcmp() function compares the two byte sequences s1 and s2 of length n each. If they are equal, and in particular if n is zero, bcmp() returns 0. Otherwise it returns a non-zero result.

RETURN VALUE

The bcmp() function returns 0 if the byte sequences are equal, otherwise a non-zero result is returned.

CONFORMING TO

4.3BSD. This function is deprecated (marked as LEGACY in POSIX.1-2001): use memcmp(3) in new programs.

SEE ALSO

memcmp(3), strcasecmp(3), strcmp(3), strcoll(3), strncasecmp(3), strncmp(3)


bcopy(3)

BCOPY

Section: Linux Programmer's Manual (3)
Updated: 2002-12-31 Return to Main Contents

NAME

bcopy - copy byte sequence

SYNOPSIS

#include <strings.h>

void bcopy(const void *src, void *dest, size_t n);

DESCRIPTION

The bcopy() function copies n bytes from src to dest. The result is correct, even when both areas overlap.

RETURN VALUE

None.

CONFORMING TO

4.3BSD. This function is deprecated (marked as LEGACY in POSIX.1-2001): use memcpy(3) or memmove(3) in new programs. Note that the first two parameters are interchanged for memcpy(3) and memmove(3).

SEE ALSO

memccpy(3), memcpy(3), memmove(3), strcpy(3), strncpy(3)


bsearch(3)

BSEARCH

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

bsearch - binary search of a sorted array

SYNOPSIS

#include <stdlib.h>

void *bsearch(const void *key, const void *base, size_t nmemb,

size_t size, int (*compar)(const void *, const void *));

DESCRIPTION

The bsearch() function searches an array of nmemb objects, the initial member of which is pointed to by base, for a member that matches the object pointed to by key. The size of each member of the array is specified by size.

The contents of the array should be in ascending sorted order according to the comparison function referenced by compar. The compar routine is expected to have two arguments which point to the key object and to an array member, in that order, and should return an integer less than, equal to, or greater than zero if the key object is found, respectively, to be less than, to match, or be greater than the array member.

RETURN VALUE

The bsearch() function returns a pointer to a matching member of the array, or NULL if no match is found. If there are multiple elements that match the key, the element returned is unspecified.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001, C89, C99

EXAMPLE

The example below first sorts an array of structures using qsort(3), then retrieves desired elements using bsearch().

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct mi {
    int nr;
    char *name;
} months[] = {
    { 1, "jan" }, { 2, "feb" }, { 3, "mar" }, { 4, "apr" },
    { 5, "may" }, { 6, "jun" }, { 7, "jul" }, { 8, "aug" },
    { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
};

#define nr_of_months (sizeof(months)/sizeof(months[0]))

static int
compmi(const void *m1, const void *m2)
{
    struct mi *mi1 = (struct mi *) m1;
    struct mi *mi2 = (struct mi *) m2;
    return strcmp(mi1->name, mi2->name);
}

int
main(int argc, char **argv)
{
    int i;

    qsort(months, nr_of_months, sizeof(struct mi), compmi);
    for (i = 1; i < argc; i++) {
        struct mi key, *res;
        key.name = argv[i];
        res = bsearch(&key, months, nr_of_months,
                      sizeof(struct mi), compmi);
        if (res == NULL)
            printf("'%s': unknown month\n", argv[i]);
        else
            printf("%s: month #%d\n", res->name, res->nr);
    }
    exit(EXIT_SUCCESS);
}

SEE ALSO

hsearch(3), lsearch(3), qsort(3), tsearch(3)


bstring(3)

BSTRING

Section: Linux Programmer's Manual (3)
Updated: 2002-01-20 Return to Main Contents

NAME

bcmp, bcopy, bzero, memccpy, memchr, memcmp, memcpy, memfrob, memmem, memmove, memset - byte string operations

SYNOPSIS

#include <string.h>

int bcmp(const void *s1, const void *s2, int n);

void bcopy(const void *src, void *dest, int n);

void bzero(void *s, int n);

void *memccpy(void *dest, const void *src, int c, size_t n);

void *memchr(const void *s, int c, size_t n);

int memcmp(const void *s1, const void *s2, size_t n);

void *memcpy(void *dest, const void *src, size_t n);

void *memfrob(void *s, size_t n);

void *memmem(const void *needle, size_t needlelen,

const void *haystack, size_t haystacklen);

void *memmove(void *dest, const void *src, size_t n);

void *memset(void *s, int c, size_t n);

DESCRIPTION

The byte string functions perform operations on strings (byte arrays) that are not necessarily null-terminated. See the individual man pages for descriptions of each function.

NOTES

The functions bcmp(), bcopy() and bzero() are obsolete. Use memcmp(), memcpy() and memset() instead.

SEE ALSO

bcmp(3), bcopy(3), bzero(3), memccpy(3), memchr(3), memcmp(3), memcpy(3), memfrob(3), memmem(3), memmove(3), memset(3)


calloc (3)

 Continue to this page.


cosh(3)

COSH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

cosh, coshf, coshl - hyperbolic cosine function

SYNOPSIS

#include <math.h>

double cosh(double x);

float coshf(float x);

long double coshl(long double x);

Link with -lm.

DESCRIPTION

The cosh() function returns the hyperbolic cosine of x, which is defined mathematically as (exp(x) + exp(-x)) / 2.

CONFORMING TO

SVr4, POSIX, 4.3BSD, C99. The float and the long double variants are C99 requirements.

SEE ALSO

acosh(3), asinh(3), atanh(3), ccos(3), sinh(3), tanh(3)


db (3)

 Continue to this page.


expm1(3)

EXPM1

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

expm1, expm1f, expm1l - exponential minus 1

SYNOPSIS

#include <math.h>

double expm1(double x);

float expm1f(float x);

long double expm1l(long double x);
Link with -lm.

DESCRIPTION

expm1(x) returns a value equivalent to `exp (x) - 1'. It is computed in a way that is accurate even if the value of x is near zero---a case where `exp (x) - 1' would be inaccurate due to subtraction of two numbers that are nearly equal.

CONFORMING TO

BSD, C99. The float and long double variants are C99 requirements.

SEE ALSO

exp(3), log(3), log1p(3)


isascii (3)

 Continue to this page.


log10(3)

LOG10

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

log10, log10f, log10l - base-10 logarithmic function

SYNOPSIS

#include <math.h>

double log10(double x);

float log10f(float x);

long double log10l(long double x);

Link with -lm.

DESCRIPTION

The log10() function returns the base 10 logarithm of x.

ERRORS

The log10() function can return the following errors:
EDOM
The argument x is negative.
ERANGE
The argument x is zero. The log of zero is not defined.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

cbrt(3), clog10(3), sqrt(3)


pclose (3)

 Continue to this page.


realloc (3)

 Continue to this page.


realpath(3)

REALPATH

Section: Linux Programmer's Manual (3)
Updated: 2004-12-14 Return to Main Contents

NAME

realpath - return the canonicalized absolute pathname

SYNOPSIS

#include <limits.h>
#include <stdlib.h>

char *realpath(const char *path, char *resolved_path);

DESCRIPTION

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the null terminated string named by path and stores the canonicalized absolute pathname in the buffer of size PATH_MAX named by resolved_path. The resulting path will have no symbolic link, '/./' or '/../' components.

RETURN VALUE

If there is no error, realpath() returns a pointer to the resolved_path.

Otherwise it returns a NULL pointer, and the contents of the array resolved_path are undefined. The global variable errno is set to indicate the error.

ERRORS

EACCES
Read or search permission was denied for a component of the path prefix.
EINVAL
Either path or resolved_path is NULL. (In libc5 this would just cause a segfault.) But, see NOTES below.
EIO
An I/O error occurred while reading from the file system.
ELOOP
Too many symbolic links were encountered in translating the pathname.
ENAMETOOLONG
A component of a pathname exceeded NAME_MAX characters, or an entire pathname exceeded PATH_MAX characters.
ENOENT
The named file does not exist.
ENOTDIR
A component of the path prefix is not a directory.

VERSIONS

On Linux this function appeared in libc 4.5.21.

CONFORMING TO

4.4BSD, POSIX.1-2001.

In 4.4BSD and Solaris the limit on the pathname length is MAXPATHLEN (found in <sys/param.h>). SUSv2 prescribes PATH_MAX and NAME_MAX, as found in <limits.h> or provided by the pathconf(3) function. A typical source fragment would be

#ifdef PATH_MAX
  path_max = PATH_MAX;
#else
  path_max = pathconf(path, _PC_PATH_MAX);
  if (path_max <= 0)
    path_max = 4096;
#endif
(But see the BUGS section.)

The 4.4BSD, Linux and SUSv2 versions always return an absolute pathname. Solaris may return a relative pathname when the path argument is relative. The prototype of realpath() is given in <unistd.h> in libc4 and libc5, but in <stdlib.h> everywhere else.

NOTES

The glibc implementation of realpath() provides a non-standard extension. If resolved_path is specified as NULL, then realpath() uses malloc(3) to allocate a buffer of up to PATH_MAX bytes to hold the resolved pathname, and returns a pointer to this buffer. The caller should deallocate this buffer using free(3).

BUGS

Avoid using this function. It is broken by design since (unless using the non-standard resolved_path == NULL feature) it is impossible to determine a suitable size for the output buffer, resolved_path. According to POSIX a buffer of size PATH_MAX suffices, but PATH_MAX need not be a defined constant, and may have to be obtained using pathconf(3). And asking pathconf(3) does not really help, since on the one hand POSIX warns that the result of pathconf(3) may be huge and unsuitable for mallocing memory. And on the other hand pathconf(3) may return -1 to signify that PATH_MAX is not bounded.

The libc4 and libc5 implementation contains a buffer overflow (fixed in libc-5.4.13). Thus, set-user-ID programs like mount need a private version.

SEE ALSO

readlink(2), canonicalize_file_name(3), getcwd(3), pathconf(3), sysconf(3)


sigemptyset (3)

 Continue to this page.


stdin(3)

STDIN

Section: C Library Functions (3) Return to Main Contents

BSD mandoc
Linux 2.0

NAME

stdin stdout stderr - standard I/O streams

SYNOPSIS

Fd #include <stdio.h> Fd extern FILE *stdin; Fd extern FILE *stdout; Fd extern FILE *stderr;

DESCRIPTION

Under normal circumstances every Unix program has three streams opened for it when it starts up, one for input, one for output, and one for printing diagnostic or error messages. These are typically attached to the user's terminal (see tty(4)) but might instead refer to files or other devices, depending on what the parent process chose to set up. (See also the ``Redirection'' section of sh(1).)

The input stream is referred to as ``standard input''; the output stream is referred to as ``standard output''; and the error stream is referred to as ``standard error''. These terms are abbreviated to form the symbols used to refer to these files, namely stdin stdout and stderr

Each of these symbols is a stdio(3) macro of type pointer to FILE, and can be used with functions like fprintf(3) or fread(3).

Since FILEs are a buffering wrapper around Unix file descriptors, the same underlying files may also be accessed using the raw Unix file interface, that is, the functions like read(2) and lseek(2).

On program startup, the integer file descriptors associated with the streams stdin stdout and stderr are 0, 1, and 2, respectively. The preprocessor symbols STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO are defined with these values in <unistd.h>. (Applying freopen(3) to one of these streams can change the file descriptor number associated with the stream.)

Note that mixing use of FILEs and raw file descriptors can produce unexpected results and should generally be avoided. (For the masochistic among you: POSIX.1, section 8.2.3, describes in detail how this interaction is supposed to work.) A general rule is that file descriptors are handled in the kernel, while stdio is just a library. This means for example, that after an Fn exec , the child inherits all open file descriptors, but all old streams have become inaccessible.

Since the symbols stdin stdout and stderr are specified to be macros, assigning to them is non-portable. The standard streams can be made to refer to different files with help of the library function freopen(3), specially introduced to make it possible to reassign stdin stdout and stderr The standard streams are closed by a call to exit(3) and by normal program termination.

CONSIDERATIONS

The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline is printed. This can produce unexpected results, especially with debugging output. The buffering mode of the standard streams (or any other stream) can be changed using the setbuf(3) or setvbuf(3) call. Note that in case stdin is associated with a terminal, there may also be input buffering in the terminal driver, entirely unrelated to stdio buffering. (Indeed, normally terminal input is line buffered in the kernel.) This kernel input handling can be modified using calls like tcsetattr(3); see also stty(1), and termios(3).

CONFORMING TO

The stdin stdout and stderr macros conform to St -ansiC , and this standard also stipulates that these three streams shall be open at program startup.

SEE ALSO

sh(1), csh(1), open(2), fopen(3), stdio(3)


sysconf(3)

SYSCONF

Section: Linux Programmer's Manual (3)
Updated: 1993-04-18 Return to Main Contents

NAME

sysconf - Get configuration information at runtime

SYNOPSIS

#include <unistd.h>

long sysconf(int name);

DESCRIPTION

POSIX allows an application to test at compile- or run-time whether certain options are supported, or what the value is of certain configurable constants or limits.

At compile time this is done by including <unistd.h> and/or <limits.h> and testing the value of certain macros.

At run time, one can ask for numerical values using the present function sysconf(). On can ask for numerical values that may depend on the filesystem a file is in using the calls fpathconf(3) and pathconf(3). One can ask for string values using confstr(3).

The values obtained from these functions are system configuration constants. They do not change during the lifetime of a process.

For options, typically, there is a constant _POSIX_FOO that may be defined in <unistd.h>. If it is undefined, one should ask at run-time. If it is defined to -1, then the option is not supported. If it is defined to 0, then relevant functions and headers exist, but one has to ask at runtime what degree of support is available. If it is defined to a value other than -1 or 0, then the option is supported. Usually the value (such as 200112L) indicates the year and month of the POSIX revision describing the option. Glibc uses the value 1 to indicate support as long as the POSIX revision has not been published yet. The sysconf() argument will be _SC_FOO. For a list of options, see posixoptions(7).

For variables or limits, typically, there is a constant _FOO, maybe defined in <limits.h>, or _POSIX_FOO, maybe defined in <unistd.h>. The constant will not be defined if the limit is unspecified. If the constant is defined, it gives a guaranteed value, and more might actually be supported. If an application wants to take advantage of values which may change between systems, a call to sysconf() can be made. The sysconf() argument will be _SC_FOO.

POSIX.1 Variables

We give the name of the variable, the name of the sysconf() parameter used to inquire about its value, and a short description.

First, the POSIX.1 compatible values.

ARG_MAX - _SC_ARG_MAX
The maximum length of the arguments to the exec(3) family of functions. Must not be less than _POSIX_ARG_MAX (4096).
CHILD_MAX - _SC_CHILD_MAX
The max number of simultaneous processes per user ID. Must not be less than _POSIX_CHILD_MAX (25).
HOST_NAME_MAX - _SC_HOST_NAME_MAX
Max length of a hostname, not including the terminating null byte, as returned by gethostname(2). Must not be less than _POSIX_HOST_NAME_MAX (255).
LOGIN_NAME_MAX - _SC_LOGIN_NAME_MAX
Maximum length of a login name, including the terminating null byte. Must not be less than _POSIX_LOGIN_NAME_MAX (9).
clock ticks - _SC_CLK_TCK
The number of clock ticks per second. The corresponding variable is obsolete. It was of course called CLK_TCK. (Note: the macro CLOCKS_PER_SEC does not give information: it must equal 1000000.)
OPEN_MAX - _SC_OPEN_MAX
The maximum number of files that a process can have open at any time. Must not be less than _POSIX_OPEN_MAX (20).
PAGESIZE - _SC_PAGESIZE
Size of a page in bytes. Must not be less than 1. (Some systems use PAGE_SIZE instead.)
RE_DUP_MAX - _SC_RE_DUP_MAX
The number of repeated occurrences of a BRE permitted by regexec(3) and regcomp(3). Must not be less than _POSIX2_RE_DUP_MAX (255).
STREAM_MAX - _SC_STREAM_MAX
The maximum number of streams that a process can have open at any time. If defined, it has the same value as the standard C macro FOPEN_MAX. Must not be less than _POSIX_STREAM_MAX (8).
SYMLOOP_MAX
The maximum number of symbolic links seen in a pathname before resolution returns ELOOP. Must not be less than _POSIX_SYMLOOP_MAX (8).
TTY_NAME_MAX - _SC_TTY_NAME_MAX
The maximum length of terminal device name, including the terminating null byte. Must not be less than _POSIX_TTY_NAME_MAX (9).
TZNAME_MAX - _SC_TZNAME_MAX
The maximum number of bytes in a timezone name. Must not be less than _POSIX_TZNAME_MAX (6).
_POSIX_VERSION - _SC_VERSION
indicates the year and month the POSIX.1 standard was approved in the format YYYYMML;the value 199009L indicates the Sept. 1990 revision.

POSIX.2 Variables

Next, the POSIX.2 values, giving limits for utilities.
BC_BASE_MAX - _SC_BC_BASE_MAX
indicates the maximum obase value accepted by the bc(1) utility.
BC_DIM_MAX - _SC_BC_DIM_MAX
indicates the maximum value of elements permitted in an array by bc(1).
BC_SCALE_MAX - _SC_BC_SCALE_MAX
indicates the maximum scale value allowed by bc(1).
BC_STRING_MAX - _SC_BC_STRING_MAX
indicates the maximum length of a string accepted by bc(1).
COLL_WEIGHTS_MAX - _SC_COLL_WEIGHTS_MAX
indicates the maximum numbers of weights that can be assigned to an entry of the LC_COLLATE order keyword in the locale definition file,
EXPR_NEST_MAX - _SC_EXPR_NEST_MAX
is the maximum number of expressions which can be nested within parentheses by expr(1).
LINE_MAX - _SC_LINE_MAX
The maximum length of a utility's input line length, either from standard input or from a file. This includes length for a trailing newline.
RE_DUP_MAX - _SC_RE_DUP_MAX
The maximum number of repeated occurrences of a regular expression when the interval notation \{m,n\} is used.
POSIX2_VERSION - _SC_2_VERSION
indicates the version of the POSIX.2 standard in the format of YYYYMML.
POSIX2_C_DEV - _SC_2_C_DEV
indicates whether the POSIX.2 C language development facilities are supported.
POSIX2_FORT_DEV - _SC_2_FORT_DEV
indicates whether the POSIX.2 FORTRAN development utilities are supported.
POSIX2_FORT_RUN - _SC_2_FORT_RUN
indicates whether the POSIX.2 FORTRAN runtime utilities are supported.
_POSIX2_LOCALEDEF - _SC_2_LOCALEDEF
indicates whether the POSIX.2 creation of locates via localedef(1) is supported.
POSIX2_SW_DEV - _SC_2_SW_DEV
indicates whether the POSIX.2 software development utilities option is supported.

These values also exist, but may not be standard.

- _SC_PHYS_PAGES
The number of pages of physical memory. Note that it is possible for the product of this value and the value of _SC_PAGE_SIZE to overflow.
- _SC_AVPHYS_PAGES
The number of currently available pages of physical memory.

RETURN VALUE

If name is invalid, -1 is returned, and errno is set to EINVAL. Otherwise, the value returned is the value of the system resource and errno is not changed. In the case of options, a positive value is returned if a queried option is available, and -1 if it is not. In the case of limits, -1 means that there is no definite limit.

CONFORMING TO

POSIX.1-2001.

BUGS

It is difficult to use ARG_MAX because it is not specified how much of the argument space for exec(3) is consumed by the user's environment variables.

Some returned values may be huge; they are not suitable for allocating memory.

SEE ALSO

bc(1), expr(1), getconf(1), locale(1), fpathconf(3), pathconf(3), posixoptions(7)


syslog(3)

SYSLOG

Section: Linux Programmer's Manual (3)
Updated: 2002-01-03 Return to Main Contents

NAME

closelog, openlog, syslog - send messages to the system logger

SYNOPSIS

#include <syslog.h>

void openlog(const char *ident, int option, int facility);
void syslog(int priority, const char *format, ...);
void closelog(void);

#define _BSD_SOURCE
#include <stdarg.h>

void vsyslog(int priority, const char *format, va_list ap);

DESCRIPTION

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

openlog() opens a connection to the system logger for a program. The string pointed to by ident is prepended to every message, and is typically set to the program name. The option argument specifies flags which control the operation of openlog() and subsequent calls to syslog(). The facility argument establishes a default to be used if none is specified in subsequent calls to syslog(). Values for option and facility are given below. The use of openlog() is optional; it will automatically be called by syslog() if necessary, in which case ident will default to NULL.

syslog() generates a log message, which will be distributed by syslogd(8). The priority argument is formed by ORing the facility and the level values (explained below). The remaining arguments are a format, as in printf(3) and any arguments required by the format, except that the two character sequence %m will be replaced by the error message string strerror(errno). A trailing newline may be added if needed.

The function vsyslog() performs the same task as syslog() with the difference that it takes a set of arguments which have been obtained using the stdarg(3) variable argument list macros.

The subsections below lists the parameters used to set the values of option, facility, and priority.

option

The option argument to openlog() is an OR of any of these:
LOG_CONS
Write directly to system console if there is an error while sending to system logger.
LOG_NDELAY
Open the connection immediately (normally, the connection is opened when the first message is logged).
LOG_NOWAIT
Don't wait for child processes that may have been created while logging the message. (The GNU C library does not create a child process, so this option has no effect on Linux.)
LOG_ODELAY
The converse of LOG_NDELAY; opening of the connection is delayed until syslog() is called. (This is the default, and need not be specified.)
LOG_PERROR
(Not in POSIX.1-2001.) Print to stderr as well.
LOG_PID
Include PID with each message.

facility

The facility argument is used to specify what type of program is logging the message. This lets the configuration file specify that messages from different facilities will be handled differently.
LOG_AUTH
security/authorization messages (DEPRECATED Use LOG_AUTHPRIV instead)
LOG_AUTHPRIV
security/authorization messages (private)
LOG_CRON
clock daemon (cron and at)
LOG_DAEMON
system daemons without separate facility value
LOG_FTP
ftp daemon
LOG_KERN
kernel messages
LOG_LOCAL0 through LOG_LOCAL7
reserved for local use
LOG_LPR
line printer subsystem
LOG_MAIL
mail subsystem
LOG_NEWS
USENET news subsystem
LOG_SYSLOG
messages generated internally by syslogd
LOG_USER (default)
generic user-level messages
LOG_UUCP
UUCP subsystem

level

This determines the importance of the message. The levels are, in order of decreasing importance:
LOG_EMERG
system is unusable
LOG_ALERT
action must be taken immediately
LOG_CRIT
critical conditions
LOG_ERR
error conditions
LOG_WARNING
warning conditions
LOG_NOTICE
normal, but significant, condition
LOG_INFO
informational message
LOG_DEBUG
debug-level message

The function setlogmask(3) can be used to restrict logging to specified levels only.

CONFORMING TO

The functions openlog(), closelog(), and syslog() (but not vsyslog()) are specified in SUSv2 and POSIX.1-2001. POSIX.1-2001 specifies only the LOG_USER and LOG_LOCAL* values for facility. However, with the exception of LOG_AUTHPRIV and LOG_FTP, the other facility values appear on most Unix systems. The LOG_PERROR value for option is not specified by POSIX.1-2001, but is available in most versions of Unix.

NOTES

The parameter ident in the call of openlog() is probably stored as-is. Thus, if the string it points to is changed, syslog() may start prepending the changed string, and if the string it points to ceases to exist, the results are undefined. Most portable is to use a string constant.

Never pass a string with user-supplied data as a format, use

syslog(priority, "%s", string);
instead.

SEE ALSO

logger(1), setlogmask(3), syslog.conf(5), feature_test_macros(7), syslogd(8)


system(3)

SYSTEM

Section: Linux Programmer's Manual (3)
Updated: 2004-12-20 Return to Main Contents

NAME

system - execute a shell command

SYNOPSIS

#include <stdlib.h>

int system(const char *command);

DESCRIPTION

system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.

RETURN VALUE

The value returned is -1 on error (e.g. fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127).

If the value of command is NULL, system() returns non-zero if the shell is available, and zero if not.

system() does not affect the wait status of any other children.

CONFORMING TO

C89, C99, POSIX.1-2001.

NOTES

If the _XOPEN_SOURCE feature test macro is defined, then the macros described in wait(2) (WEXITSTATUS(), etc.) are made available when including <stdlib.h>.

As mentioned, system() ignores SIGINT and SIGQUIT. This may make programs that call it from a loop uninterruptible, unless they take care themselves to check the exit status of the child. E.g.

    while(something) {
        int ret = system("foo");

        if (WIFSIGNALED(ret) &&
            (WTERMSIG(ret) == SIGINT || WTERMSIG(ret) == SIGQUIT))
                break;
    }

Do not use system() from a program with set-user-ID or set-group-ID privileges, because strange values for some environment variables might be used to subvert system integrity. Use the exec(3) family of functions instead, but not execlp(3) or execvp(3). system() will not, in fact, work properly from programs with set-user-ID or set-group-ID privileges on systems on which /bin/sh is bash version 2, since bash 2 drops privileges on startup. (Debian uses a modified bash which does not do this when invoked as sh.)

In versions of glibc before 2.1.3, the check for the availability of /bin/sh was not actually performed if command was NULL; instead it was always assumed to be available, and system() always returned 1 in this case. Since glibc 2.1.3, this check is performed because, even though POSIX.1-2001 requires a conforming implementation to provide a shell, that shell may not be available or executable if the calling program has previously called chroot(2) (which is not specified by POSIX.1-2001).

It is possible for the shell command to return 127, so that code is not a sure indication that the execve(2) call failed.

SEE ALSO

sh(1), signal(2), wait(2), exec(3)


tanh(3)

TANH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

tanh, tanhf, tanhl - hyperbolic tangent function

SYNOPSIS

#include <math.h>

double tanh(double x);

float tanhf(float x);

long double tanhl(long double x);

Link with -lm.

DESCRIPTION

The tanh() function returns the hyperbolic tangent of x, which is defined mathematically as sinh(x) / cosh(x).

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acosh(3), asinh(3), atanh(3), cosh(3), ctanh(3), sinh(3)


killpg(3)

KILLPG

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

killpg - send signal to all members of a process group

SYNOPSIS

#include <signal.h>

int killpg(pid_t pgrp, int signal);

DESCRIPTION

The killpg() function causes signal signal to be sent to all the processes in the process group pgrp or to the processes' own process group if pgrp is equal to zero.

If pgrp is greater than 1, it is equivalent to:

kill(-pgrp , signal);

RETURN VALUE

The value returned is -1 on error, or 0 for success.

ERRORS

Errors are returned in errno and can be one of the following:
EINVAL
for an invalid signal,
EPERM
if the userid of the calling process is not equal to that of the process the signal is sent to, and the userid is not that of the superuser.
ESRCH
for a process group which does not exist, and

CONFORMING TO

SUSv2, POSIX.1-2001

SEE ALSO

kill(2), signal(2), sigqueue(2), signal(7)


crypt(3)

CRYPT

Section: Linux Programmer's Manual (3)
Updated: 2001-12-23 Return to Main Contents

NAME

crypt - password and data encryption

SYNOPSIS

#define _XOPEN_SOURCE
#include <unistd.h>

char *crypt(const char *key, const char *salt);

Link with -lcrypt.

DESCRIPTION

crypt() is the password encryption function. It is based on the Data Encryption Standard algorithm with variations intended (among other things) to discourage use of hardware implementations of a key search.

key is a user's typed password.

salt is a two-character string chosen from the set [a-zA-Z0-9./]. This string is used to perturb the algorithm in one of 4096 different ways.

By taking the lowest 7 bits of each of the first eight characters of the key, a 56-bit key is obtained. This 56-bit key is used to encrypt repeatedly a constant string (usually a string consisting of all zeros). The returned value points to the encrypted password, a series of 13 printable ASCII characters (the first two characters represent the salt itself). The return value points to static data whose content is overwritten by each call.

Warning: The key space consists of 2**56 equal 7.2e16 possible values. Exhaustive searches of this key space are possible using massively parallel computers. Software, such as crack(1), is available which will search the portion of this key space that is generally used by humans for passwords. Hence, password selection should, at minimum, avoid common words and names. The use of a passwd(1) program that checks for crackable passwords during the selection process is recommended.

The DES algorithm itself has a few quirks which make the use of the crypt(3) interface a very poor choice for anything other than password authentication. If you are planning on using the crypt(3) interface for a cryptography project, don't do it: get a good book on encryption and one of the widely available DES libraries.

RETURN VALUE

A pointer to the encrypted password is returned. On error, NULL is returned.

ERRORS

ENOSYS
The crypt() function was not implemented, probably because of U.S.A. export restrictions.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001

NOTES

Glibc Notes

The glibc2 version of this function has the following additional features. If salt is a character string starting with the three characters "$1$" followed by at most eight characters, and optionally terminated by "$", then instead of using the DES machine, the glibc crypt function uses an MD5-based algorithm, and outputs up to 34 bytes, namely "$1$<salt>$<encoded>", where "<salt>" stands for the up to 8 characters following "$1$" in the salt, and "<encoded>" is a further 22 characters. The characters in "<salt>" and "<encoded>" are drawn from the set [a-zA-Z0-9./]. The entire key is significant here (instead of only the first 8 bytes).

SEE ALSO

login(1), passwd(1), encrypt(3), getpass(3), passwd(5), feature_test_macros(7)


fflush(3)

FFLUSH

Section: Linux Programmer's Manual (3)
Updated: 1993-11-29 Return to Main Contents

NAME

fflush - flush a stream

SYNOPSIS

#include <stdio.h>

int fflush(FILE *stream);

DESCRIPTION

The function fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. The open status of the stream is unaffected.

If the stream argument is NULL, fflush() flushes all open output streams.

For a non-locking counterpart, see unlocked_stdio(3).

RETURN VALUE

Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error.

ERRORS

EBADF
Stream is not an open stream, or is not open for writing.

The function fflush() may also fail and set errno for any of the errors specified for the routine write(2).

CONFORMING TO

C89, C99.

NOTES

Note that fflush() only flushes the user space buffers provided by the C library. To ensure that the data is physically stored on disk the kernel buffers must be flushed too, for example, with sync(2) or fsync(2).

SEE ALSO

fsync(2), sync(2), write(2), fclose(3), fopen(3), setbuf(3), unlocked_stdio(3)


ffs(3)

FFS

Section: Linux Programmer's Manual (3)
Updated: 2003-08-05 Return to Main Contents

NAME

ffs - find first bit set in a word

SYNOPSIS

#include <strings.h>

int ffs(int i);

#define _GNU_SOURCE

#include <string.h>

int ffsl(long int i);

int ffsll(long long int i);

DESCRIPTION

The ffs() function returns the position of the first (least significant) bit set in the word i. The least significant bit is position 1 and the most significant position is, for example, 32 or 64. Thefunctions ffsll() and ffsl() do the same but take arguments of possibly different size.

RETURN VALUE

These functions return the position of the first bit set, or 0 if no bits are set in i.

CONFORMING TO

4.3BSD, POSIX.1-2001.

NOTES

BSD systems have a prototype in <string.h>.

SEE ALSO

feature_test_macros(7)


dbopen(3)

DBOPEN

Section: Linux Programmer's Manual (3)
Updated: 1994-01-02 Return to Main Contents

NAME

dbopen - database access methods

SYNOPSIS

#include <sys/types.h>
#include <limits.h>
#include <db.h>

DB *dbopen(const char *file, int flags, int mode, DBTYPE type,
           const void *openinfo);

DESCRIPTION

dbopen() is the library interface to database files. The supported file formats are btree, hashed and UNIX file oriented. The btree format is a representation of a sorted, balanced tree structure. The hashed format is an extensible, dynamic hashing scheme. The flat-file format is a byte stream file with fixed or variable length records. The formats and file format specific information are described in detail in their respective manual pages btree(3), hash(3) and recno(3).

dbopen() opens file for reading and/or writing. Files never intended to be preserved on disk may be created by setting the file parameter to NULL.

The flags and mode arguments are as specified to the open(2) routine, however, only the O_CREAT, O_EXCL, O_EXLOCK, O_NONBLOCK, O_RDONLY, O_RDWR, O_SHLOCK and O_TRUNC flags are meaningful. (Note, opening a database file O_WRONLY is not possible.)

The type argument is of type DBTYPE (as defined in the <db.h> include file) and may be set to DB_BTREE, DB_HASH or DB_RECNO.

The openinfo argument is a pointer to an access method specific structure described in the access method's manual page. If openinfo is NULL, each access method will use defaults appropriate for the system and the access method.

dbopen() returns a pointer to a DB structure on success and NULL on error. The DB structure is defined in the <db.h> include file, and contains at least the following fields:

typedef struct {
    DBTYPE type;
    int (*close)(const DB *db);
    int (*del)(const DB *db, const DBT *key, u_int flags);
    int (*fd)(const DB *db);
    int (*get)(const DB *db, DBT *key, DBT *data, u_int flags);
    int (*put)(const DB *db, DBT *key, const DBT *data,
               u_int flags);
    int (*sync)(const DB *db, u_int flags);
    int (*seq)(const DB *db, DBT *key, DBT *data, u_int flags);
} DB;

These elements describe a database type and a set of functions performing various actions. These functions take a pointer to a structure as returned by dbopen(), and sometimes one or more pointers to key/data structures and a flag value.

type
The type of the underlying access method (and file format).
close
A pointer to a routine to flush any cached information to disk, free any allocated resources, and close the underlying file(s). Since key/data pairs may be cached in memory, failing to sync the file with a close or sync function may result in inconsistent or lost information. Close routines return -1 on error (setting errno) and 0 on success.
del
A pointer to a routine to remove key/data pairs from the database.
The parameter flag may be set to the following value:
R_CURSOR
Delete the record referenced by the cursor. The cursor must have previously been initialized.
Delete routines return -1 on error (setting errno), 0 on success, and 1 if the specified key was not in the file.
fd
A pointer to a routine which returns a file descriptor representative of the underlying database. A file descriptor referencing the same file will be returned to all processes which call dbopen() with the same file name. This file descriptor may be safely used as an argument to the fcntl(2) and flock(2) locking functions. The file descriptor is not necessarily associated with any of the underlying files used by the access method. No file descriptor is available for in memory databases. Fd routines return -1 on error (setting errno), and the file descriptor on success.
get
A pointer to a routine which is the interface for keyed retrieval from the database. The address and length of the data associated with the specified key are returned in the structure referenced by data. Get routines return -1 on error (setting errno), 0 on success, and 1 if the key was not in the file.
put
A pointer to a routine to store key/data pairs in the database.
The parameter flag may be set to one of the following values:
R_CURSOR
Replace the key/data pair referenced by the cursor. The cursor must have previously been initialized.
R_IAFTER
Append the data immediately after the data referenced by key, creating a new key/data pair. The record number of the appended key/data pair is returned in the key structure. (Applicable only to the DB_RECNO access method.)
R_IBEFORE
Insert the data immediately before the data referenced by key, creating a new key/data pair. The record number of the inserted key/data pair is returned in the key structure. (Applicable only to the DB_RECNO access method.)
R_NOOVERWRITE
Enter the new key/data pair only if the key does not previously exist.
R_SETCURSOR
Store the key/data pair, setting or initializing the position of the cursor to reference it. (Applicable only to the DB_BTREE and DB_RECNO access methods.)
R_SETCURSOR is available only for the DB_BTREE and DB_RECNO access methods because it implies that the keys have an inherent order which does not change.
R_IAFTER and R_IBEFORE are available only for the DB_RECNO access method because they each imply that the access method is able to create new keys. This is only true if the keys are ordered and independent, record numbers for example.
The default behavior of the put routines is to enter the new key/data pair, replacing any previously existing key.
Put routines return -1 on error (setting errno), 0 on success, and 1 if the R_NOOVERWRITE flag was set and the key already exists in the file.
seq
A pointer to a routine which is the interface for sequential retrieval from the database. The address and length of the key are returned in the structure referenced by key, and the address and length of the data are returned in the structure referenced by data.
Sequential key/data pair retrieval may begin at any time, and the position of the ``cursor'' is not affected by calls to the del, get, put, or sync routines. Modifications to the database during a sequential scan will be reflected in the scan, that is, records inserted behind the cursor will not be returned while records inserted in front of the cursor will be returned.
The flag value must be set to one of the following values:
R_CURSOR
The data associated with the specified key is returned. This differs from the get routines in that it sets or initializes the cursor to the location of the key as well. (Note, for the DB_BTREE access method, the returned key is not necessarily an exact match for the specified key. The returned key is the smallest key greater than or equal to the specified key, permitting partial key matches and range searches.)
R_FIRST
The first key/data pair of the database is returned, and the cursor is set or initialized to reference it.
R_LAST
The last key/data pair of the database is returned, and the cursor is set or initialized to reference it. (Applicable only to the DB_BTREE and DB_RECNO access methods.)
R_NEXT
Retrieve the key/data pair immediately after the cursor. If the cursor is not yet set, this is the same as the R_FIRST flag.
R_PREV
Retrieve the key/data pair immediately before the cursor. If the cursor is not yet set, this is the same as the R_LAST flag. (Applicable only to the DB_BTREE and DB_RECNO access methods.)
R_LAST and R_PREV are available only for the DB_BTREE and DB_RECNO access methods because they each imply that the keys have an inherent order which does not change.
Seq routines return -1 on error (setting errno), 0 on success and 1 if there are no key/data pairs less than or greater than the specified or current key. If the DB_RECNO access method is being used, and if the database file is a character special file and no complete key/data pairs are currently available, the seq routines return 2.
sync
A pointer to a routine to flush any cached information to disk. If the database is in memory only, the sync routine has no effect and will always succeed.
The flag value may be set to the following value:
R_RECNOSYNC
If the DB_RECNO access method is being used, this flag causes the sync routine to apply to the btree file which underlies the recno file, not the recno file itself. (See the bfname field of the recno(3) manual page for more information.)
Sync routines return -1 on error (setting errno) and 0 on success.

Key/Data Pairs

Access to all file types is based on key/data pairs. Both keys and data are represented by the following data structure:

typedef struct {

void *data;
size_t size;
} DBT;

The elements of the DBT structure are defined as follows:

data
A pointer to a byte string.
size
The length of the byte string.

Key and data byte strings may reference strings of essentially unlimited length although any two of them must fit into available memory at the same time. It should be noted that the access methods provide no guarantees about byte string alignment.

ERRORS

The dbopen() routine may fail and set errno for any of the errors specified for the library routines open(2) and malloc(3) or the following:
[EFTYPE]
A file is incorrectly formatted.
[EINVAL]
A parameter has been specified (hash function, pad byte etc.) that is incompatible with the current file specification or which is not meaningful for the function (for example, use of the cursor without prior initialization) or there is a mismatch between the version number of file and the software.

The close routines may fail and set errno for any of the errors specified for the library routines close(2), read(2), write(2), free(3), or fsync(2).

The del, get, put and seq routines may fail and set errno for any of the errors specified for the library routines read(2), write(2), free(3) or malloc(3).

The fd routines will fail and set errno to ENOENT for in memory databases.

The sync routines may fail and set errno for any of the errors specified for the library routine fsync(2).

BUGS

The typedef DBT is a mnemonic for ``data base thang'', and was used because no-one could think of a reasonable name that wasn't already used.

The file descriptor interface is a kludge and will be deleted in a future version of the interface.

None of the access methods provide any form of concurrent access, locking, or transactions.

SEE ALSO

btree(3), hash(3), mpool(3), recno(3)

LIBTP: Portable, Modular Transactions for UNIX, Margo Seltzer, Michael Olson, USENIX proceedings, Winter 1992.


j0(3)

J0

Section: Linux Programmer's Manual (3)
Updated: 2002-08-25 Return to Main Contents

NAME

j0, j0f, j0l, j1, j1f, j1l, jn, jnf, jnl, y0, y0f, y0l, y1, y1f, y1l, yn, ynf, ynl - Bessel functions

SYNOPSIS

#define _GNU_SOURCE
#include <math.h>

double j0(double x);

double j1(double x);

double jn(int n, double x);

double y0(double x);

double y1(double x);

double yn(int n, double x);

float j0f(float x);

float j1f(float x);

float jnf(int n, float x);

float y0f(float x);

float y1f(float x);

float ynf(int n, float x);

long double j0l(long double x);

long double j1l(long double x);

long double jnl(int n, long double x);

long double y0l(long double x);

long double y1l(long double x);

long double ynl(int n, long double x);

Link with -lm.

DESCRIPTION

The j0() and j1() functions return Bessel functions of x of the first kind of orders 0 and 1, respectively. The jn() function returns the Bessel function of x of the first kind of order n.

The y0() and y1() functions return Bessel functions of x of the second kind of orders 0 and 1, respectively. The yn() function returns the Bessel function of x of the second kind of order n.

For the functions y0(), y1() and yn(), the value of x must be positive. For negative values of x, these functions return -HUGE_VAL.

The j0f() etc. and j0l() etc. functions are versions that take and return float and long double values, respectively.

CONFORMING TO

The functions returning double conform to SVr4, 4.3BSD, POSIX.1-2001.

BUGS

There are errors of up to 2e-16 in the values returned by j0(), j1() and jn() for values of x between -8 and 8.

SEE ALSO

feature_test_macros(7)


lcong48 (3)

 Continue to this page.


psignal(3)

PSIGNAL

Section: Linux Programmer's Manual (3)
Updated: 1993-04-13 Return to Main Contents

NAME

psignal - print signal message

SYNOPSIS

#include <signal.h>

void psignal(int sig, const char *s);

extern const char *const sys_siglist[];

DESCRIPTION

The psignal() function displays a message on stderr consisting of the string s, a colon, a space, and a string describing the signal number sig. If sig is invalid, the message displayed will indicate an unknown signal.

The array sys_siglist holds the signal description strings indexed by signal number.

RETURN VALUE

The psignal() function returns no value.

CONFORMING TO

4.3BSD

SEE ALSO

perror(3), strsignal(3)


printf(3)

PRINTF

Section: Linux Programmer's Manual (3)
Updated: 2000-10-16 Return to Main Contents

NAME

printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf - formatted output conversion

SYNOPSIS

#include <stdio.h>

int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);

#include <stdarg.h>

int vprintf(const char *format, va_list ap);
int vfprintf(FILE *stream, const char *format, va_list ap);
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);

DESCRIPTION

The functions in the printf() family produce output according to a format as described below. The functions printf() and vprintf() write output to stdout, the standard output stream; fprintf() and vfprintf() write output to the given output stream; sprintf(), snprintf(), vsprintf() and vsnprintf() write to the character string str.

The functions snprintf() and vsnprintf() write at most size bytes (including the trailing null byte ('\0')) to str.

The functions vprintf(), vfprintf(), vsprintf(), vsnprintf() are equivalent to the functions printf(), fprintf(), sprintf(), snprintf(), respectively, except that they are called with a va_list instead of a variable number of arguments. These functions do not call the va_end macro. Consequently, the value of ap is undefined after the call. The application should call va_end(ap) itself afterwards.

These eight functions write the output under the control of a format string that specifies how subsequent arguments (or arguments accessed via the variable-length argument facilities of stdarg(3)) are converted for output.

Return value

Upon successful return, these functions return the number of characters printed (not including the trailing '\0' used to end output to strings).

The functions snprintf() and vsnprintf() do not write more than size bytes (including the trailing '\0'). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\0') which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. (See also below under NOTES.)

If an output error is encountered, a negative value is returned.

Format of the format string

The format string is a character string, beginning and ending in its initial shift state, if any. The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments. Each conversion specification is introduced by the character %, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width, an optional precision and an optional length modifier.

The arguments must correspond properly (after type promotion) with the conversion specifier. By default, the arguments are used in the order given, where each `*' and each conversion specifier asks for the next argument (and it is an error if insufficiently many arguments are given). One can also specify explicitly which argument is taken, at each place where an argument is required, by writing `%m$' instead of `%' and `*m$' instead of `*', where the decimal integer m denotes the position in the argument list of the desired argument, indexed starting from 1. Thus,

    printf("%*d", width, num);
and

    printf("%2$*1$d", width, num);
are equivalent. The second style allows repeated references to the same argument. The C99 standard does not include the style using `$', which comes from the Single Unix Specification. If the style using `$' is used, it must be used throughout for all conversions taking an argument and all width and precision arguments, but it may be mixed with `%%' formats which do not consume an argument. There may be no gaps in the numbers of arguments specified using `$'; for example, if arguments 1 and 3 are specified, argument 2 must also be specified somewhere in the format string.

For some numeric conversions a radix character (`decimal point') or thousands' grouping character is used. The actual character used depends on the LC_NUMERIC part of the locale. The POSIX locale uses `.' as radix character, and does not have a grouping character. Thus,

    printf("%'.2f", 1234567.89);
results in `1234567.89' in the POSIX locale, in `1234567,89' in the nl_NL locale, and in `1.234.567,89' in the da_DK locale.

The flag characters

The character % is followed by zero or more of the following flags:
#
The value should be converted to an ``alternate form''. For o conversions, the first character of the output string is made zero (by prefixing a 0 if it was not zero already). For x and X conversions, a non-zero result has the string `0x' (or `0X' for X conversions) prepended to it. For a, A, e, E, f, F, g, and G conversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows). For g and G conversions, trailing zeros are not removed from the result as they would otherwise be. For other conversions, the result is undefined.
0
The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - flags both appear, the 0 flag is ignored. If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. For other conversions, the behavior is undefined.
-
The converted value is to be left adjusted on the field boundary. (The default is right justification.) Except for n conversions, the converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.
' '
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
+
A sign (+ or -) should always be placed before a number produced by a signed conversion. By default a sign is used only for negative numbers. A + overrides a space if both are used.

The five flag characters above are defined in the C standard. The SUSv2 specifies one further flag character.

'
For decimal conversion (i, d, u, f, F, g, G) the output is to be grouped with thousands' grouping characters if the locale information indicates any. Note that many versions of gcc(1) cannot parse this option and will issue a warning. SUSv2 does not include %'F.

glibc 2.2 adds one further flag character.

I
For decimal integer conversion (i, d, u) the output uses the locale's alternative output digits, if any. For example, since glibc 2.2.3 this will give Arabic-Indic digits in the Persian (`fa_IR') locale.

The field width

An optional decimal digit string (with non-zero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write `*' or `*m$' (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. A negative field width is taken as a `-' flag followed by a positive field width. In no case does a non-existent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

The precision

An optional precision, in the form of a period (`.') followed by an optional decimal digit string. Instead of a decimal digit string one may write `*' or `*m$' (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just `.', or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

The length modifier

Here, `integer conversion' stands for d, i, o, u, x, or X conversion.
hh
A following integer conversion corresponds to a signed char or unsigned char argument, or a following n conversion corresponds to a pointer to a signed char argument.
h
A following integer conversion corresponds to a short int or unsigned short int argument, or a following n conversion corresponds to a pointer to a short int argument.
l
(ell) A following integer conversion corresponds to a long int or unsigned long int argument, or a following n conversion corresponds to a pointer to a long int argument, or a following c conversion corresponds to a wint_t argument, or a following s conversion corresponds to a pointer to wchar_t argument.
ll
(ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.
L
A following a, A, e, E, f, F, g, or G conversion corresponds to a long double argument. (C99 allows %LF, but SUSv2 does not.)
q
(`quad'. 4.4BSD and Linux libc5 only. Don't use.) This is a synonym for ll.
j
A following integer conversion corresponds to an intmax_t or uintmax_t argument.
z
A following integer conversion corresponds to a size_t or ssize_t argument. (Linux libc5 has Z with this meaning. Don't use it.)
t
A following integer conversion corresponds to a ptrdiff_t argument.

The SUSv2 only knows about the length modifiers h (in hd, hi, ho, hx, hX, hn) and l (in ld, li, lo, lx, lX, ln, lc, ls) and L (in Le, LE, Lf, Lg, LG).

The conversion specifier

A character that specifies the type of conversion to be applied. The conversion specifiers and their meanings are:
d,i
The int argument is converted to signed decimal notation. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.
o,u,x,X
The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation. The letters abcdef are used for x conversions; the letters ABCDEF are used for X conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.
e,E
The double argument is rounded and converted in the style [-]d.ddde\*(Pmdd where there is one digit before the decimal-point character and the number of digits after it is equal to the precision; if the precision is missing, it is taken as 6; if the precision is zero, no decimal-point character appears. An E conversion uses the letter E (rather than e) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00.
f,F
The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.

(The SUSv2 does not know about F and says that character string representations for infinity and NaN may be made available. The C99 standard specifies `[-]inf' or `[-]infinity' for infinity, and a string starting with `nan' for NaN, in the case of f conversion, and `[-]INF' or `[-]INFINITY' or `NAN*' in the case of F conversion.)

g,G
The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
a,A
(C99; not in SUSv2) For a conversion, the double argument is converted to hexadecimal notation (using the letters abcdef) in the style [-]0xh.hhhhp\*(Pmd; for A conversion the prefix 0X, the letters ABCDEF, and the exponent separator P is used. There is one hexadecimal digit before the decimal point, and the number of digits after it is equal to the precision. The default precision suffices for an exact representation of the value if an exact representation in base 2 exists and otherwise is sufficiently large to distinguish values of type double. The digit before the decimal point is unspecified for non-normalized numbers, and non-zero but otherwise unspecified for normalized numbers.
c
If no l modifier is present, the int argument is converted to an unsigned char, and the resulting character is written. If an l modifier is present, the wint_t (wide character) argument is converted to a multibyte sequence by a call to the wcrtomb(3) function, with a conversion state starting in the initial state, and the resulting multibyte string is written.
s
If no l modifier is present: The const char * argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not including) a terminating null byte ('\0'); if a precision is specified, no more than the number specified are written. If a precision is given, no null byte need be present; if the precision is not specified, or is greater than the size of the array, the array must contain a terminating null byte.

If an l modifier is present: The const wchar_t * argument is expected to be a pointer to an array of wide characters. Wide characters from the array are converted to multibyte characters (each by a call to the wcrtomb(3) function, with a conversion state starting in the initial state before the first wide character), up to and including a terminating null wide character. The resulting multibyte characters are written up to (but not including) the terminating null byte. If a precision is specified, no more bytes than the number specified are written, but no partial multibyte characters are written. Note that the precision determines the number of bytes written, not the number of wide characters or screen positions. The array must contain a terminating null wide character, unless a precision is given and it is so small that the number of bytes written exceeds it before the end of the array is reached.

C
(Not in C99, but in SUSv2.) Synonym for lc. Don't use.
S
(Not in C99, but in SUSv2.) Synonym for ls. Don't use.
p
The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx).
n
The number of characters written so far is stored into the integer indicated by the int * (or variant) pointer argument. No argument is converted.
m
(Glibc extension.) Print output of strerror(errno). No argument is required.
%
A `%' is written. No argument is converted. The complete conversion specification is `%%'.

CONFORMING TO

The fprintf(), printf(), sprintf(), vprintf(), vfprintf(), and vsprintf() functions conform to C89 and C99. The snprintf() and vsnprintf() functions conform to C99.

Concerning the return value of snprintf(), SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough.

Linux libc4 knows about the five C standard flags. It knows about the length modifiers h,l,L, and the conversions cdeEfFgGinopsuxX, where F is a synonym for f. Additionally, it accepts D,O,U as synonyms for ld,lo,lu. (This is bad, and caused serious bugs later, when support for %D disappeared.) No locale-dependent radix character, no thousands' separator, no NaN or infinity, no %m$ and *m$.

Linux libc5 knows about the five C standard flags and the ' flag, locale, %m$ and *m$. It knows about the length modifiers h,l,L,Z,q, but accepts L and q both for long doubles and for long long integers (this is a bug). It no longer recognizes FDOU, but adds the conversion character m, which outputs strerror(errno).

glibc 2.0 adds conversion characters C and S.

glibc 2.1 adds length modifiers hh,j,t,z and conversion characters a,A.

glibc 2.2 adds the conversion character F with C99 semantics, and the flag character I.

NOTES

The glibc implementation of the functions snprintf() and vsnprintf() conforms to the C99 standard, that is, behaves as described above, since glibc version 2.1. Until glibc 2.0.6 they would return -1 when the output was truncated.

BUGS

Because sprintf() and vsprintf() assume an arbitrarily long string, callers must be careful not to overflow the actual space; this is often impossible to assure. Note that the length of the strings produced is locale-dependent and difficult to predict. Use snprintf() and vsnprintf() instead (or asprintf() and vasprintf).

Linux libc4.[45] does not have a snprintf(), but provides a libbsd that contains an snprintf() equivalent to sprintf(), that is, one that ignores the size argument. Thus, the use of snprintf() with early libc4 leads to serious security problems.

Code such as printf(foo); often indicates a bug, since foo may contain a % character. If foo comes from untrusted user input, it may contain %n, causing the printf() call to write to memory and creating a security hole.

EXAMPLE

To print to five decimal places:

#include <math.h>
#include <stdio.h>
fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));

To print a date and time in the form `Sunday, July 3, 10:02', where weekday and month are pointers to strings:

#include <stdio.h>
fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
        weekday, month, day, hour, min);

Many countries use the day-month-year order. Hence, an internationalized version must be able to print the arguments in an order specified by the format:

#include <stdio.h>
fprintf(stdout, format,
        weekday, month, day, hour, min);
where format depends on locale, and may permute the arguments. With the value
"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
one might obtain `Sonntag, 3. Juli, 10:02'.

To allocate a sufficiently large string and print into it (code correct for both glibc 2.0 and glibc 2.1):

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

char *
make_message(const char *fmt, ...)
{
    /* Guess we need no more than 100 bytes. */
    int n, size = 100;
    char *p, *np;
    va_list ap;

    if ((p = malloc(size)) == NULL)
        return NULL;

    while (1) {
        /* Try to print in the allocated space. */
        va_start(ap, fmt);
        n = vsnprintf(p, size, fmt, ap);
        va_end(ap);
        /* If that worked, return the string. */
        if (n > -1 && n < size)
            return p;
        /* Else try again with more space. */
        if (n > -1)    /* glibc 2.1 */
            size = n+1; /* precisely what is needed */
        else           /* glibc 2.0 */
            size *= 2;  /* twice the old size */
        if ((np = realloc (p, size)) == NULL) {
            free(p);
            return NULL;
        } else {
            p = np;
        }
    }
}

SEE ALSO

printf(1), asprintf(3), dprintf(3), scanf(3), setlocale(3), wcrtomb(3), wprintf(3), locale(5)


erfc (3)

 Continue to this page.


memcmp(3)

MEMCMP

Section: Linux Programmer's Manual (3)
Updated: 1993-04-10 Return to Main Contents

NAME

memcmp - compare memory areas

SYNOPSIS

#include <string.h>

int memcmp(const void *s1, const void *s2, size_t n);

DESCRIPTION

The memcmp() function compares the first n bytes of the memory areas s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

RETURN VALUE

The memcmp() function returns an integer less than, equal to, or greater than zero if the first n bytes of s1 is found, respectively, to be less than, to match, or be greater than the first n bytes of s2.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001.

SEE ALSO

bcmp(3), strcasecmp(3), strcmp(3), strcoll(3), strncasecmp(3), strncmp(3), wmemcmp(3)


mrand48 (3)

 Continue to this page.


perror(3)

PERROR

Section: Linux Programmer's Manual (3)
Updated: 2001-12-14 Return to Main Contents

NAME

perror - print a system error message

SYNOPSIS

#include <stdio.h>

void perror(const char *s);

#include <errno.h>

const char *sys_errlist[];
int sys_nerr;
int errno;

DESCRIPTION

The routine perror() produces a message on the standard error output, describing the last error encountered during a call to a system or library function. First (if s is not NULL and *s is not a null byte ('\0')) the argument string s is printed, followed by a colon and a blank. Then the message and a new-line.

To be of most use, the argument string should include the name of the function that incurred the error. The error number is taken from the external variable errno, which is set when errors occur but not cleared when non-erroneous calls are made.

The global error list sys_errlist[] indexed by errno can be used to obtain the error message without the newline. The largest message number provided in the table is sys_nerr -1. Be careful when directly accessing this list because new error values may not have been added to sys_errlist[].

When a system call fails, it usually returns -1 and sets the variable errno to a value describing what went wrong. (These values can be found in <errno.h>.) Many library functions do likewise. The function perror() serves to translate this error code into human-readable form. Note that errno is undefined after a successful library call: this call may well change this variable, even though it succeeds, for example because it internally used some other library function that failed. Thus, if a failing call is not immediately followed by a call to perror(), the value of errno should be saved.

CONFORMING TO

The function perror() and the external errno (see errno(3)) conform to C89, C99, 4.3BSD, POSIX.1-2001. The externals sys_nerr and sys_errlist conform to BSD.

NOTES

The externals sys_nerr and sys_errlist are defined by glibc, but in <stdio.h>.

SEE ALSO

err(3), errno(3), error(3), strerror(3)


cfgetospeed (3)

 Continue to this page.


j1 (3)

 Continue to this page.


recno(3)

RECNO

Section: Linux Programmer's Manual (3)
Updated: 1994-08-18 Return to Main Contents

NAME

recno - record number database access method

SYNOPSIS

#include <sys/types.h>
#include <db.h>

DESCRIPTION

The routine dbopen is the library interface to database files. One of the supported file formats is record number files. The general description of the database access methods is in dbopen(3), this manual page describes only the recno specific information.

The record number data structure is either variable or fixed-length records stored in a flat-file format, accessed by the logical record number. The existence of record number five implies the existence of records one through four, and the deletion of record number one causes record number five to be renumbered to record number four, as well as the cursor, if positioned after record number one, to shift down one record.

The recno access method specific data structure provided to dbopen is defined in the <db.h> include file as follows:

typedef struct {
    u_long  flags;
    u_int   cachesize;
    u_int   psize;
    int     lorder;
    size_t  reclen;
    u_char  bval;
    char   *bfname;
} RECNOINFO;

The elements of this structure are defined as follows:

flags
The flag value is specified by or'ing any of the following values:
R_FIXEDLEN
The records are fixed-length, not byte delimited. The structure element reclen specifies the length of the record, and the structure element bval is used as the pad character. Any records, inserted into the database, that are less than reclen bytes long are automatically padded.
R_NOKEY
In the interface specified by dbopen, the sequential record retrieval fills in both the caller's key and data structures. If the R_NOKEY flag is specified, the cursor routines are not required to fill in the key structure. This permits applications to retrieve records at the end of files without reading all of the intervening records.
R_SNAPSHOT
This flag requires that a snapshot of the file be taken when dbopen is called, instead of permitting any unmodified records to be read from the original file.
cachesize
A suggested maximum size, in bytes, of the memory cache. This value is only advisory, and the access method will allocate more memory rather than fail. If cachesize is 0 (no size is specified) a default cache is used.
psize
The recno access method stores the in-memory copies of its records in a btree. This value is the size (in bytes) of the pages used for nodes in that tree. If psize is 0 (no page size is specified) a page size is chosen based on the underlying file system I/O block size. See btree(3) for more information.
lorder
The byte order for integers in the stored database metadata. The number should represent the order as an integer; for example, big endian order would be the number 4,321. If lorder is 0 (no order is specified) the current host order is used.
reclen
The length of a fixed-length record.
bval
The delimiting byte to be used to mark the end of a record for variable-length records, and the pad character for fixed-length records. If no value is specified, newlines (``\n'') are used to mark the end of variable-length records and fixed-length records are padded with spaces.
bfname
The recno access method stores the in-memory copies of its records in a btree. If bfname is non-NULL, it specifies the name of the btree file, as if specified as the filename for a dbopen of a btree file.

The data part of the key/data pair used by the recno access method is the same as other access methods. The key is different. The data field of the key should be a pointer to a memory location of type recno_t, as defined in the <db.h> include file. This type is normally the largest unsigned integral type available to the implementation. The size field of the key should be the size of that type.

Because there can be no meta-data associated with the underlying recno access method files, any changes made to the default values (e.g., fixed record length or byte separator value) must be explicitly specified each time the file is opened.

In the interface specified by dbopen, using the put interface to create a new record will cause the creation of multiple, empty records if the record number is more than one greater than the largest record currently in the database.

ERRORS

The recno access method routines may fail and set errno for any of the errors specified for the library routine dbopen(3) or the following:
[EINVAL]
An attempt was made to add a record to a fixed-length database that was too large to fit.

BUGS

Only big and little endian byte order is supported.

SEE ALSO

btree(3) dbopen(3), hash(3), mpool(3)

Document Processing in a Relational Database System, Michael Stonebraker, Heidi Stettner, Joseph Kalash, Antonin Guttman, Nadene Lynn, Memorandum No. UCB/ERL M82/32, May 1982.


scandir(3)

SCANDIR

Section: Linux Programmer's Manual (3)
Updated: 2001-12-26 Return to Main Contents

NAME

scandir, alphasort, versionsort - scan a directory for matching entries

SYNOPSIS

#include <dirent.h>

int scandir(const char *dir, struct dirent ***namelist,

int(*filter)(const struct dirent *),
int(*compar)(const struct dirent **, const struct dirent **));

int alphasort(const void *a, const void *b);

int versionsort(const void *a, const void *b);

DESCRIPTION

The scandir() function scans the directory dir, calling filter() on each directory entry. Entries for which filter() returns non-zero are stored in strings allocated via malloc(3), sorted using qsort(3) with the comparison function compar(), and collected in array namelist which is allocated via malloc(3). If filter is NULL, all entries are selected.

The alphasort() and versionsort() functions can be used as the comparison function compar(). The former sorts directory entries using strcoll(3), the latter using strverscmp(3) on the strings (*a)->d_name and (*b)->d_name.

RETURN VALUE

The scandir() function returns the number of directory entries selected or -1 if an error occurs.

The alphasort() and versionsort() functions return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

ERRORS

ENOMEM
Insufficient memory to complete the operation.

CONFORMING TO

None of these functions is in POSIX.1-2001, but alphasort() and scandir() are under consideration for a future revision to POSIX.1.

The functions scandir() and alphasort() are from 4.3BSD, and have been available under Linux since libc4. Libc4 and libc5 use the more precise prototype

    int alphasort(const struct dirent ** a,
                  const struct dirent **b);

but glibc 2.0 returns to the imprecise BSD prototype.

The function versionsort() is a GNU extension, available since glibc 2.1.

Since glibc 2.1, alphasort() calls strcoll(3); earlier it used strcmp(3).

EXAMPLE

/* print files in current directory in reverse order */
#include <dirent.h>

int
main(void)
{
    struct dirent **namelist;
    int n;

    n = scandir(".", &namelist, 0, alphasort);
    if (n < 0)
        perror("scandir");
    else {
        while(n--) {
            printf("%s\n", namelist[n]->d_name);
            free(namelist[n]);
        }
        free(namelist);
    }
}

SEE ALSO

closedir(3), fnmatch(3), opendir(3), readdir(3), rewinddir(3), seekdir(3), strcmp(3), strcoll(3), strverscmp(3), telldir(3)


setgrent (3)

 Continue to this page.


sinh(3)

SINH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

sinh, sinhf, sinhl - hyperbolic sine function

SYNOPSIS

#include <math.h>

double sinh(double x);

float sinhf(float x);

long double sinhl(long double x);

Link with -lm.

DESCRIPTION

The sinh() function returns the hyperbolic sine of x, which is defined mathematically as (exp(x) - exp(-x)) / 2.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acosh(3), asinh(3), atanh(3), cosh(3), csinh(3), tanh(3)


y1 (3)

 Continue to this page.


yn (3)

 Continue to this page.


fwrite (3)

 Continue to this page.


toascii(3)

TOASCII

Section: Linux Programmer's Manual (3)
Updated: 1995-09-16 Return to Main Contents

NAME

toascii - convert character to ASCII

SYNOPSIS

#include <ctype.h>

int toascii(int c);

DESCRIPTION

toascii() converts c to a 7-bit unsigned char value that fits into the ASCII character set, by clearing the high-order bits.

RETURN VALUE

The value returned is that of the converted character.

CONFORMING TO

SVr4, BSD, POSIX.1-2001.

BUGS

Many people will be unhappy if you use this function. This function will convert accented letters into random characters.

SEE ALSO

isascii(3), tolower(3), toupper(3)


tsearch(3)

TSEARCH

Section: Linux Programmer's Manual (3)
Updated: 1995-09-24 Return to Main Contents

NAME

tsearch, tfind, tdelete, twalk, tdestroy - manage a binary tree

SYNOPSIS

#include <search.h>

void *tsearch(const void *key, void **rootp,
                int (*compar)(const void *, const void *));

void *tfind(const void *key, const void **rootp,
                int (*compar)(const void *, const void *));

void *tdelete(const void *key, void **rootp,
                int (*compar)(const void *, const void *));

void twalk(const void *root, void (*action)(const void *nodep,
                                   const VISIT which,
                                   const int depth));

#define _GNU_SOURCE

#include <search.h>

void tdestroy(void *root, void (*free_node)(void *nodep));

DESCRIPTION

tsearch(), tfind(), twalk(), and tdelete() manage a binary tree. They are generalized from Knuth (6.2.2) Algorithm T. The first field in each node of the tree is a pointer to the corresponding data item. (The calling program must store the actual data.) compar points to a comparison routine, which takes pointers to two items. It should return an integer which is negative, zero, or positive, depending on whether the first item is less than, equal to, or greater than the second.

tsearch() searches the tree for an item. key points to the item to be searched for. rootp points to a variable which points to the root of the tree. If the tree is empty, then the variable that rootp points to should be set to NULL. If the item is found in the tree, then tsearch() returns a pointer to it. If it is not found, then tsearch() adds it, and returns a pointer to the newly added item.

tfind() is like tsearch(), except that if the item is not found, then tfind() returns NULL.

tdelete() deletes an item from the tree. Its arguments are the same as for tsearch().

twalk() performs depth-first, left-to-right traversal of a binary tree. root points to the starting node for the traversal. If that node is not the root, then only part of the tree will be visited. twalk() calls the user function action each time a node is visited (that is, three times for an internal node, and once for a leaf). action, in turn, takes three arguments. The first is a pointer to the node being visited. The second is an integer which takes on the values preorder, postorder, and endorder depending on whether this is the first, second, or third visit to the internal node, or leaf if it is the single visit to a leaf node. (These symbols are defined in <search.h>.) The third argument is the depth of the node, with zero being the root.

(More commonly, preorder, postorder, and endorder are known as preorder, inorder, and postorder: before visiting the children, after the first and before the second, and after visiting the children. Thus, the choice of name postorder is rather confusing.)

tdestroy() removes the whole tree pointed to by root, freeing all resources allocated by the tsearch() function. For the data in each tree node the function free_node is called. The pointer to the data is passed as the argument to the function. If no such work is necessary free_node must point to a function doing nothing.

RETURN VALUE

tsearch() returns a pointer to a matching item in the tree, or to the newly added item, or NULL if there was insufficient memory to add the item. tfind() returns a pointer to the item, or NULL if no match is found. If there are multiple elements that match the key, the element returned is unspecified.

tdelete() returns a pointer to the parent of the item deleted, or NULL if the item was not found.

tsearch(), tfind(), and tdelete() also return NULL if rootp was NULL on entry.

CONFORMING TO

SVr4, POSIX.1-2001. The function tdestroy() is a GNU extension.

NOTES

twalk() takes a pointer to the root, while the other functions take a pointer to a variable which points to the root.

twalk() uses postorder to mean "after the left subtree, but before the right subtree". Some authorities would call this "inorder", and reserve "postorder" to mean "after both subtrees".

tdelete() frees the memory required for the node in the tree. The user is responsible for freeing the memory for the corresponding data.

The example program depends on the fact that twalk() makes no further reference to a node after calling the user function with argument "endorder" or "leaf". This works with the GNU library implementation, but is not in the SysV documentation.

EXAMPLE

The following program inserts twelve random numbers into a binary tree, where duplicate numbers are collapsed, then prints the numbers in order.

#include <search.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void *root = NULL;

void *
xmalloc(unsigned n)
{
    void *p;
    p = malloc(n);
    if (p)
        return p;
    fprintf(stderr, "insufficient memory\n");
    exit(EXIT_FAILURE);
}

int
compare(const void *pa, const void *pb)
{
    if (*(int *) pa < *(int *) pb)
        return -1;
    if (*(int *) pa > *(int *) pb)
        return 1;
    return 0;
}

void
action(const void *nodep, const VISIT which, const int depth)
{
    int *datap;

    switch(which) {
    case preorder:
        break;
    case postorder:
        datap = *(int **) nodep;
        printf("%6d\n", *datap);
        break;
    case endorder:
        break;
    case leaf:
        datap = *(int **) nodep;
        printf("%6d\n", *datap);
        break;
    }
}

int
main(void)
{
    int i, *ptr;
    void *val;

    srand(time(NULL));
    for (i = 0; i < 12; i++) {
        ptr = (int *) xmalloc(sizeof(int));
        *ptr = rand() & 0xff;
        val = tsearch((void *) ptr, &root, compare);
        if (val == NULL)
            exit(EXIT_FAILURE);
    }
    twalk(root, action);
    exit(EXIT_SUCCESS);
}

SEE ALSO

bsearch(3), hsearch(3), lsearch(3), qsort(3), feature_test_macros(7)


va_start (3)

 Continue to this page.


nftw (3)

 Continue to this page.


setjmp(3)

SETJMP

Section: Linux Programmer's Manual (3)
Updated: 1997-03-02 Return to Main Contents

NAME

setjmp, sigsetjmp - save stack context for non-local goto

SYNOPSIS

#include <setjmp.h>

int setjmp(jmp_buf env);
int sigsetjmp(sigjmp_buf env, int savesigs);

DESCRIPTION

setjmp() and longjmp(3) are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. setjmp() saves the stack context/environment in env for later use by longjmp(3). The stack context will be invalidated if the function which called setjmp() returns. sigsetjmp() is similar to setjmp(). If savesigs is non-zero, the set of blocked signals is saved in env and will be restored if a siglongjmp(3) is later performed with this env.

RETURN VALUE

setjmp() and sigsetjmp() return 0 if returning directly, and non-zero when returning from longjmp(3) using the saved context.

CONFORMING TO

C89, C99, and POSIX.1-2001 specify setjmp(). POSIX.1-2001 specifies sigsetjmp().

NOTES

POSIX does not specify whether setjmp() will save the signal context. (In System V it will not. In 4.3BSD it will, and there is a function _setjmp that will not.) If you want to save signal masks, use sigsetjmp(). setjmp() and sigsetjmp() make programs hard to understand and maintain. If possible an alternative should be used.

SEE ALSO

longjmp(3), siglongjmp(3)


__setfpucw(3)

__SETFPUCW

Section: Linux Programmer's Manual (3)
Updated: 1997-03-08 Return to Main Contents

NAME

__setfpucw - set fpu control word on i386 architecture (obsolete)

SYNOPSIS

#include <i386/fpu_control.h>

void __setfpucw((unsigned short) control_word);

DESCRIPTION

__setfpucw() transfers control_word to the registers of the fpu (floating point unit) on i386 architecture. This was used to control floating point precision, rounding and floating point exceptions.

AVAILABILITY

As of glibc 2.1 this function does not exist anymore. There are new functions from C99, with prototypes in /usr/include/fenv.h, to control fpu rounding modes, like fegetround, fesetround, and the floating point environment, like fegetenv, feholdexcept, fesetenv, feupdateenv and fpu exception handling, like feclearexcept, fegetexceptflag, feraiseexcept, fesetexceptflag, fetestexcept.

If direct access to the FPU control word is still needed, the _FPU_GETCW and _FPU_SETCW macros from /usr/include/fpu_control.h can be used.

EXAMPLE

__setfpucw(0x1372)

Set fpu control word on i386 architecture to

- extended precision

- rounding to nearest

- exceptions on overflow, zero divide and NaN

SEE ALSO

feclearexcept(3)
/usr/include/i386/fpu_control.h


isgraph (3)

 Continue to this page.


jn (3)

 Continue to this page.


tcflow (3)

 Continue to this page.


abort(3)

ABORT

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

abort - cause abnormal program termination

SYNOPSIS

#include <stdlib.h>

void abort(void);

DESCRIPTION

The abort() function causes abnormal program termination unless the signal SIGABRT is caught and the signal handler does not return. If the abort() function causes program termination, all open streams are closed and flushed.

If the SIGABRT signal is blocked or ignored, the abort() function will still override it.

RETURN VALUE

The abort() function never returns.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89, C99

SEE ALSO

sigaction(2), exit(3), raise(3)


fileno (3)

 Continue to this page.


regcomp (3)

 Continue to this page.


undocumented(3)

UNDOCUMENTED

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

none - undocumented library functions

SYNOPSIS

Undocumented library functions

DESCRIPTION

This man page mentions those library functions which are implemented in the standard libraries but not yet documented in man pages.

Solicitation

If you have information about these functions, please look in the source code, write a man page (using a style similar to that of the other Linux section 3 man pages), and send it to mtk-manpages@gmx.net for inclusion in the next man page release.

The List

authdes_create authdes_getucred authdes_pk_create backtrace backtrace_symbols backtrace_symbols_fd clntunix_create creat64 dn_skipname fcrypt fopencookie fp_nquery fp_query fp_resstat freading freeifaddrs freopen64 fseeko64 ftello64 ftw64 fwscanf get_avphys_pages getdirentries64 getmsg getnetname get_nprocs get_nprocs_conf get_phys_pages getpublickey getsecretkey getutmp getutmpx h_errlist host2netname hostalias if_freenameindex if_indextoname if_nameindex if_nametoindex inet_nsap_addr inet_nsap_ntoa init_des initstate_r libc_nls_init lio_listio mallinfo mallopt mcheck mprobe mstats netname2host netname2user nlist obstack_free obstack stuff parse_printf_format p_cdname p_cdnname p_class p_fqname p_option p_query printf_size printf_size_info p_rr p_time p_type putlong putshort rawmemchr readdir_r re_compile_fastmap re_compile_pattern register_printf_function re_match re_match_2 re_rx_search re_search re_search_2 re_set_registers re_set_syntax res_send_setqhook res_send_setrhook rexec rpmatch ruserpass sethostfile setkey_r setstate_r svc_exit svcudp_enablecache tell tmpnam_r tr_break tzsetwall ufc_dofinalperm ufc_doit user2netname utmpxname vlimit vtimes wcschrnul wcsftime wscanf xdr_authdes_cred xdr_authdes_verf xdr_cryptkeyarg xdr_cryptkeyres xdr_datum xdr_des_block xdr_domainname xdr_getcredres xdr_keybuf xdr_keystatus xdr_mapname xdr_netnamestr xdr_netobj xdr_passwd xdr_peername xdr_rmtcall_args xdr_rmtcallres xdr_unixcred xdr_yp_buf xdr_yp_inaddr xdr_ypbind_binding xdr_ypbind_resp xdr_ypbind_resptype xdr_ypbind_setdom xdr_ypdelete_args xdr_ypmaplist xdr_ypmaplist_str xdr_yppasswd xdr_ypreq_key xdr_ypreq_nokey xdr_ypresp_all xdr_ypresp_all_seq xdr_ypresp_key_val xdr_ypresp_maplist xdr_ypresp_master xdr_ypresp_order xdr_ypresp_val xdr_ypstat xdr_ypupdate_args yp_all yp_bind yperr_string yp_first yp_get_default_domain yp_maplist yp_master yp_match yp_next yp_order ypprot_err yp_unbind yp_update


getgrgid (3)

 Continue to this page.


getgrnam(3)

GETGRNAM

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

getgrnam, getgrnam_r, getgrgid, getgrgid_r - get group file entry

SYNOPSIS

#include <sys/types.h>
#include <grp.h>

struct group *getgrnam(const char *name);

struct group *getgrgid(gid_t gid);

int getgrnam_r(const char *name, struct group *gbuf,

          char *buf, size_t buflen, struct group **gbufp);

int getgrgid_r(gid_t gid, struct group *gbuf,

          char *buf, size_t buflen, struct group **gbufp);

DESCRIPTION

The getgrnam() function returns a pointer to a structure containing the broken-out fields of the record in the group database (e.g., the local group file /etc/group, NIS, and LDAP) that matches the group name name.

The getgrgid() function returns a pointer to a structure containing the broken-out fields of the record in the group database that matches the group ID gid.

The getgrnam_r() and getgrgid_r() functions obtain the same information, but store the retrieved group structure in the space pointed to by gbuf. This group structure contains pointers to strings, and these strings are stored in the buffer buf of size buflen. A pointer to the result (in case of success) or NULL (in case no entry was found or an error occurred) is stored in *gbufp.

The group structure is defined in <grp.h> as follows:

struct group {
    char   *gr_name;       /* group name */
    char   *gr_passwd;     /* group password */
    gid_t   gr_gid;        /* group ID */
    char  **gr_mem;        /* group members */
};

The maximum needed size for buf can be found using sysconf(3) with the _SC_GETGR_R_SIZE_MAX parameter.

RETURN VALUE

The getgrnam() and getgrgid() functions return a pointer to a group structure, or NULL if the matching entry is not found or an error occurs. If an error occurs, errno is set appropriately. If one wants to check errno after the call, it should be set to zero before the call.

The return value may point to static area, and may be overwritten by subsequent calls to getgrent(3), getgrgid(), or getgrnam().

The getgrnam_r() and getgrgid_r() functions return zero on success. In case of error, an error number is returned.

ERRORS

0 or ENOENT or ESRCH or EBADF or EPERM or ...
The given name or gid was not found.
EINTR
A signal was caught.
EIO
I/O error.
EMFILE
The maximum number (OPEN_MAX) of files was open already in the calling process.
ENFILE
The maximum number of files was open already in the system.
ENOMEM
Insufficient memory to allocate group structure.
ERANGE
Insufficient buffer space supplied.

FILES

/etc/group
local group database file

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001

NOTES

The formulation given above under "RETURN VALUE" is from POSIX.1-2001. It does not call "not found" an error, hence does not specify what value errno might have in this situation. But that makes it impossible to recognize errors. One might argue that according to POSIX errno should be left unchanged if an entry is not found. Experiments on various Unix-like systems shows that lots of different values occur in this situation: 0, ENOENT, EBADF, ESRCH, EWOULDBLOCK, EPERM and probably others.

SEE ALSO

endgrent(3), fgetgrent(3), getgrent(3), getpwnam(3), setgrent(3), group(5)


abs(3)

ABS

Section: Linux Programmer's Manual (3)
Updated: 2000-12-17 Return to Main Contents

NAME

abs, labs, llabs, imaxabs - compute the absolute value of an integer

SYNOPSIS

#include <stdlib.h>

int abs(int j);

long int labs(long int j);

long long int llabs(long long int j);

#include <inttypes.h>

intmax_t imaxabs(intmax_t j);

DESCRIPTION

The abs() function computes the absolute value of the integer argument j. The labs(), llabs() and imaxabs() functions compute the absolute value of the argument j of the appropriate integer type for the function.

RETURN VALUE

Returns the absolute value of the integer argument, of the appropriate integer type for the function.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C99. C89 only includes the abs() and labs() functions; the functions llabs() and imaxabs() were added in C99.

NOTES

Trying to take the absolute value of the most negative integer is not defined.

The llabs() function is included in glibc since version 2.0, but is not in libc5 or libc4. The imaxabs() function is included in glibc since version 2.1.1.

For llabs() to be declared, it may be necessary to define _ISOC99_SOURCE or _ISOC9X_SOURCE (depending on the version of glibc) before including any standard headers.

GCC handles abs() and labs() as builtin functions. GCC 3.0 also handles llabs() and imaxabs() as builtins.

SEE ALSO

cabs(3), ceil(3), fabs(3), floor(3), rint(3)


y0 (3)

 Continue to this page.


islower (3)

 Continue to this page.


isnan (3)

 Continue to this page.


isprint (3)

 Continue to this page.


ispunct (3)

 Continue to this page.


isspace (3)

 Continue to this page.


isxdigit (3)

 Continue to this page.


jrand48 (3)

 Continue to this page.


labs (3)

 Continue to this page.


ldiv (3)

 Continue to this page.


lfind (3)

 Continue to this page.


lgamma(3)

LGAMMA

Section: Linux Programmer's Manual (3)
Updated: 2002-08-10 Return to Main Contents

NAME

lgamma, lgammaf, lgammal, lgamma_r, lgammaf_r, lgammal_r - log gamma function

SYNOPSIS

#include <math.h>

double lgamma(double x);

float lgammaf(float x);

long double lgammal(long double x);

double lgamma_r(double x, int *signp);

float lgammaf_r(float x, int *signp);

long double lgammal_r(long double x, int *signp);

Compile with -std=c99; link with -lm.

DESCRIPTION

For the definition of the Gamma function, see tgamma(3).

The lgamma() function returns the natural logarithm of the absolute value of the Gamma function. The sign of the Gamma function is returned in the external integer signgam declared in <math.h>. It is 1 when the Gamma function is positive or zero, -1 when it is negative.

Since using a constant location signgam is not thread-safe, the functions lgamma_r() etc. have been introduced; they return this sign via the parameter signp.

For non-positive integer values of x, lgamma() returns HUGE_VAL, sets errno to ERANGE and raises the zero divide exception. (Similarly, lgammaf() returns HUGE_VALF and lgammal() returns HUGE_VALL.)

ERRORS

In order to check for errors, set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

A range error occurs if x is too large. A pole error occurs if x is a negative integer or zero.

CONFORMING TO

C99, SVr4, 4.3BSD

SEE ALSO

tgamma(3)


localeconv(3)

LOCALECONV

Section: Linux Programmer's Manual (3)
Updated: 1993-04-25 Return to Main Contents

NAME

localeconv - get numeric formatting information

SYNOPSIS

#include <locale.h>

struct lconv *localeconv(void);

DESCRIPTION

The localeconv() function returns a pointer to a struct lconv for the current locale. This structure is shown in locale(7), and contains all values associated with the locale categories LC_NUMERIC and LC_MONETARY. Programs may also use the functions printf(3) and strfmon(3), which behave according to the actual locale in use.

CONFORMING TO

C89, C99.

BUGS

The printf(3) family of functions may or may not honor the current locale.

SEE ALSO

locale(1), localedef(1), isalpha(3), nl_langinfo(3), setlocale(3), strcoll(3), strftime(3), locale(7)


acos(3)

ACOS

Section: Linux Programmer's Manual (3)
Updated: 2004-10-06 Return to Main Contents

NAME

acos, acosf, acosl - arc cosine function

SYNOPSIS

#include <math.h>

double acos(double x);
float acosf(float x);
long double acosl(long double x);

Link with -lm.

DESCRIPTION

The acos() function calculates the arc cosine of x; that is the value whose cosine is x. If x falls outside the range -1 to 1, acos() fails and errno is set.

RETURN VALUE

The acos() function returns the arc cosine in radians and the value is mathematically defined to be between 0 and PI (inclusive).

ERRORS

EDOM
x is out of range.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89, C99. The float and long double variants are C99 requirements.

SEE ALSO

asin(3), atan(3), atan2(3), cacos(3), cos(3), sin(3), tan(3)


puts(3)

PUTS

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

fputc, fputs, putc, putchar, puts - output of characters and strings

SYNOPSIS

#include <stdio.h>

int fputc(int c, FILE *stream);

int fputs(const char *s, FILE *stream);

int putc(int c, FILE *stream);

int putchar(int c);

int puts(const char *s);

DESCRIPTION

fputc() writes the character c, cast to an unsigned char, to stream.

fputs() writes the string s to stream, without its trailing '\0'.

putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.

putchar(c); is equivalent to putc(c,stdout).

puts() writes the string s and a trailing newline to stdout.

Calls to the functions described here can be mixed with each other and with calls to other output functions from the stdio library for the same output stream.

For non-locking counterparts, see unlocked_stdio(3).

RETURN VALUE

fputc(), putc() and putchar() return the character written as an unsigned char cast to an int or EOF on error.

puts() and fputs() return a non-negative number on success, or EOF on error.

CONFORMING TO

C89, C99

BUGS

It is not advisable to mix calls to output functions from the stdio library with low-level calls to write(2) for the file descriptor associated with the same output stream; the results will be undefined and very probably not what you want.

SEE ALSO

write(2), ferror(3), fopen(3), fputwc(3), fputws(3), fseek(3), fwrite(3), gets(3), putwchar(3), scanf(3), unlocked_stdio(3)


pututline (3)

 Continue to this page.


putw (3)

 Continue to this page.


qsort(3)

QSORT

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

qsort - sorts an array

SYNOPSIS

#include <stdlib.h>

void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));

DESCRIPTION

The qsort() function sorts an array with nmemb elements of size size. The base argument points to the start of the array.

The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.

RETURN VALUE

The qsort() function returns no value.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

NOTES

Library routines suitable for use as the compar argument include alphasort(3) and versionsort(3). To compare C strings, the comparison function can call strcmp(3), as shown in the example below.

EXAMPLE

For one example of use, see the example under bsearch(3).

Another example is the following example program, which sorts the strings given in its command-line arguments:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

static int
cmpstringp(const void *p1, const void *p2)
{
    /* The actual arguments to this function are "pointers to
       pointers to char", but strcmp() arguments are "pointers
       to char", hence the following cast plus dereference */

    return strcmp(* (char * const *) p1, * (char * const *) p2);
}

int
main(int argc, char *argv[])
{
    int j;

    assert(argc > 1);

    qsort(&argv[1], argc - 1, sizeof(char *), cmpstringp);

    for (j = 1; j < argc; j++)
        puts(argv[j]);
    exit(EXIT_SUCCESS);
}

SEE ALSO

sort(1), alphasort(3), strcmp(3), versionsort(3)


erand48 (3)

 Continue to this page.


gethostbyname(3)

GETHOSTBYNAME

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

gethostbyname, gethostbyaddr, sethostent, gethostent, endhostent, herror, hstrerror - get network host entry

SYNOPSIS

#include <netdb.h>
extern int h_errno;

struct hostent *gethostbyname(const char *name);

#include <sys/socket.h>       /* for AF_INET */
struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type);

void sethostent(int stayopen);

void endhostent(void);

void herror(const char *s);

const char *hstrerror(int err);

/* System V/POSIX extension */

struct hostent *gethostent(void);

/* GNU extensions */

struct hostent *gethostbyname2(const char *name, int af);

int gethostent_r(
        struct hostent *ret, char *buf, size_t buflen,
        struct hostent **result, int *h_errnop);

int gethostbyname_r(const char *name,
        struct hostent *ret, char *buf, size_t buflen,
        struct hostent **result, int *h_errnop);

int gethostbyname2_r(const char *name, int af,
        struct hostent *ret, char *buf, size_t buflen,
        struct hostent **result, int *h_errnop);

DESCRIPTION

The gethostbyname() function returns a structure of type hostent for the given host name. Here name is either a host name, or an IPv4 address in standard dot notation, or an IPv6 address in colon (and possibly dot) notation. (See RFC 1884 for the description of IPv6 addresses.) If name is an IPv4 or IPv6 address, no lookup is performed and gethostbyname() simply copies name into the h_name field and its struct in_addr equivalent into the h_addr_list[0] field of the returned hostent structure. If name doesn't end in a dot and the environment variable HOSTALIASES is set, the alias file pointed to by HOSTALIASES will first be searched for name (see hostname(7) for the file format). The current domain and its parents are searched unless name ends in a dot.

The gethostbyaddr() function returns a structure of type hostent for the given host address addr of length len and address type type. Valid address types are AF_INET and AF_INET6. The host address argument is a pointer to a struct of a type depending on the address type, for example a struct in_addr * (probably obtained via a call to inet_addr(3)) for address type AF_INET.

The sethostent() function specifies, if stayopen is true (1), that a connected TCP socket should be used for the name server queries and that the connection should remain open during successive queries. Otherwise, name server queries will use UDP datagrams.

The endhostent() function ends the use of a TCP connection for name server queries.

The (obsolete) herror() function prints the error message associated with the current value of h_errno on stderr.

The (obsolete) hstrerror() function takes an error number (typically h_errno) and returns the corresponding message string.

The domain name queries carried out by gethostbyname() and gethostbyaddr() use a combination of any or all of the name server named(8), a broken out line from /etc/hosts, and the Network Information Service (NIS or YP), depending upon the contents of the order line in /etc/host.conf. The default action is to query named(8), followed by /etc/hosts.

The hostent structure is defined in <netdb.h> as follows:

struct hostent {
    char  *h_name;            /* official name of host */
    char **h_aliases;         /* alias list */
    int    h_addrtype;        /* host address type */
    int    h_length;          /* length of address */
    char **h_addr_list;       /* list of addresses */
}
#define h_addr h_addr_list[0] /* for backward compatibility */

The members of the hostent structure are:

h_name
The official name of the host.
h_aliases
An array of alternative names for the host, terminated by a NULL pointer.
h_addrtype
The type of address; always AF_INET or AF_INET6 at present.
h_length
The length of the address in bytes.
h_addr_list
An array of pointers to network addresses for the host (in network byte order), terminated by a NULL pointer.
h_addr
The first address in h_addr_list for backward compatibility.

RETURN VALUE

The gethostbyname() and gethostbyaddr() functions return the hostent structure or a NULL pointer if an error occurs. On error, the h_errno variable holds an error number. When non-NULL, the return value may point at static data, see the notes below.

ERRORS

The variable h_errno can have the following values:
HOST_NOT_FOUND
The specified host is unknown.
NO_ADDRESS or NO_DATA
The requested name is valid but does not have an IP address.
NO_RECOVERY
A non-recoverable name server error occurred.
TRY_AGAIN
A temporary error occurred on an authoritative name server. Try again later.

FILES

/etc/host.conf
resolver configuration file
/etc/hosts
host database file
/etc/nsswitch.conf
name service switch configuration

CONFORMING TO

4.3BSD, POSIX.1-2001.

NOTES

The functions gethostbyname() and gethostbyaddr() may return pointers to static data, which may be overwritten by later calls. Copying the struct hostent does not suffice, since it contains pointers; a deep copy is required.

In the original BSD implementation the len argument of gethostbyname() was an int. The SUSv2 standard is buggy and declares the len parameter of gethostbyaddr() to be of type size_t. (That is wrong, because it has to be int, and size_t is not. POSIX.1-2001 makes it socklen_t, which is OK.) See also accept(2).

The BSD prototype for gethostbyaddr() uses const char * for the first argument.

POSIX.1-2001 marks gethostbyaddr() and gethostbyname() obsolescent. See getaddrinfo(3), getnameinfo(3), gai_strerror(3).

System V/POSIX Extension

POSIX requires the gethostent() call, that should return the next entry in the host data base. When using DNS/BIND this does not make much sense, but it may be reasonable if the host data base is a file that can be read line by line. On many systems a routine of this name reads from the file /etc/hosts. It may be available only when the library was built without DNS support. The glibc version will ignore ipv6 entries. This function is not reentrant, and glibc adds a reentrant version gethostent_r().

GNU Extensions

Glibc2 also has a gethostbyname2() that works like gethostbyname(), but permits to specify the address family to which the address must belong.

Glibc2 also has reentrant versions gethostbyname_r() and gethostbyname2_r(). These return 0 on success and non-zero on error. The result of the call is now stored in the struct with address ret. After the call, *result will be NULL on error or point to the result on success. Auxiliary data is stored in the buffer buf of length buflen. (If the buffer is too small, these functions will return ERANGE.) No global variable h_errno is modified, but the address of a variable in which to store error numbers is passed in h_errnop.

SEE ALSO

getaddrinfo(3), getipnodebyaddr(3), getipnodebyname(3), getnameinfo(3), inet_ntop(3), inet_pton(3), resolver(3), hosts(5), nsswitch.conf(5), hostname(7), named(8)


getlogin(3)

GETLOGIN

Section: Linux Programmer's Manual (3)
Updated: 2003-08-24 Return to Main Contents

NAME

getlogin, getlogin_r, cuserid - get user name

SYNOPSIS

#include <unistd.h>

char *getlogin(void);
int getlogin_r(char *buf, size_t bufsize);

#include <stdio.h>

char *cuserid(char *string);

DESCRIPTION

getlogin() returns a pointer to a string containing the name of the user logged in on the controlling terminal of the process, or a null pointer if this information cannot be determined. The string is statically allocated and might be overwritten on subsequent calls to this function or to cuserid().

getlogin_r() returns this same user name in the array buf of size bufsize.

cuserid() returns a pointer to a string containing a user name associated with the effective user ID of the process. If string is not a null pointer, it should be an array that can hold at least L_cuserid characters; the string is returned in this array. Otherwise, a pointer to a string in a static area is returned. This string is statically allocated and might be overwritten on subsequent calls to this function or to getlogin().

The macro L_cuserid is an integer constant that indicates how long an array you might need to store a user name. L_cuserid is declared in <stdio.h>.

These functions let your program identify positively the user who is running (cuserid()) or the user who logged in this session (getlogin()). (These can differ when set-user-ID programs are involved.)

For most purposes, it is more useful to use the environment variable LOGNAME to find out who the user is. This is more flexible precisely because the user can set LOGNAME arbitrarily.

RETURN VALUE

getlogin() returns a pointer to the user name when successful, and NULL on failure. getlogin_r() returns 0 when successful, and non-zero on failure.

ERRORS

POSIX specifies
EMFILE
The calling process already has the maximum allowed number of open files.
ENFILE
The system already has the maximum allowed number of open files.
ENXIO
The calling process has no controlling tty.
ERANGE
(getlogin_r) The length of the user name, including the terminating null byte, is larger than bufsize.

Linux/glibc also has

ENOENT
There was no corresponding entry in the utmp-file.
ENOMEM
Insufficient memory to allocate passwd structure.

FILES

/etc/passwd     password database file

/var/run/utmp   (traditionally /etc/utmp;
                        some libc versions used /var/adm/utmp)

CONFORMING TO

getlogin() and getlogin_r() specified in POSIX.1-2001.

System V has a cuserid() function which uses the real user ID rather than the effective user ID. The cuserid() function was included in the 1988 version of POSIX, but removed from the 1990 version. It was present in SUSv2, but removed in POSIX.1-2001.

OpenBSD has getlogin() and setlogin(), and a username associated with a session, even if it has no controlling tty.

BUGS

Unfortunately, it is often rather easy to fool getlogin(). Sometimes it does not work at all, because some program messed up the utmp file. Often, it gives only the first 8 characters of the login name. The user currently logged in on the controlling tty of our program need not be the user who started it. Avoid getlogin() for security-related purposes.

Note that glibc does not follow the POSIX spec and uses stdin instead of /dev/tty. A bug. (Other recent systems, like SunOS 5.8 and HP-UX 11.11 and FreeBSD 4.8 all return the login name also when stdin is redirected.)

Nobody knows precisely what cuserid() does; avoid it in portable programs. Or avoid it altogether: use getpwuid(geteuid()) instead, if that is what you meant. DO NOT USE cuserid().

SEE ALSO

geteuid(2), getuid(2)


getmntent(3)

GETMNTENT

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

getmntent, setmntent, addmntent, endmntent, hasmntopt, getmntent_r - get file system descriptor file entry

SYNOPSIS

#include <stdio.h>
#include <mntent.h>

FILE *setmntent(const char *filename, const char *type);

struct mntent *getmntent(FILE *fp);

int addmntent(FILE *fp, const struct mntent *mnt);

int endmntent(FILE *fp);

char *hasmntopt(const struct mntent *mnt, const char *opt);

/* GNU extension */
#define _GNU_SOURCE    /* or _SVID_SOURCE or _BSD_SOURCE */
#include <mntent.h>

struct mntent *getmntent_r(FILE *fp, struct mntent *mntbuf,
                           char *buf, int buflen);

DESCRIPTION

These routines are used to access the file system description file /etc/fstab and the mounted file system description file /etc/mtab.

The setmntent() function opens the file system description file fp and returns a file pointer which can be used by getmntent(). The argument type is the type of access required and can take the same values as the mode argument of fopen(3).

The getmntent() function reads the next line from the file system description file fp and returns a pointer to a structure containing the broken out fields from a line in the file. The pointer points to a static area of memory which is overwritten by subsequent calls to getmntent().

The addmntent() function adds the mntent structure mnt to the end of the open file fp.

The endmntent() function closes the file system description file fp.

The hasmntopt() function scans the mnt_opts field (see below) of the mntent structure mnt for a substring that matches opt. See <mntent.h> and mount(8) for valid mount options.

The reentrant getmntent_r() function is similar to getmntent(), but stores the struct mount in the provided *mntbuf and stores the strings pointed to by the entries in that struct in the provided array buf of size buflen.

The mntent structure is defined in <mntent.h> as follows:

struct mntent {
    char *mnt_fsname;   /* name of mounted file system */
    char *mnt_dir;      /* file system path prefix */
    char *mnt_type;     /* mount type (see mntent.h) */
    char *mnt_opts;     /* mount options (see mntent.h) */
    int   mnt_freq;     /* dump frequency in days */
    int   mnt_passno;   /* pass number on parallel fsck */
};

Since fields in the mtab and fstab files are separated by whitespace, octal escapes are used to represent the four characters space (\040), tab (\011), newline (\012) and backslash (\134) in those files when they occur in one of the four strings in a mntent structure. The routines addmntent() and getmntent() will convert from string representation to escaped representation and back.

RETURN VALUE

The getmntent() and getmntent_r() functions return a pointer to the mntent structure or NULL on failure.

The addmntent() function returns 0 on success and 1 on failure.

The endmntent() function always returns 1.

The hasmntopt() function returns the address of the substring if a match is found and NULL otherwise.

FILES

/etc/fstab          file system description file
/etc/mtab           mounted file system description file

CONFORMING TO

The non-reentrant functions are from SunOS 4.1.3. A routine getmntent_r() was introduced in HP-UX 10, but it returns an int. The prototype shown above is glibc-only. LSB deprecates the functions endhostent(), sethostent() and setmntent().

NOTES

System V also has a getmntent() function but the calling sequence differs, and the returned structure is different. Under System V /etc/mnttab is used. 4.4BSD and Digital Unix have a routine getmntinfo(), a wrapper around the system call getfsstat().

SEE ALSO

fopen(3), fstab(5), feature_test_macros(7), mount(8)


getnetent(3)

GETNETENT

Section: Linux Programmer's Manual (3)
Updated: 1993-05-15 Return to Main Contents

NAME

getnetent, getnetbyname, getnetbyaddr, setnetent, endnetent - get network entry

SYNOPSIS

#include <netdb.h>

struct netent *getnetent(void);

struct netent *getnetbyname(const char *name);

struct netent *getnetbyaddr(long net, int type);

void setnetent(int stayopen);

void endnetent(void);

DESCRIPTION

The getnetent() function reads the next line from the file /etc/networks and returns a structure netent containing the broken out fields from the line. The /etc/networks file is opened if necessary.

The getnetbyname() function returns a netent structure for the line from /etc/networks that matches the network name.

The getnetbyaddr() function returns a netent structure for the line that matches the network number net of type type.

The setnetent() function opens and rewinds the /etc/networks file. If stayopen is true (1), then the file will not be closed between calls to getnetbyname() and getnetbyaddr().

The endnetent() function closes /etc/networks.

The netent structure is defined in <netdb.h> as follows:

struct netent {
    char          *n_name;     /* official network name */
    char         **n_aliases;  /* alias list */
    int            n_addrtype; /* net address type */
    unsigned long  n_net;      /* network number */
}

The members of the netent structure are:

n_name
The official name of the network.
n_aliases
A zero terminated list of alternative names for the network.
n_addrtype
The type of the network number; always AF_INET.
n_net
The network number in host byte order.

RETURN VALUE

The getnetent(), getnetbyname() and getnetbyaddr() functions return the netent structure, or a NULL pointer if an error occurs or the end of the file is reached.

FILES

/etc/networks
networks database file

CONFORMING TO

4.3BSD, POSIX.1-2001.

SEE ALSO

getprotoent(3), getservent(3), networks(5)
RFC 1101


getopt(3)

GETOPT

Section: Linux Programmer's Manual (3)
Updated: 2004-07-28 Return to Main Contents

NAME

getopt, getopt_long, getopt_long_only - Parse command-line options

SYNOPSIS

#include <unistd.h>

int getopt(int argc, char * const argv[],
           const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;

#define _GNU_SOURCE

#include <getopt.h>

int getopt_long(int argc, char * const argv[],
           const char *optstring,
           const struct option *longopts, int *longindex);

int getopt_long_only(int argc, char * const argv[],
           const char *optstring,
           const struct option *longopts, int *longindex);

DESCRIPTION

The getopt() function parses the command-line arguments. Its arguments argc and argv are the argument count and array as passed to the main() function on program invocation. An element of argv that starts with '-' (and is not exactly "-" or "--") is an option element. The characters of this element (aside from the initial '-') are option characters. If getopt() is called repeatedly, it returns successively each of the option characters from each of the option elements.

If getopt() finds another option character, it returns that character, updating the external variable optind and a static variable nextchar so that the next call to getopt() can resume the scan with the following option character or argv-element.

If there are no more option characters, getopt() returns -1. Then optind is the index in argv of the first argv-element that is not an option.

optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. Two colons mean an option takes an optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"), then it is returned in optarg, otherwise optarg is set to zero. This is a GNU extension. If optstring contains W followed by a semicolon, then -W foo is treated as the long option --foo. (The -W option is reserved by POSIX.2 for implementation extensions.) This behavior is a GNU extension, not available with libraries before GNU libc 2.

By default, getopt() permutes the contents of argv as it scans, so that eventually all the non-options are at the end. Two other modes are also implemented. If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered. If the first character of optstring is '-', then each non-option argv-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other argv-elements in any order and that care about the ordering of the two.) The special argument "--" forces an end of option-scanning regardless of the scanning mode.

If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns '?'. The calling program may prevent the error message by setting opterr to 0.

If getopt() finds an option character in argv that was not included in optstring, or if it detects a missing option argument, it returns '?' and sets the external variable optopt to the actual option character. If the first character (following any optional '+' or '-' described above) of optstring is a colon (':'), then getopt() returns ':' instead of '?' to indicate a missing option argument. If an error was detected, and the first character of optstring is not a colon, and the external variable opterr is non-zero (which is the default), getopt() prints an error message.

The getopt_long() function works like getopt() except that it also accepts long options, started out by two dashes. (If the program accepts only long options, then optstring should be specified as an empty string (""), not NULL.) Long option names may be abbreviated if the abbreviation is unique or is an exact match for some defined option. A long option may take a parameter, of the form --arg=param or --arg param.

longopts is a pointer to the first element of an array of struct option declared in <getopt.h> as

struct option {
const char *name;
int has_arg;
int *flag;
int val;
};

The meanings of the different fields are:

name
is the name of the long option.
has_arg
is: no_argument (or 0) if the option does not take an argument; required_argument (or 1) if the option requires an argument; or optional_argument (or 2) if the option takes an optional argument.
flag
specifies how results are returned for a long option. If flag is NULL, then getopt_long() returns val. (For example, the calling program may set val to the equivalent short option character.) Otherwise, getopt_long() returns 0, and flag points to a variable which is set to val if the option is found, but left unchanged if the option is not found.
val
is the value to return, or to load into the variable pointed to by flag.

The last element of the array has to be filled with zeroes.

If longindex is not NULL, it points to a variable which is set to the index of the long option relative to longopts.

getopt_long_only() is like getopt_long(), but '-' as well as '--' can indicate a long option. If an option that starts with '-' (not '--') doesn't match a long option, but does match a short option, it is parsed as a short option instead.

RETURN VALUE

If an option was successfully found, then getopt() returns the option character. If all command-line options have been parsed, then getopt() returns -1. If getopt() encounters an option character that was not in optstring, then '?' is returned. If getopt() encounters an option with a missing argument, then the return value depends on the first character in optstring: if it is ':', then ':' is returned; otherwise '?' is returned.

getopt_long() and getopt_long_only() also return the option character when a short option is recognized. For a long option, they return val if flag is NULL, and 0 otherwise. Error and -1 returns are the same as for getopt(), plus '?' for an ambiguous match or an extraneous parameter.

ENVIRONMENT

POSIXLY_CORRECT
If this is set, then option processing stops as soon as a non-option argument is encountered.
_<PID>_GNU_nonoption_argv_flags_
This variable was used by bash 2.0 to communicate to GNU libc which arguments are the results of wildcard expansion and so should not be considered as options. This behavior was removed in bash version 2.01, but the support remains in GNU libc.

CONFORMING TO

getopt():
POSIX.2 and POSIX.1-2001, provided the environment variable POSIXLY_CORRECT is set. Otherwise, the elements of argv aren't really const, because we permute them. We pretend they're const in the prototype to be compatible with other systems.

On some older implementations, getopt() was declared in <stdio.h>. SUSv1 permitted the declaration to appear in either <unistd.h> or <stdio.h>. POSIX.1-2001 marked the use of <stdio.h> for this purpose as LEGACY. POSIX.1-2001 does not allow the declaration to appear in <stdio.h>.

BUGS

The POSIX.2 specification of getopt() has a technical error described in POSIX.2 Interpretation 150. The GNU implementation (and probably all other implementations) implements the correct behavior rather than that specified.

EXAMPLE

The following trivial example program uses getopt() to handle two program options: -n, with no associated value; and -t val, which expects an associated value.

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
    int flags, opt;
    int nsecs, tfnd;

    nsecs = 0;
    tfnd = 0;
    flags = 0;
    while ((opt = getopt(argc, argv, "nt:")) != -1) {
        switch (opt) {
        case 'n':
            flags = 1;
            break;
        case 't':
            nsecs = atoi(optarg);
            tfnd = 1;
            break;
        default: /* '?' */
            fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
                    argv[1]);
            exit(EXIT_FAILURE);
        }
    }

    printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);

    if (optind >= argc) {
        fprintf(stderr, "Expected argument after options\n");
        exit(EXIT_FAILURE);
    }

    printf("name argument = %s\n", argv[optind]);

    /* Other code omitted */

    exit(EXIT_SUCCESS);
}

The following example program illustrates the use of getopt_long() with most of its features.

#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <getopt.h>

int
main(int argc, char **argv)
{
    int c;
    int digit_optind = 0;

    while (1) {
        int this_option_optind = optind ? optind : 1;
        int option_index = 0;
        static struct option long_options[] = {
            {"add", 1, 0, 0},
            {"append", 0, 0, 0},
            {"delete", 1, 0, 0},
            {"verbose", 0, 0, 0},
            {"create", 1, 0, 'c'},
            {"file", 1, 0, 0},
            {0, 0, 0, 0}
        };

        c = getopt_long(argc, argv, "abc:d:012",
                 long_options, &option_index);
        if (c == -1)
            break;

        switch (c) {
        case 0:
            printf("option %s", long_options[option_index].name);
            if (optarg)
                printf(" with arg %s", optarg);
            printf("\n");
            break;

        case '0':
        case '1':
        case '2':
            if (digit_optind != 0 && digit_optind != this_option_optind)
              printf("digits occur in two different argv-elements.\n");
            digit_optind = this_option_optind;
            printf("option %c\n", c);
            break;

        case 'a':
            printf("option a\n");
            break;

        case 'b':
            printf("option b\n");
            break;

        case 'c':
            printf("option c with value '%s'\n", optarg);
            break;

        case 'd':
            printf("option d with value '%s'\n", optarg);
            break;

        case '?':
            break;

        default:
            printf("?? getopt returned character code 0%o ??\n", c);
        }
    }

    if (optind < argc) {
        printf("non-option ARGV-elements: ");
        while (optind < argc)
            printf("%s ", argv[optind++]);
        printf("\n");
    }

    exit(EXIT_SUCCESS);
}

SEE ALSO

getsubopt(3), feature_test_macros(7)


getservbyname (3)

 Continue to this page.


getservent(3)

GETSERVENT

Section: Linux Programmer's Manual (3)
Updated: 2001-07-25 Return to Main Contents

NAME

getservent, getservbyname, getservbyport, setservent, endservent - get service entry

SYNOPSIS

#include <netdb.h>

struct servent *getservent(void);

struct servent *getservbyname(const char *name, const char *proto);

struct servent *getservbyport(int port, const char *proto);

void setservent(int stayopen);

void endservent(void);

DESCRIPTION

The getservent() function reads the next line from the file /etc/services and returns a structure servent containing the broken out fields from the line. The /etc/services file is opened if necessary.

The getservbyname() function returns a servent structure for the line from /etc/services that matches the service name using protocol proto. If proto is NULL, any protocol will be matched.

The getservbyport() function returns a servent structure for the line that matches the port port given in network byte order using protocol proto. If proto is NULL, any protocol will be matched.

The setservent() function opens and rewinds the /etc/services file. If stayopen is true (1), then the file will not be closed between calls to getservbyname() and getservbyport().

The endservent() function closes /etc/services.

The servent structure is defined in <netdb.h> as follows:

struct servent {
    char  *s_name;       /* official service name */
    char **s_aliases;    /* alias list */
    int    s_port;       /* port number */
    char  *s_proto;      /* protocol to use */
}

The members of the servent structure are:

s_name
The official name of the service.
s_aliases
A zero terminated list of alternative names for the service.
s_port
The port number for the service given in network byte order.
s_proto
The name of the protocol to use with this service.

RETURN VALUE

The getservent(), getservbyname() and getservbyport() functions return the servent structure, or a NULL pointer if an error occurs or the end of the file is reached.

FILES

/etc/services
services database file

CONFORMING TO

4.3BSD, POSIX.1-2001.

SEE ALSO

getnetent(3), getprotoent(3), services(5)


getutid (3)

 Continue to this page.


getw(3)

GETW

Section: Linux Programmer's Manual (3)
Updated: 1995-09-16 Return to Main Contents

NAME

getw, putw - input and output of words (ints)

SYNOPSIS

#include <stdio.h>

int getw(FILE *stream);

int putw(int w, FILE *stream);

DESCRIPTION

getw() reads a word (that is, an int) from stream. It's provided for compatibility with SVr4. We recommend you use fread(3) instead. putw() writes the word w (that is, an int) to stream. It is provided for compatibility with SVr4, but we recommend you use fwrite(3) instead.

RETURN VALUE

Normally, getw() returns the word read, and putw() returns 0. On error, they return EOF.

CONFORMING TO

SVr4

BUGS

The value returned on error is also a legitimate data value. ferror(3) can be used to distinguish between the two cases.

SEE ALSO

ferror(3), fread(3), fwrite(3), getc(3), putc(3)


isatty(3)

ISATTY

Section: Linux Programmer's Manual (3)
Updated: 1995-04-20 Return to Main Contents

NAME

isatty - does this descriptor refer to a terminal

SYNOPSIS

#include <unistd.h>

int isatty(int desc);

DESCRIPTION

returns 1 if desc is an open descriptor connected to a terminal and 0 else.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

SEE ALSO

fstat(2), ttyname(3)


memfrob(3)

MEMFROB

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

memfrob - frobnicate (encrypt) a memory area

SYNOPSIS

#include <string.h>

void *memfrob(void *s, size_t n);

DESCRIPTION

The memfrob() function encrypts the first n bytes of the memory area s by exclusive-ORing each character with the number 42. The effect can be reversed by using memfrob() on the encrypted memory area.

Note that this function is not a proper encryption routine as the XOR constant is fixed, and is only suitable for hiding strings.

RETURN VALUE

The memfrob() function returns a pointer to the encrypted memory area.

CONFORMING TO

The memfrob() function is unique to the GNU C Library.

SEE ALSO

strfry(3)


memmove(3)

MEMMOVE

Section: Linux Programmer's Manual (3)
Updated: 1993-04-10 Return to Main Contents

NAME

memmove - copy memory area

SYNOPSIS

#include <string.h>

void *memmove(void *dest, const void *src, size_t n);

DESCRIPTION

The memmove() function copies n bytes from memory area src to memory area dest. The memory areas may overlap: copying takes place as though the bytes in src are first copied into a temporary array that does not overlap src or dst, and the bytes are then copied from the temporary array to dest.

RETURN VALUE

The memmove() function returns a pointer to dest.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001.

SEE ALSO

bcopy(3), memccpy(3), memcpy(3), strcpy(3), strncpy(3), wmemmove(3)


memset(3)

MEMSET

Section: Linux Programmer's Manual (3)
Updated: 1993-04-11 Return to Main Contents

NAME

memset - fill memory with a constant byte

SYNOPSIS

#include <string.h>

void *memset(void *s, int c, size_t n);

DESCRIPTION

The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

RETURN VALUE

The memset() function returns a pointer to the memory area s.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001.

SEE ALSO

bzero(3), swab(3), wmemset(3)


mkstemp(3)

MKSTEMP

Section: Linux Programmer's Manual (3)
Updated: 2001-12-23 Return to Main Contents

NAME

mkstemp - create a unique temporary file

SYNOPSIS

#include <stdlib.h>

int mkstemp(char *template);

DESCRIPTION

The mkstemp() function generates a unique temporary filename from template. The last six characters of template must be XXXXXX and these are replaced with a string that makes the filename unique. The file is then created with mode read/write and permissions 0666 (glibc 2.0.6 and earlier), 0600 (glibc 2.0.7 and later). Since it will be modified, template must not be a string constant, but should be declared as a character array. The file is opened with the open(2) O_EXCL flag, guaranteeing that when mkstemp() returns successfully we are the only user.

RETURN VALUE

On success, the mkstemp() function returns the file descriptor of the temporary file. On error, -1 is returned, and errno is set appropriately.

ERRORS

EEXIST
Could not create a unique temporary filename. Now the contents of template are undefined.
EINVAL
The last six characters of template were not XXXXXX. Now template is unchanged.

CONFORMING TO

4.3BSD, POSIX.1-2001

NOTES

The old behavior (creating a file with mode 0666) may be a security risk, especially since other Unix flavors use 0600, and somebody might overlook this detail when porting programs.

More generally, the POSIX specification does not say anything about file modes, so the application should make sure its umask is set appropriately before calling mkstemp().

The prototype is in <unistd.h> for libc4, libc5, glibc1; glibc2 follows POSIX.1 and has the prototype in <stdlib.h>.

SEE ALSO

mkdtemp(3), mktemp(3), tempnam(3), tmpfile(3), tmpnam(3)


mktime (3)

 Continue to this page.


nrand48 (3)

 Continue to this page.


rand(3)

RAND

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

rand, rand_r, srand - pseudo-random number generator

SYNOPSIS

#include <stdlib.h>

int rand(void);

int rand_r(unsigned int *seedp);

void srand(unsigned int seed);

DESCRIPTION

The rand() function returns a pseudo-random integer between 0 and RAND_MAX.

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call. This might just be the seed value to be used by the next call, or it might be something more elaborate. In order to get reproducible behavior in a threaded application, this state must be made explicit. The function rand_r() is supplied with a pointer to an unsigned int, to be used as state. This is a very small amount of state, so this function will be a weak pseudo-random generator. Try drand48_r(3) instead.

RETURN VALUE

The rand() and rand_r() functions return a value between 0 and RAND_MAX. The srand() function returns no value.

CONFORMING TO

The functions rand() and srand() conform to SVr4, 4.3BSD, C89, C99, POSIX.1-2001. The function rand_r() is from POSIX.1-2001.

NOTES

The versions of rand() and srand() in the Linux C Library use the same random number generator as random(3) and srandom(3), so the lower-order bits should be as random as the higher-order bits. However, on older rand() implementations, and on current implementations on different systems, the lower-order bits are much less random than the higher-order bits. Do not use this function in applications intended to be portable when good randomness is needed.

In Numerical Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the following comments are made:

"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

and never by anything resembling

j = 1 + (rand() % 10);

(which uses lower-order bits)."

Random-number generation is a complex topic. The Numerical Recipes in C book (see reference above) provides an excellent discussion of practical random-number generation issues in Chapter 7 (Random Numbers).

For a more theoretical discussion which also covers many practical issues in depth, see Chapter 3 (Random Numbers) in Donald E. Knuth's The Art of Computer Programming, volume 2 (Seminumerical Algorithms), 2nd ed.; Reading, Massachusetts: Addison-Wesley Publishing Company, 1981.

EXAMPLE

POSIX.1-2001 gives the following example of an implementation of rand() and srand(), possibly useful when one needs the same sequence on two different machines.

    static unsigned long next = 1;

    /* RAND_MAX assumed to be 32767 */
    int myrand(void) {
        next = next * 1103515245 + 12345;
        return((unsigned)(next/65536) % 32768);
    }

    void mysrand(unsigned seed) {
        next = seed;
    }

SEE ALSO

drand48(3), random(3)


random(3)

RANDOM

Section: Linux Programmer's Manual (3)
Updated: 2000-08-20 Return to Main Contents

NAME

random, srandom, initstate, setstate - random number generator

SYNOPSIS

#include <stdlib.h>

long int random(void);

void srandom(unsigned int seed);

char *initstate(unsigned int seed, char *state, size_t n);

char *setstate(char *state);

DESCRIPTION

The random() function uses a non-linear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16*((2**31)-1).

The srandom() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by random(). These sequences are repeatable by calling srandom() with the same seed value. If no seed value is provided, the random() function is automatically seeded with a value of 1.

The initstate() function allows a state array state to be initialized for use by random(). The size of the state array n is used by initstate() to decide how sophisticated a random number generator it should use --- the larger the state array, the better the random numbers will be. seed is the seed for the initialization, which specifies a starting point for the random number sequence, and provides for restarting at the same point.

The setstate() function changes the state array used by the random() function. The state array state is used for random number generation until the next call to initstate() or setstate(). state must first have been initialized using initstate() or be the result of a previous call of setstate().

RETURN VALUE

The random() function returns a value between 0 and RAND_MAX. The srandom() function returns no value. The initstate() and setstate() functions return a pointer to the previous state array, or NULL on error.

ERRORS

EINVAL
A state array of less than 8 bytes was specified to initstate().

CONFORMING TO

4.3BSD, POSIX.1-2001.

NOTES

Current "optimal" values for the size of the state array n are 8, 32, 64, 128, and 256 bytes; other amounts will be rounded down to the nearest known amount. Using less than 8 bytes will cause an error.

SEE ALSO

rand(3), srand(3)


seed48 (3)

 Continue to this page.


setlocale(3)

SETLOCALE

Section: Linux Programmer's Manual (3)
Updated: 1999-07-04 Return to Main Contents

NAME

setlocale - set the current locale

SYNOPSIS

#include <locale.h>

char *setlocale(int category, const char *locale);

DESCRIPTION

The setlocale() function is used to set or query the program's current locale.

If locale is not NULL, the program's current locale is modified according to the arguments. The argument category determines which parts of the program's current locale should be modified.

LC_ALL
for all of the locale.
LC_COLLATE
for regular expression matching (it determines the meaning of range expressions and equivalence classes) and string collation.
LC_CTYPE
for regular expression matching, character classification, conversion, case-sensitive comparison, and wide character functions.
LC_MESSAGES
for localizable natural-language messages.
LC_MONETARY
for monetary formatting.
LC_NUMERIC
for number formatting (such as the decimal point and the thousands separator).
LC_TIME
for time and date formatting.

The argument locale is a pointer to a character string containing the required setting of category. Such a string is either a well-known constant like "C" or "da_DK" (see below), or an opaque string that was returned by another call of setlocale().

If locale is , each part of the locale that should be modified is set according to the environment variables. The details are implementation dependent. For glibc, first (regardless of category), the environment variable LC_ALL is inspected, next the environment variable with the same name as the category (LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME) and finally the environment variable LANG. The first existing environment variable is used. If its value is not a valid locale specification, the locale is unchanged, and setlocale() returns NULL.

The locale C or POSIX is a portable locale; its LC_CTYPE part corresponds to the 7-bit ASCII character set.

A locale name is typically of the form language[_territory][.codeset][@modifier], where language is an ISO 639 language code, territory is an ISO 3166 country code, and codeset is a character set or encoding identifier like ISO-8859-1 or UTF-8. For a list of all supported locales, try "locale -a", cf. locale(1).

If locale is NULL, the current locale is only queried, not modified.

On startup of the main program, the portable C locale is selected as default. A program may be made portable to all locales by calling setlocale(LC_ALL, ) after program initialization, by using the values returned from a localeconv(3) call for locale-dependent information, by using the multi-byte and wide character functions for text processing if MB_CUR_MAX > 1, and by using strcoll(3), wcscoll(3) or strxfrm(3), wcsxfrm(3) to compare strings.

RETURN VALUE

A successful call to setlocale() returns an opaque string that corresponds to the locale set. This string may be allocated in static storage. The string returned is such that a subsequent call with that string and its associated category will restore that part of the process's locale. The return value is NULL if the request cannot be honored.

CONFORMING TO

C89, C99, POSIX.1-2001.

NOTES

Linux (that is, GNU libc) supports the portable locales C and POSIX. In the good old days there used to be support for the European Latin-1 ISO-8859-1 locale (e.g., in libc-4.5.21 and libc-4.6.27), and the Russian KOI-8 (more precisely, "koi-8r") locale (e.g., in libc-4.6.27), so that having an environment variable LC_CTYPE=ISO-8859-1 sufficed to make isprint(3) return the right answer. These days non-English speaking Europeans have to work a bit harder, and must install actual locale files.

SEE ALSO

locale(1), localedef(1), isalpha(3), localeconv(3), nl_langinfo(3), rpmatch(3), strcoll(3), strftime(3), charsets(7), locale(7)


setvbuf (3)

 Continue to this page.


sleep(3)

SLEEP

Section: Linux Programmer's Manual (3)
Updated: 1993-04-07 Return to Main Contents

NAME

sleep - Sleep for the specified number of seconds

SYNOPSIS

#include <unistd.h>

unsigned int sleep(unsigned int seconds);

DESCRIPTION

sleep() makes the current process sleep until seconds seconds have elapsed or a signal arrives which is not ignored.

RETURN VALUE

Zero if the requested time has elapsed, or the number of seconds left to sleep.

CONFORMING TO

POSIX.1-2001.

BUGS

sleep() may be implemented using SIGALRM; mixing calls to alarm(2) and sleep() is a bad idea.

Using longjmp(3) from a signal handler or modifying the handling of SIGALRM while sleeping will cause undefined results.

SEE ALSO

alarm(2), signal(2)


sqrt(3)

SQRT

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

sqrt, sqrtf, sqrtl - square root function

SYNOPSIS

#include <math.h>

double sqrt(double x);

float sqrtf(float x);

long double sqrtl(long double x);

Link with -lm.

DESCRIPTION

The sqrt() function returns the non-negative square root of x. It fails and sets errno to EDOM, if x is negative.

ERRORS

EDOM
x is negative.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

cbrt(3), csqrt(3), hypot(3)


strcpy(3)

STRCPY

Section: Linux Programmer's Manual (3)
Updated: 2007-06-15 Return to Main Contents

NAME

strcpy, strncpy - copy a string

SYNOPSIS

#include <string.h>

char *strcpy(char *dest, const char *src);

char *strncpy(char *dest, const char *src, size_t n);

DESCRIPTION

The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null terminated.

If the length of src is less than n, strncat() pads the remainder of dest with null bytes.

A simple implementation of strncpy() might be:

char*
strncpy(char *dest, const char *src, size_t n){
    size_t i;

    for(i = 0 ; i < n && src[i] != '\0' ; i++)
        dest[i] = src[i];
    for( ; i < n ; i++)
        dest[i] = '\0';

    return dest;
}

RETURN VALUE

The strcpy() and strncpy() functions return a pointer to the destination string dest.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

NOTES

Some programmers consider strncpy() to be inefficient and error prone. If the programmer knows (i.e., includes code to test!) that the size of dest is greater than the length of src, then strcpy() can be used.

If there is no terminating null byte in the first n characters of src, strncpy() produces an unterminated string in dest. Programmers often prevent this mistake by forcing termination as follows:

strncpy(buf, str, n);
if (n > 0)
    buf[n - 1]= ' ';

BUGS

If the destination string of a strcpy() is not large enough (that is, if the programmer was stupid or lazy, and failed to check the size before copying) then anything might happen. Overflowing fixed length strings is a favorite cracker technique.

SEE ALSO

bcopy(3), memccpy(3), memcpy(3), memmove(3), wcscpy(3), wcsncpy(3)


tcdrain (3)

 Continue to this page.


string(3)

STRING

Section: Linux Programmer's Manual (3)
Updated: 1993-04-09 Return to Main Contents

NAME

strcasecmp, strcat, strchr, strcmp, strcoll, strcpy, strcspn, strdup, strfry, strlen, strncat, strncmp, strncpy, strncasecmp, strpbrk, strrchr, strsep, strspn, strstr, strtok, strxfrm, index, rindex - string operations

SYNOPSIS

#include <strings.h>

int strcasecmp(const char *s1, const char *s2);

int strncasecmp(const char *s1, const char *s2, size_t n);

char *index(const char *s, int c);

char *rindex(const char *s, int c);

#include <string.h>

char *strcat(char *dest, const char *src);

char *strchr(const char *s, int c);

int strcmp(const char *s1, const char *s2);

int strcoll(const char *s1, const char *s2);

char *strcpy(char *dest, const char *src);

size_t strcspn(const char *s, const char *reject);

char *strdup(const char *s);

char *strfry(char *string);

size_t strlen(const char *s);

char *strncat(char *dest, const char *src, size_t n);

int strncmp(const char *s1, const char *s2, size_t n);

char *strncpy(char *dest, const char *src, size_t n);

char *strpbrk(const char *s, const char *accept);

char *strrchr(const char *s, int c);

char *strsep(char **stringp, const char *delim);

size_t strspn(const char *s, const char *accept);

char *strstr(const char *haystack, const char *needle);

char *strtok(char *s, const char *delim);

size_t strxfrm(char *dest, const char *src, size_t n);

DESCRIPTION

The string functions perform string operations on null-terminated strings. See the individual man pages for descriptions of each function.

SEE ALSO

index(3), rindex(3), strcasecmp(3), strcat(3), strchr(3), strcmp(3), strcoll(3), strcpy(3), strcspn(3), strdup(3), strfry(3), strlen(3), strncasecmp(3), strncat(3), strncmp(3), strncpy(3), strpbrk(3), strrchr(3), strsep(3), strspn(3), strstr(3), strtok(3), strxfrm(3)


strlen(3)

STRLEN

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strlen - calculate the length of a string

SYNOPSIS

#include <string.h>

size_t strlen(const char *s);

DESCRIPTION

The strlen() function calculates the length of the string s, not including the terminating `\0' character.

RETURN VALUE

The strlen() function returns the number of characters in s.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

SEE ALSO

string(3), wcslen(3), wcsnlen(3)


strncpy (3)

 Continue to this page.


strpbrk(3)

STRPBRK

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strpbrk - search a string for any of a set of characters

SYNOPSIS

#include <string.h>

char *strpbrk(const char *s, const char *accept);

DESCRIPTION

The strpbrk() function locates the first occurrence in the string s of any of the characters in the string accept.

RETURN VALUE

The strpbrk() function returns a pointer to the character in s that matches one of the characters in accept, or NULL if no such character is found.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strsep(3), strspn(3), strstr(3), strtok(3), wcspbrk(3)


strptime(3)

STRPTIME

Section: Linux Programmer's Manual (3)
Updated: 2001-11-12 Return to Main Contents

NAME

strptime - convert a string representation of time to a time tm structure

SYNOPSIS

#define _XOPEN_SOURCE /* glibc2 needs this */
#include <time.h>

char *strptime(const char *s, const char *format, struct tm *tm);

DESCRIPTION

The strptime() function is the converse function to strftime(3) and converts the character string pointed to by s to values which are stored in the tm structure pointed to by tm, using the format specified by format. Here format is a character string that consists of field descriptors and text characters, reminiscent of scanf(3). Each field descriptor consists of a % character followed by another character that specifies the replacement for the field descriptor. All other characters in the format string must have a matching character in the input string, except for whitespace, which matches zero or more whitespace characters in the input string. There should be whitespace or other alphanumeric characters between any two field descriptors.

The strptime() function processes the input string from left to right. Each of the three possible input elements (whitespace, literal, or format) are handled one after the other. If the input cannot be matched to the format string the function stops. The remainder of the format and input strings are not processed.

The supported input field descriptors are listed below. In case a text string (such as a weekday or month name) is to be matched, the comparison is case insensitive. In case a number is to be matched, leading zeros are permitted but not required.

%%
The % character.
%a or %A
The weekday name according to the current locale, in abbreviated form or the full name.
%b or %B or %h
The month name according to the current locale, in abbreviated form or the full name.
%c
The date and time representation for the current locale.
%C
The century number (0-99).
%d or %e
The day of month (1-31).
%D
Equivalent to %m/%d/%y. (This is the American style date, very confusing to non-Americans, especially since %d/%m/%y is widely used in Europe. The ISO 8601 standard format is %Y-%m-%d.)
%H
The hour (0-23).
%I
The hour on a 12-hour clock (1-12).
%j
The day number in the year (1-366).
%m
The month number (1-12).
%M
The minute (0-59).
%n
Arbitrary whitespace.
%p
The locale's equivalent of AM or PM. (Note: there may be none.)
%r
The 12-hour clock time (using the locale's AM or PM). In the POSIX locale equivalent to %I:%M:%S %p. If t_fmt_ampm is empty in the LC_TIME part of the current locale then the behavior is undefined.
%R
Equivalent to %H:%M.
%S
The second (0-60; 60 may occur for leap seconds; earlier also 61 was allowed).
%t
Arbitrary whitespace.
%T
Equivalent to %H:%M:%S.
%U
The week number with Sunday the first day of the week (0-53). The first Sunday of January is the first day of week 1.
%w
The weekday number (0-6) with Sunday = 0.
%W
The week number with Monday the first day of the week (0-53). The first Monday of January is the first day of week 1.
%x
The date, using the locale's date format.
%X
The time, using the locale's time format.
%y
The year within century (0-99). When a century is not otherwise specified, values in the range 69-99 refer to years in the twentieth century (1969-1999); values in the range 00-68 refer to years in the twenty-first century (2000-2068).
%Y
The year, including century (for example, 1991).

Some field descriptors can be modified by the E or O modifier characters to indicate that an alternative format or specification should be used. If the alternative format or specification does not exist in the current locale, the unmodified field descriptor is used.

The E modifier specifies that the input string may contain alternative locale-dependent versions of the date and time representation:

%Ec
The locale's alternative date and time representation.
%EC
The name of the base year (period) in the locale's alternative representation.
%Ex
The locale's alternative date representation.
%EX
The locale's alternative time representation.
%Ey
The offset from %EC (year only) in the locale's alternative representation.
%EY
The full alternative year representation.

The O modifier specifies that the numerical input may be in an alternative locale-dependent format:

%Od or %Oe
The day of the month using the locale's alternative numeric symbols; leading zeros are permitted but not required.
%OH
The hour (24-hour clock) using the locale's alternative numeric symbols.
%OI
The hour (12-hour clock) using the locale's alternative numeric symbols.
%Om
The month using the locale's alternative numeric symbols.
%OM
The minutes using the locale's alternative numeric symbols.
%OS
The seconds using the locale's alternative numeric symbols.
%OU
The week number of the year (Sunday as the first day of the week) using the locale's alternative numeric symbols.
%Ow
The number of the weekday (Sunday=0) using the locale's alternative numeric symbols.
%OW
The week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols.
%Oy
The year (offset from %C) using the locale's alternative numeric symbols.

The broken-down time structure tm is defined in <time.h> as follows:

struct tm {
    int tm_sec;        /* seconds */
    int tm_min;        /* minutes */
    int tm_hour;       /* hours */
    int tm_mday;       /* day of the month */
    int tm_mon;        /* month */
    int tm_year;       /* year */
    int tm_wday;       /* day of the week */
    int tm_yday;       /* day in the year */
    int tm_isdst;      /* daylight saving time */
};

RETURN VALUE

The return value of the function is a pointer to the first character not processed in this function call. In case the input string contains more characters than required by the format string the return value points right after the last consumed input character. In case the whole input string is consumed the return value points to the null byte at the end of the string. If strptime() fails to match all of the format string and therefore an error occurred the function returns NULL.

CONFORMING TO

SUSv2, POSIX.1-2001.

NOTES

In principle, this function does not initialize tm but only stores the values specified. This means that tm should be initialized before the call. Details differ a bit between different Unix systems. The GNU libc implementation does not touch those fields which are not explicitly specified, except that it recomputes the tm_wday and tm_yday field if any of the year, month, or day elements changed.

This function is available since libc 4.6.8. Linux libc4 and libc5 includes define the prototype unconditionally; glibc2 includes provide a prototype only when _XOPEN_SOURCE or _GNU_SOURCE are defined.

Before libc 5.4.13 whitespace (and the 'n' and 't' specifications) was not handled, no 'E' and 'O' locale modifier characters were accepted, and the 'C' specification was a synonym for the 'c' specification.

The 'y' (year in century) specification is taken to specify a year in the 20th century by libc4 and libc5. It is taken to be a year in the range 1950-2049 by glibc 2.0. It is taken to be a year in 1969-2068 since glibc 2.1.

Glibc Notes

For reasons of symmetry, glibc tries to support for strptime() the same format characters as for strftime(3). (In most cases the corresponding fields are parsed, but no field in tm is changed.) This leads to
%F
Equivalent to %Y-%m-%d, the ISO 8601 date format.
%g
The year corresponding to the ISO week number, but without the century (0-99).
%G
The year corresponding to the ISO week number. (For example, 1991.)
%u
The day of the week as a decimal number (1-7, where Monday = 1).
%V
The ISO 8601:1988 week number as a decimal number (1-53). If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1.
%z
An RFC-822/ISO 8601 standard time zone specification.
%Z
The timezone name.

Similarly, because of GNU extensions to strftime(3), %k is accepted as a synonym for %H, and %l should be accepted as a synonym for %I, and %P is accepted as a synonym for %p. Finally

%s
The number of seconds since the epoch, that is, since 1970-01-01 00:00:00 UTC. Leap seconds are not counted unless leap second support is available.

The GNU libc implementation does not require whitespace between two field descriptors.

EXAMPLE

The following example demonstrates the use of strptime() and strftime(3).

#include <stdio.h>
#include <time.h>

int
main(void)
{
    struct tm tm;
    char buf[255];

    strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
    strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
    puts(buf);
    exit(EXIT_SUCCESS);
}

SEE ALSO

time(2), getdate(3), scanf(3), setlocale(3), strftime(3), feature_test_macros(7)


strcspn (3)

 Continue to this page.


strrchr (3)

 Continue to this page.


strsep(3)

STRSEP

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strsep - extract token from string

SYNOPSIS

#include <string.h>

char *strsep(char **stringp, const char *delim);

DESCRIPTION

If *stringp is NULL, the strsep() function returns NULL and does nothing else. Otherwise, this function finds the first token in the string *stringp, where tokens are delimited by symbols in the string delim. This token is terminated with a `\0' character (by overwriting the delimiter) and *stringp is updated to point past the token. In case no delimiter was found, the token is taken to be the entire string *stringp, and *stringp is made NULL.

RETURN VALUE

The strsep() function returns a pointer to the token, that is, it returns the original value of *stringp.

CONFORMING TO

4.4BSD

NOTES

The strsep() function was introduced as a replacement for strtok(3), since the latter cannot handle empty fields. However, strtok(3) conforms to C89/C99 and hence is more portable.

BUGS

This function suffers from the same problems as strtok(3). In particular, it modifies the original string. Avoid it.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strpbrk(3), strspn(3), strstr(3), strtok(3)


strspn(3)

STRSPN

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strspn, strcspn - search a string for a set of characters

SYNOPSIS

#include <string.h>

size_t strspn(const char *s, const char *accept);

size_t strcspn(const char *s, const char *reject);

DESCRIPTION

The strspn() function calculates the length of the initial segment of s which consists entirely of characters in accept.

The strcspn() function calculates the length of the initial segment of s which consists entirely of characters not in reject.

RETURN VALUE

The strspn() function returns the number of characters in the initial segment of s which consist only of characters from accept.

The strcspn() function returns the number of characters in the initial segment of s which are not in the string reject.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strpbrk(3), strsep(3), strstr(3), strtok(3), wcsspn(3), wcscspn(3)


strstr(3)

STRSTR

Section: Linux Programmer's Manual (3)
Updated: 2005-04-05 Return to Main Contents

NAME

strstr - locate a substring

SYNOPSIS

#include <string.h>

char *strstr(const char *haystack, const char *needle);

#define _GNU_SOURCE

#include <string.h>

char *strcasestr(const char *haystack, const char *needle);

DESCRIPTION

The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating `\0' characters are not compared.

The strcasestr() function is like strstr(3), but ignores the case of both arguments.

RETURN VALUE

These functions return a pointer to the beginning of the substring, or NULL if the substring is not found.

CONFORMING TO

The strstr() function conforms to C89 and C99. The strcasestr() function is a non-standard extension.

BUGS

Early versions of Linux libc (like 4.5.26) would not allow an empty needle argument for strstr(). Later versions (like 4.6.27) work correctly, and return haystack when needle is empty.

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strcasecmp(3), strpbrk(3), strsep(3), strspn(3), strtok(3), wcsstr(3), feature_test_macros(7)


mkfifo(3)

MKFIFO

Section: Linux Programmer's Manual (3)
Updated: 1995-09-03 Return to Main Contents

NAME

mkfifo - make a FIFO special file (a named pipe)

SYNOPSIS

#include <sys/types.h>
#include <sys/stat.h>

int mkfifo(const char *pathname, mode_t mode);

DESCRIPTION

mkfifo() makes a FIFO special file with name pathname. mode specifies the FIFO's permissions. It is modified by the process's umask in the usual way: the permissions of the created file are (mode & ~umask).

A FIFO special file is similar to a pipe, except that it is created in a different way. Instead of being an anonymous communications channel, a FIFO special file is entered into the file system by calling mkfifo().

Once you have created a FIFO special file in this way, any process can open it for reading or writing, in the same way as an ordinary file. However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa. See fifo(7) for non-blocking handling of FIFO special files.

RETURN VALUE

On success mkfifo() returns 0. In the case of an error, -1 is returned (in which case, errno is set appropriately).

ERRORS

EACCES
One of the directories in pathname did not allow search (execute) permission.
EEXIST
pathname already exists.
ENAMETOOLONG
Either the total length of pathname is greater than PATH_MAX, or an individual filename component has a length greater than NAME_MAX. In the GNU system, there is no imposed limit on overall filename length, but some file systems may place limits on the length of a component.
ENOENT
A directory component in pathname does not exist or is a dangling symbolic link.
ENOSPC
The directory or filesystem has no room for the new file.
ENOTDIR
A component used as a directory in pathname is not, in fact, a directory.
EROFS
pathname refers to a read-only filesystem.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

mkfifo(1), close(2), open(2), read(2), stat(2), umask(2), write(2), mkfifoat(3), fifo(7)


mktemp(3)

MKTEMP

Section: Linux Programmer's Manual (3)
Updated: 1993-04-03 Return to Main Contents

NAME

mktemp - make a unique temporary filename

SYNOPSIS

#include <stdlib.h>

char *mktemp(char *template);

DESCRIPTION

The mktemp() function generates a unique temporary filename from template. The last six characters of template must be XXXXXX and these are replaced with a string that makes the filename unique. Since it will be modified, template must not be a string constant, but should be declared as a character array.

RETURN VALUE

The mktemp() function returns NULL on error (template did not end in XXXXXX) and template otherwise. If the call was successful, the last six bytes of template will have been modified in such a way that the resulting name is unique (does not exist already). If the call was unsuccessful, template is made an empty string.

ERRORS

EINVAL
The last six characters of template were not XXXXXX.

CONFORMING TO

4.3BSD, POSIX.1-2001.

NOTES

The prototype is in <unistd.h> for libc4, libc5, glibc1; glibc2 follows the Single Unix Specification and has the prototype in <stdlib.h>.

BUGS

Never use mktemp(). Some implementations follow 4.3BSD and replace XXXXXX by the current process ID and a single letter, so that at most 26 different names can be returned. Since on the one hand the names are easy to guess, and on the other hand there is a race between testing whether the name exists and opening the file, every use of mktemp() is a security risk. The race is avoided by mkstemp(3).

SEE ALSO

mkstemp(3), tempnam(3), tmpfile(3), tmpnam(3)


putpwent(3)

PUTPWENT

Section: Linux Programmer's Manual (3)
Updated: 1993-04-09 Return to Main Contents

NAME

putpwent - write a password file entry

SYNOPSIS

#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>

int putpwent(const struct passwd *p, FILE *stream);

DESCRIPTION

The putpwent() function writes a password entry from the structure p in the file associated with stream.

The passwd structure is defined in <pwd.h> as follows:

struct passwd {
    char    *pw_name;        /* user name */
    char    *pw_passwd;      /* user password */
    uid_t    pw_uid;         /* user ID */
    gid_t    pw_gid;         /* group ID */
    char    *pw_gecos;       /* real name */
    char    *pw_dir;         /* home directory */
    char    *pw_shell;       /* shell program */
};

RETURN VALUE

The putpwent() function returns 0 on success, or -1 if an error occurs.

ERRORS

EINVAL
Invalid (NULL) argument given.

CONFORMING TO

SVr4

SEE ALSO

endpwent(3), fgetpwent(3), getpw(3), getpwent(3), getpwnam(3), getpwuid(3), setpwent(3)


fts_set (3)

 Continue to this page.


strerror(3)

STRERROR

Section: Linux Programmer's Manual (3)
Updated: 2005-12-13 Return to Main Contents

NAME

strerror, strerror_r - return string describing error number

SYNOPSIS

#include <string.h>

char *strerror(int errnum);

char *strerror_r(int errnum, char *buf, size_t buflen);
                        /* GNU-specific strerror_r() */

#define _XOPEN_SOURCE 600
#include <string.h>

int strerror_r(int errnum, char *buf, size_t buflen);
                        /* XSI-compliant strerror_r() */

DESCRIPTION

The strerror() function returns a string describing the error code passed in the argument errnum, possibly using the LC_MESSAGES part of the current locale to select the appropriate language. This string must not be modified by the application, but may be modified by a subsequent call to perror(3) or strerror(). No library function will modify this string.

The strerror_r() function is similar to strerror(), but is thread safe. This function is available in two versions: an XSI-compliant version specified in POSIX.1-2001, and a GNU-specific version (available since glibc 2.0). If _XOPEN_SOURCE is defined with the value 600, then the XSI-compliant version is provided, otherwise the GNU-specific version is provided.

The XSI-compliant strerror_r() is preferred for portable applications. It returns the error string in the user-supplied buffer buf of length buflen.

The GNU-specific strerror_r() returns a pointer to a string containing the error message. This may be either a pointer to a string that the function stores in buf, or a pointer to some (immutable) static string (in which case buf is unused). If the function stores a string in buf, then at most buflen bytes are stored (the string may be truncated if buflen is too small) and the string always includes a terminating null byte.

RETURN VALUE

The strerror() and strerror_r() functions return the appropriate error description string, or an "Unknown error nnn" message if the error number is unknown.

The XSI-compliant strerror_r() function returns 0 on success; on error, -1 is returned and errno is set to indicate the error.

ERRORS

EINVAL
The value of errnum is not a valid error number.
ERANGE
Insufficient storage was supplied to contain the error description string.

CONFORMING TO

strerror() is specified by POSIX.1-2001, C89, C99. strerror_r() is specified by POSIX.1-2001.

The GNU-specific strerror_r() function is a non-standard extension.

POSIX.1-2001 permits strerror() to set errno if the call encounters an error, but does not specify what value should be returned as the function result in the event of an error. On some systems, strerror() returns NULL if the error number is unknown. On other systems, strerror() returns a string something like "Error nnn occurred" and sets errno to EINVAL if the error number is unknown.

SEE ALSO

err(3), errno(3), error(3), perror(3), strsignal(3), feature_test_macros(7)


strftime(3)

STRFTIME

Section: Linux Programmer's Manual (3)
Updated: 2005-11-23 Return to Main Contents

NAME

strftime - format date and time

SYNOPSIS

#include <time.h>

size_t strftime(char *s, size_t max, const char *format,
                const struct tm *tm);

DESCRIPTION

The strftime() function formats the broken-down time tm according to the format specification format and places the result in the character array s of size max.

Ordinary characters placed in the format string are copied to s without conversion. Conversion specifications are introduced by a `%' character, and terminated by a conversion specifier character, and are replaced in s as follows:

%a
The abbreviated weekday name according to the current locale.
%A
The full weekday name according to the current locale.
%b
The abbreviated month name according to the current locale.
%B
The full month name according to the current locale.
%c
The preferred date and time representation for the current locale.
%C
The century number (year/100) as a 2-digit integer. (SU)
%d
The day of the month as a decimal number (range 01 to 31).
%D
Equivalent to %m/%d/%y. (Yecch --- for Americans only. Americans should note that in other countries %d/%m/%y is rather common. This means that in international context this format is ambiguous and should not be used.) (SU)
%e
Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space. (SU)
%E
Modifier: use alternative format, see below. (SU)
%F
Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
%G
The ISO 8601 year with century as a decimal number. The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %y, except that if the ISO week number belongs to the previous or next year, that year is used instead. (TZ)
%g
Like %G, but without century, that is, with a 2-digit year (00-99). (TZ)
%h
Equivalent to %b. (SU)
%H
The hour as a decimal number using a 24-hour clock (range 00 to 23).
%I
The hour as a decimal number using a 12-hour clock (range 01 to 12).
%j
The day of the year as a decimal number (range 001 to 366).
%k
The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (See also %H.) (TZ)
%l
The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. (See also %I.) (TZ)
%m
The month as a decimal number (range 01 to 12).
%M
The minute as a decimal number (range 00 to 59).
%n
A newline character. (SU)
%O
Modifier: use alternative format, see below. (SU)
%p
Either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale. Noon is treated as `pm' and midnight as `am'.
%P
Like %p but in lowercase: `am' or `pm' or a corresponding string for the current locale. (GNU)
%r
The time in a.m. or p.m. notation. In the POSIX locale this is equivalent to `%I:%M:%S %p'. (SU)
%R
The time in 24-hour notation (%H:%M). (SU) For a version including the seconds, see %T below.
%s
The number of seconds since the Epoch, that is, since 1970-01-01 00:00:00 UTC. (TZ)
%S
The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.)
%t
A tab character. (SU)
%T
The time in 24-hour notation (%H:%M:%S). (SU)
%u
The day of the week as a decimal, range 1 to 7, Monday being 1. See also %w. (SU)
%U
The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W.
%V
The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. See also %U and %W. (SU)
%w
The day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u.
%W
The week number of the current year as a decimal number, range 00 to 53, starting with the first Monday as the first day of week 01.
%x
The preferred date representation for the current locale without the time.
%X
The preferred time representation for the current locale without the date.
%y
The year as a decimal number without a century (range 00 to 99).
%Y
The year as a decimal number including the century.
%z
The time-zone as hour offset from GMT. Required to emit RFC 822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z"). (GNU)
%Z
The time zone or name or abbreviation.
%+
The date and time in date(1) format. (TZ) (Not supported in glibc2.)
%%
A literal `%' character.

Some conversion specifications can be modified by preceding the conversion specifier character by the E or O modifier to indicate that an alternative format should be used. If the alternative format or specification does not exist for the current locale, the behavior will be as if the unmodified conversion specification were used. (SU) The Single Unix Specification mentions %Ec, %EC, %Ex, %EX, %Ey, %EY, %Od, %Oe, %OH, %OI, %Om, %OM, %OS, %Ou, %OU, %OV, %Ow, %OW, %Oy, where the effect of the O modifier is to use alternative numeric symbols (say, roman numerals), and that of the E modifier is to use a locale-dependent alternative representation.

The broken-down time structure tm is defined in <time.h>. See also ctime(3).

RETURN VALUE

The strftime() function returns the number of characters placed in the array s, not including the terminating null byte, provided the string, including the terminating null byte, fits. Otherwise, it returns 0, and the contents of the array is undefined. (Thus at least since libc 4.4.4; very old versions of libc, such as libc 4.4.1, would return max if the array was too small.)

Note that the return value 0 does not necessarily indicate an error; for example, in many locales %p yields an empty string.

ENVIRONMENT

The environment variables TZ and LC_TIME are used.

CONFORMING TO

SVr4, C89, C99. There are strict inclusions between the set of conversions given in ANSI C (unmarked), those given in the Single Unix Specification (marked SU), those given in Olson's timezone package (marked TZ), and those given in glibc (marked GNU), except that %+ is not supported in glibc2. On the other hand glibc2 has several more extensions. POSIX.1 only refers to ANSI C; POSIX.2 describes under date(1) several extensions that could apply to strftime() as well. The %F conversion is in C99 and POSIX.1-2001.

In SUSv2, the %S specified allowed a range of 00 to 61, to allow for the theoretical possibility of a minute that included a double leap second (there never has been such a minute).

NOTES

Glibc Notes

Glibc provides some extensions for conversion specifications. (These extensions are not specified in POSIX.1-2001, but a few other systems provide similar features.) Between the % character and the conversion specifier character, an optional flag and field width may be specified. (These precede the E or O modifiers, if present.)

The following flag characters are permitted:

_
(underscore) Pad a numeric result string with spaces.
-
(dash) Do not pad a numeric result string.
0
Pad a numeric result string with zeros even if the conversion specifier character uses space-padding by default.
^
Convert alphabetic characters in result string to upper case.
#
Swap the case of the result string. (This flag only works with certain conversion specifier characters, and of these, it is only really useful with %Z).

An optional decimal width specifier may follow the (possibly absent) flag. If the natural size of the field is smaller than this width, then the result string is padded (on the left) to the specified width.

BUGS

Some buggy versions of gcc complain about the use of %c: warning: `%c' yields only last 2 digits of year in some locales. Of course programmers are encouraged to use %c, it gives the preferred date and time representation. One meets all kinds of strange obfuscations to circumvent this gcc problem. A relatively clean one is to add an intermediate function

size_t
my_strftime(char *s, size_t max, const char *fmt,
            const struct tm *tm)
{
    return strftime(s, max, fmt, tm);
}

EXAMPLE

The program below can be used to experiment with strftime().

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    char outstr[200];
    time_t t;
    struct tm *tmp;

    t = time(NULL);
    tmp = localtime(&t);
    if (tmp == NULL) {
        perror("localtime");
        exit(EXIT_FAILURE);
    }

    if (strftime(outstr, sizeof(outstr), argv[1], tmp) == 0) {
        fprintf(stderr, "strftime returned 0");
        exit(EXIT_FAILURE);
    }

    printf("Result string is \"%s\"\n", outstr);
    exit(EXIT_SUCCESS);
} /* main */

Some examples of the result string produced by the glibc implementation of strftime() are as follows:

$ ./a.out "%m"
Result string is "11"
$ ./a.out "%5m"
Result string is "00011"
$ ./a.out "%_5m"
Result string is "   11"

SEE ALSO

date(1), time(2), ctime(3), setlocale(3), sprintf(3), strptime(3)


strncat (3)

 Continue to this page.


strsignal(3)

STRSIGNAL

Section: Linux Programmer's Manual (3)
Updated: 1999-02-08 Return to Main Contents

NAME

strsignal - return string describing signal

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

char *strsignal(int sig);

extern const char * const sys_siglist[];

DESCRIPTION

The strsignal() function returns a string describing the signal number passed in the argument sig. The string can only be used until the next call to strsignal().

The array sys_siglist holds the signal description strings indexed by signal number. The strsignal() function should be used if possible instead of this array.

RETURN VALUE

The strsignal() function returns the appropriate description string, or an unknown signal message if the signal number is invalid. On some systems (but not on Linux), a NULL pointer may be returned instead for an invalid signal number.

CONFORMING TO

This function is not part of any standard, but aside from Linux, it can be found on Solaris and the BSDs.

SEE ALSO

psignal(3), strerror(3), feature_test_macros(7)


strtod(3)

STRTOD

Section: Linux Programmer's Manual (3)
Updated: 2001-06-07 Return to Main Contents

NAME

strtod, strtof, strtold - convert ASCII string to floating point number

SYNOPSIS

#include <stdlib.h>

double strtod(const char *nptr, char **endptr);

#define _XOPEN_SOURCE 600 /* or #define _ISOC99_SOURCE */
#include <stdlib.h>

float strtof(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr);

DESCRIPTION

The strtod(), strtof(), and strtold() functions convert the initial portion of the string pointed to by nptr to double, float, and long double representation, respectively.

The expected form of the (initial portion of the) string is optional leading white space as recognized by isspace(3), an optional plus (``+'') or minus sign (``-'') and then either (i) a decimal number, or (ii) a hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-a-number).

A decimal number consists of a nonempty sequence of decimal digits possibly containing a radix character (decimal point, locale dependent, usually ``.''), optionally followed by a decimal exponent. A decimal exponent consists of an ``E'' or ``e'', followed by an optional plus or minus sign, followed by a non-empty sequence of decimal digits, and indicates multiplication by a power of 10.

A hexadecimal number consists of a ``0x'' or ``0X'' followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent. A binary exponent consists of a ``P'' or ``p'', followed by an optional plus or minus sign, followed by a non-empty sequence of decimal digits, and indicates multiplication by a power of 2. At least one of radix character and binary exponent must be present.

An infinity is either ``INF'' or ``INFINITY'', disregarding case.

A NAN is ``NAN'' (disregarding case) optionally followed by `(', a sequence of characters, followed by ')'. The character string specifies in an implementation-dependent way the type of NAN.

RETURN VALUE

These functions return the converted value, if any.

If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.

If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.

If the correct value would cause overflow, plus or minus HUGE_VAL (HUGE_VALF, HUGE_VALL) is returned (according to the sign of the value), and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

ERRORS

ERANGE
Overflow or underflow occurred.

CONFORMING TO

C89 describes strtod(), C99 describes the other two functions.

NOTES

Since 0 can legitimately be returned on both success and failure, the calling program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a non-zero value after the call.

EXAMPLE

See the example on the strtol(3) manual page; the use of the functions described in this manual page is similar.

SEE ALSO

atof(3), atoi(3), atol(3), strtol(3), strtoul(3), feature_test_macros(7)


strtok(3)

STRTOK

Section: Linux Programmer's Manual (3)
Updated: 2000-02-13 Return to Main Contents

NAME

strtok, strtok_r - extract tokens from strings

SYNOPSIS

#include <string.h>

char *strtok(char *str, const char *delim);

char *strtok_r(char *str, const char *delim, char **saveptr);

DESCRIPTION

The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

The delim argument specifies a set of characters that delimit the tokens in the parsed string. The caller may specify different strings in delim in successive calls that parse the same string.

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting character. If no more tokens are found, strtok() returns NULL.

A sequence of two or more contiguous delimiter characters in the parsed string is considered to be a single delimiter. Delimiter characters at the start or end of the string are ignored. Put another way: the tokens returned by strtok() are always non-empty strings.

The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

On the first call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored. In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

Different strings may be parsed concurrently using sequences of calls to strtok_r() that specify different saveptr arguments.

RETURN VALUE

The strtok() and strtok_r() functions return a pointer to the next token, or NULL if there are no more tokens.

CONFORMING TO

strtok()
SVr4, POSIX.1-2001, 4.3BSD, C89, C99.
strtok_r()
POSIX.1-2001

BUGS

Avoid using these functions. If you do use them, note that:

These functions modify their first argument.

These functions cannot be used on constant strings.

The identity of the delimiting character is lost.

The strtok() function uses a static buffer while parsing, so it's not thread safe. Use strtok_r() if this matters to you.

EXAMPLE

The following program uses nested loops that employ strtok_r() to break a string into a two-level hierarchy of tokens. The first command-line argument specifies the string to be parsed. The second argument specifies the delimiter character(s) to be used to separate that string into "major" tokens. The third argument specifies the delimiter character(s) to be used to separate the "major" tokens into subtokens.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char *argv[])
{
    char *str1, *str2, *token, *subtoken;
    char *saveptr1, *saveptr2;
    int j;

    if (argc != 4) {
        fprintf(stderr, "Usage: %s string delim subdelim\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }

    for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
        token = strtok_r(str1, argv[2], &saveptr1);
        if (token == NULL)
            break;
        printf("%d: %s\n", j, token);

        for (str2 = token; ; str2 = NULL) {
            subtoken = strtok_r(str2, argv[3], &saveptr2);
            if (subtoken == NULL)
                break;
            printf("	 --> %s\n", subtoken);
        }
    }

    exit(EXIT_SUCCESS);
} /* main */

An example of the output produced by this program is the following:

$ ./a.out 'a/bbb///cc;xxx:yyy:' ':;' '/'
1: a/bbb///cc
         --> a
         --> bbb
         --> cc
2: xxx
         --> xxx
3: yyy
         --> yyy

SEE ALSO

index(3), memchr(3), rindex(3), strchr(3), strpbrk(3), strsep(3), strspn(3), strstr(3), wcstok(3)


strtol(3)

STRTOL

Section: Linux Programmer's Manual (3)
Updated: 2002-05-30 Return to Main Contents

NAME

strtol, strtoll, strtoq - convert a string to a long integer

SYNOPSIS

#include <stdlib.h>

long int
strtol(const char *nptr, char **endptr, int base);

long long int
strtoll(const char *nptr, char **endptr, int base);

DESCRIPTION

The strtol() function converts the initial part of the string in nptr to a long integer value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0.

The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional `+' or `-' sign. If base is zero or 16, the string may then include a `0x' prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is `0', in which case it is taken as 8 (octal).

The remainder of the string is converted to a long int value in the obvious manner, stopping at the first character which is not a valid digit in the given base. (In bases above 10, the letter `A' in either upper or lower case represents 10, `B' represents 11, and so forth, with `Z' representing 35.)

If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, strtol() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not `\0' but **endptr is `\0' on return, the entire string is valid.

The strtoll() function works just like the strtol() function but returns a long long integer value.

RETURN VALUE

The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX. In both cases, errno is set to ERANGE. Precisely the same holds for strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX).

ERRORS

EINVAL
(not in C99) The given base contains an unsupported value.
ERANGE
The resulting value was out of range.

The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned).

CONFORMING TO

strtol() conforms to SVr4, 4.3BSD, C89, C99 and POSIX.1-2001, and strtoll() to C99 and POSIX.1-2001.

NOTES

Since strtol() can legitimately return 0, LONG_MAX, or LONG_MIN (LLONG_MAX or LLONG_MIN for strtoll()) on both success and failure, the calling program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a non-zero value after the call.

In locales other than the "C" locale, other strings may also be accepted. (For example, the thousands separator of the current locale may be supported.)

BSD also has

quad_t
strtoq(const char *nptr, char **endptr, int base);
with completely analogous definition. Depending on the wordsize of the current architecture, this may be equivalent to strtoll() or to strtol().

EXAMPLE

The program shown below demonstrates the use of strtol(). The first command line argument specifies a string from which strtol() should parse a number. The second (optional) argument specifies the base to be used for the conversion. (This argument is converted to numeric form using atoi(3), a function that performs no error checking and has a simpler interface than strtol().) Some examples of the results produced by this program are the following:

$ ./a.out 123
strtol() returned 123
$ ./a.out '    123'
strtol() returned 123
$ ./a.out 123abc
strtol() returned 123
Further characters after number: abc
$ ./a.out 123abc 55
strtol: Invalid argument
$ ./a.out ''
No digits were found
$ ./a.out 4000000000
strtol: Numerical result out of range
The source code of the program is as follows:

#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <errno.h>

int
main(int argc, char *argv[])
{
    int base;
    char *endptr, *str;
    long val;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    str = argv[1];
    base = (argc > 2) ? atoi(argv[2]) : 10;

    errno = 0;    /* To distinguish success/failure after call */
    val = strtol(str, &endptr, base);

    /* Check for various possible errors */

    if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
            || (errno != 0 && val == 0)) {
        perror("strtol");
        exit(EXIT_FAILURE);
    }

    if (endptr == str) {
        fprintf(stderr, "No digits were found\n");
        exit(EXIT_FAILURE);
    }

    /* If we got here, strtol() successfully parsed a number */

    printf("strtol() returned %ld\n", val);

    if (*endptr != '\0')        /* Not necessarily an error... */
        printf("Further characters after number: %s\n", endptr);

    exit(EXIT_SUCCESS);
}

SEE ALSO

atof(3), atoi(3), atol(3), strtod(3), strtoul(3)


strtoul(3)

STRTOUL

Section: Linux Programmer's Manual (3)
Updated: 2002-05-30 Return to Main Contents

NAME

strtoul, strtoull, strtouq - convert a string to an unsigned long integer

SYNOPSIS

#include <stdlib.h>

unsigned long int
strtoul(const char *nptr, char **endptr, int base);

unsigned long long int
strtoull(const char *nptr, char **endptr, int base);

DESCRIPTION

The strtoul() function converts the initial part of the string in nptr to an unsigned long integer value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0.

The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional `+' or `-' sign. If base is zero or 16, the string may then include a `0x' prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is `0', in which case it is taken as 8 (octal).

The remainder of the string is converted to an unsigned long int value in the obvious manner, stopping at the first character which is not a valid digit in the given base. (In bases above 10, the letter `A' in either upper or lower case represents 10, `B' represents 11, and so forth, with `Z' representing 35.)

If endptr is not NULL, strtoul() stores the address of the first invalid character in *endptr. If there were no digits at all, strtoul() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not `\0' but **endptr is `\0' on return, the entire string is valid.

The strtoull() function works just like the strtoul() function but returns an unsigned long long integer value.

RETURN VALUE

The strtoul() function returns either the result of the conversion or, if there was a leading minus sign, the negation of the result of the conversion represented as an unsigned value, unless the original (non-negated) value would overflow; in the latter case, strtoul() returns ULONG_MAX and sets the global variable errno to ERANGE. Precisely the same holds for strtoull() (with ULLONG_MAX instead of ULONG_MAX).

ERRORS

EINVAL
(not in C99) The given base contains an unsupported value.
ERANGE
The resulting value was out of range.

The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned).

CONFORMING TO

strtoul() conforms to SVr4, C89, C99 and POSIX-2001, and strtoull() to C99 and POSIX.1-2001.

NOTES

Since strtoul() can legitimately return 0 or LONG_MAX (LLONG_MAX for strtoull()) on both success and failure, the calling program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a non-zero value after the call.

In locales other than the "C" locale, other strings may be accepted. (For example, the thousands separator of the current locale may be supported.)

BSD also has

u_quad_t
strtouq(const char *nptr, char **endptr, int base);
with completely analogous definition. Depending on the wordsize of the current architecture, this may be equivalent to strtoull() or to strtoul().

Negative values are considered valid input and are silently converted to the equivalent unsigned long value.

EXAMPLE

See the example on the strtol(3) manual page; the use of the functions described in this manual page is similar.

SEE ALSO

atof(3), atoi(3), atol(3), strtod(3), strtol(3)


strxfrm(3)

STRXFRM

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strxfrm - string transformation

SYNOPSIS

#include <string.h>

size_t strxfrm(char *dest, const char *src, size_t n);

DESCRIPTION

The strxfrm() function transforms the src string into a form such that the result of strcmp(3) on two strings that have been transformed with strxfrm() is the same as the result of strcoll(3) on the two strings before their transformation. The first n characters of the transformed string are placed in dest. The transformation is based on the program's current locale for category LC_COLLATE. (See setlocale(3)).

RETURN VALUE

The strxfrm() function returns the number of bytes required to store the transformed string in dest excluding the terminating `\0' character. If the value returned is n or more, the contents of dest are indeterminate.

CONFORMING TO

SVr4, 4.3BSD, C89, C99

NOTES

In the "POSIX" or "C" locales strxfrm() is equivalent to copying the string with strncpy(3).

SEE ALSO

bcmp(3), memcmp(3), setlocale(3), strcasecmp(3), strcmp(3), strcoll(3)


swab(3)

SWAB

Section: Linux Programmer's Manual (3)
Updated: 2001-12-15 Return to Main Contents

NAME

swab - swap adjacent bytes

SYNOPSIS

#define _XOPEN_SOURCE
#include <unistd.h>

void swab(const void *from, void *to, ssize_t n);

DESCRIPTION

The swab() function copies n bytes from the array pointed to by from to the array pointed to by to, exchanging adjacent even and odd bytes. This function is used to exchange data between machines that have different low/high byte ordering.

This function does nothing when n is negative. When n is positive and odd, it handles n-1 bytes as above, and does something unspecified with the last byte. (In other words, n should be even.)

RETURN VALUE

The swab() function returns no value.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001

SEE ALSO

bstring(3), feature_test_macros(7)


tan(3)

TAN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

tan, tanf, tanl - tangent function

SYNOPSIS

#include <math.h>

double tan(double x);

float tanf(float x);

long double tanl(long double x);

Link with -lm.

DESCRIPTION

The tan() function returns the tangent of x, where x is given in radians.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), cos(3), ctan(3), sin(3)


tcflush (3)

 Continue to this page.


dn_comp (3)

 Continue to this page.


dn_expand (3)

 Continue to this page.


fputc (3)

 Continue to this page.


fgetc (3)

 Continue to this page.


profil(3)

PROFIL

Section: Linux Programmer's Manual (3)
Updated: 1993-07-23 Return to Main Contents

NAME

profil - execution time profile

SYNOPSIS

#include <unistd.h>

int profil(u_short *buf, size_t bufsiz, size_t offset, u_int scale);

DESCRIPTION

This routine provides a means to find out in what areas your program spends most of its time. The argument buf points to bufsiz bytes of core. Every virtual 10 milliseconds, the user's program counter (PC) is examined: offset is subtracted and the result is multiplied by scale and divided by 65536. If the resulting value is less than bufsiz, then the corresponding entry in buf is incremented. If buf is NULL, profiling is disabled.

RETURN VALUE

Zero is always returned.

CONFORMING TO

Similar to a call in SVr4 (but not POSIX.1-2001).

BUGS

profil() cannot be used on a program that also uses ITIMER_PROF itimers.

True kernel profiling provides more accurate results. Libc 4.4 contained a kernel patch providing a system call profil.

SEE ALSO

gprof(1), setitimer(2), sigaction(2), signal(2)


setpwent (3)

 Continue to this page.


srand48 (3)

 Continue to this page.


tcgetattr (3)

 Continue to this page.


termios(3)

TERMIOS

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

termios, tcgetattr, tcsetattr, tcsendbreak, tcdrain, tcflush, tcflow, cfmakeraw, cfgetospeed, cfgetispeed, cfsetispeed, cfsetospeed, cfsetspeed - get and set terminal attributes, line control, get and set baud rate

SYNOPSIS

#include <termios.h>
#include <unistd.h>

int tcgetattr(int fd, struct termios *termios_p);

int tcsetattr(int fd, int optional_actions, const struct termios *termios_p);

int tcsendbreak(int fd, int duration);

int tcdrain(int fd);

int tcflush(int fd, int queue_selector);

int tcflow(int fd, int action);

void cfmakeraw(struct termios *termios_p);

speed_t cfgetispeed(const struct termios *termios_p);

speed_t cfgetospeed(const struct termios *termios_p);

int cfsetispeed(struct termios *termios_p, speed_t speed);

int cfsetospeed(struct termios *termios_p, speed_t speed);

DESCRIPTION

The termios functions describe a general terminal interface that is provided to control asynchronous communications ports.

The termios structure

Many of the functions described here have a termios_p argument that is a pointer to a termios structure. This structure contains at least the following members:

tcflag_t c_iflag;      /* input modes */
tcflag_t c_oflag;      /* output modes */
tcflag_t c_cflag;      /* control modes */
tcflag_t c_lflag;      /* local modes */
cc_t     c_cc[NCCS];   /* control chars */

The values that may be assigned to these fields are described below. In the case of the first four bit-mask fields, the definitions of some of the associated flags that may be set are only exposed if a specific feature test macro (see feature_test_macros(7)) is defined, as noted in brackets ("[]").

In the descriptions below, "not in POSIX" means that the value is not specified in POSIX.1-2001, and "XSI" means that the value is specified in POSIX.1-2001 as part of the XSI extension.

c_iflag flag constants:

IGNBRK
Ignore BREAK condition on input.
BRKINT
If IGNBRK is set, a BREAK is ignored. If it is not set but BRKINT is set, then a BREAK causes the input and output queues to be flushed, and if the terminal is the controlling terminal of a foreground process group, it will cause a SIGINT to be sent to this foreground process group. When neither IGNBRK nor BRKINT are set, a BREAK reads as a null byte ('\0'), except when PARMRK is set, in which case it reads as the sequence \377 \0 \0.
IGNPAR
Ignore framing errors and parity errors.
PARMRK
If IGNPAR is not set, prefix a character with a parity error or framing error with \377 \0. If neither IGNPAR nor PARMRK is set, read a character with a parity error or framing error as \0.
INPCK
Enable input parity checking.
ISTRIP
Strip off eighth bit.
INLCR
Translate NL to CR on input.
IGNCR
Ignore carriage return on input.
ICRNL
Translate carriage return to newline on input (unless IGNCR is set).
IUCLC
(not in POSIX) Map uppercase characters to lowercase on input.
IXON
Enable XON/XOFF flow control on output.
IXANY
(XSI) Typing any character will restart stopped output. (The default is to allow just the START character to restart output.)
IXOFF
Enable XON/XOFF flow control on input.
IMAXBEL
(not in POSIX) Ring bell when input queue is full. Linux does not implement this bit, and acts as if it is always set.
IUTF8 (since Linux 2.6.4)
(not in POSIX) Input is UTF8; this allows character-erase to be correctly performed in cooked mode.

c_oflag flag constants defined in POSIX.1:

OPOST
Enable implementation-defined output processing.

The remaining c_oflag flag constants are defined in POSIX.1-2001, unless marked otherwise.

OLCUC
(not in POSIX) Map lowercase characters to uppercase on output.
ONLCR
(XSI) Map NL to CR-NL on output.
OCRNL
Map CR to NL on output.
ONOCR
Don't output CR at column 0.
ONLRET
Don't output CR.
OFILL
Send fill characters for a delay, rather than using a timed delay.
OFDEL
(not in POSIX) Fill character is ASCII DEL (0177). If unset, fill character is ASCII NUL ('\0'). (Not implemented on Linux.)
NLDLY
Newline delay mask. Values are NL0 and NL1. [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]
CRDLY
Carriage return delay mask. Values are CR0, CR1, CR2, or CR3. [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]
TABDLY
Horizontal tab delay mask. Values are TAB0, TAB1, TAB2, TAB3 (or XTABS). A value of TAB3, that is, XTABS, expands tabs to spaces (with tab stops every eight columns). [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]
BSDLY
Backspace delay mask. Values are BS0 or BS1. (Has never been implemented.) [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]
VTDLY
Vertical tab delay mask. Values are VT0 or VT1.
FFDLY
Form feed delay mask. Values are FF0 or FF1. [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]

c_cflag flag constants:

CBAUD
(not in POSIX) Baud speed mask (4+1 bits). [requires _BSD_SOURCE or _SVID_SOURCE]
CBAUDEX
(not in POSIX) Extra baud speed mask (1 bit), included in CBAUD. [requires _BSD_SOURCE or _SVID_SOURCE]

(POSIX says that the baud speed is stored in the termios structure without specifying where precisely, and provides cfgetispeed() and cfsetispeed() for getting at it. Some systems use bits selected by CBAUD in c_cflag, other systems use separate fields, for example, sg_ispeed and sg_ospeed.)

CSIZE
Character size mask. Values are CS5, CS6, CS7, or CS8.
CSTOPB
Set two stop bits, rather than one.
CREAD
Enable receiver.
PARENB
Enable parity generation on output and parity checking for input.
PARODD
If set, then parity for input and output is odd; otherwise even parity is used.
HUPCL
Lower modem control lines after last process closes the device (hang up).
CLOCAL
Ignore modem control lines.
LOBLK
(not in POSIX) Block output from a noncurrent shell layer. For use by shl (shell layers). (Not implemented on Linux.)
CIBAUD
(not in POSIX) Mask for input speeds. The values for the CIBAUD bits are the same as the values for the CBAUD bits, shifted left IBSHIFT bits. [requires _BSD_SOURCE or _SVID_SOURCE] (Not implemented on Linux.)
CMSPAR
(not in POSIX) Use "stick" (mark/space) parity (supported on certain serial devices): if PARODD is set, the parity bit is always 1; if PARODD is not set, then the parity bit is always 0). [requires _BSD_SOURCE or _SVID_SOURCE]
CRTSCTS
(not in POSIX) Enable RTS/CTS (hardware) flow control. [requires _BSD_SOURCE or _SVID_SOURCE]

c_lflag flag constants:

ISIG
When any of the characters INTR, QUIT, SUSP, or DSUSP are received, generate the corresponding signal.
ICANON
Enable canonical mode (described below).
XCASE
(not in POSIX; not supported under Linux) If ICANON is also set, terminal is uppercase only. Input is converted to lowercase, except for characters preceded by \. On output, uppercase characters are preceded by \ and lowercase characters are converted to uppercase.
ECHO
Echo input characters.
ECHOE
If ICANON is also set, the ERASE character erases the preceding input character, and WERASE erases the preceding word.
ECHOK
If ICANON is also set, the KILL character erases the current line.
ECHONL
If ICANON is also set, echo the NL character even if ECHO is not set.
ECHOCTL
(not in POSIX) If ECHO is also set, ASCII control signals other than TAB, NL, START, and STOP are echoed as ^X, where X is the character with ASCII code 0x40 greater than the control signal. For example, character 0x08 (BS) is echoed as ^H. [requires _BSD_SOURCE or _SVID_SOURCE]
ECHOPRT
(not in POSIX) If ICANON and IECHO are also set, characters are printed as they are being erased. [requires _BSD_SOURCE or _SVID_SOURCE]
ECHOKE
(not in POSIX) If ICANON is also set, KILL is echoed by erasing each character on the line, as specified by ECHOE and ECHOPRT. [requires _BSD_SOURCE or _SVID_SOURCE]
DEFECHO
(not in POSIX) Echo only when a process is reading. (Not implemented on Linux.)
FLUSHO
(not in POSIX; not supported under Linux) Output is being flushed. This flag is toggled by typing the DISCARD character. [requires _BSD_SOURCE or _SVID_SOURCE]
NOFLSH
Disable flushing the input and output queues when generating the SIGINT, SIGQUIT and SIGSUSP signals.
TOSTOP
Send the SIGTTOU signal to the process group of a background process which tries to write to its controlling terminal.
PENDIN
(not in POSIX; not supported under Linux) All characters in the input queue are reprinted when the next character is read. (bash handles typeahead this way.) [requires _BSD_SOURCE or _SVID_SOURCE]
IEXTEN
Enable implementation-defined input processing. This flag, as well as ICANON must be enabled for the special characters EOL2, LNEXT, REPRINT, WERASE to be interpreted, and for the IUCLC flag to be effective.

The c_cc array defines the special control characters. The symbolic indices (initial values) and meaning are:

VINTR
(003, ETX, Ctrl-C, or also 0177, DEL, rubout) Interrupt character. Send a SIGINT signal. Recognized when ISIG is set, and then not passed as input.
VQUIT
(034, FS, Ctrl-\) Quit character. Send SIGQUIT signal. Recognized when ISIG is set, and then not passed as input.
VERASE
(0177, DEL, rubout, or 010, BS, Ctrl-H, or also #) Erase character. This erases the previous not-yet-erased character, but does not erase past EOF or beginning-of-line. Recognized when ICANON is set, and then not passed as input.
VKILL
(025, NAK, Ctrl-U, or Ctrl-X, or also @) Kill character. This erases the input since the last EOF or beginning-of-line. Recognized when ICANON is set, and then not passed as input.
VEOF
(004, EOT, Ctrl-D) End-of-file character. More precisely: this character causes the pending tty buffer to be sent to the waiting user program without waiting for end-of-line. If it is the first character of the line, the read(2) in the user program returns 0, which signifies end-of-file. Recognized when ICANON is set, and then not passed as input.
VMIN
Minimum number of characters for non-canonical read.
VEOL
(0, NUL) Additional end-of-line character. Recognized when ICANON is set.
VTIME
Timeout in deciseconds for non-canonical read.
VEOL2
(not in POSIX; 0, NUL) Yet another end-of-line character. Recognized when ICANON is set.
VSWTCH
(not in POSIX; not supported under Linux; 0, NUL) Switch character. (Used by shl only.)
VSTART
(021, DC1, Ctrl-Q) Start character. Restarts output stopped by the Stop character. Recognized when IXON is set, and then not passed as input.
VSTOP
(023, DC3, Ctrl-S) Stop character. Stop output until Start character typed. Recognized when IXON is set, and then not passed as input.
VSUSP
(032, SUB, Ctrl-Z) Suspend character. Send SIGTSTP signal. Recognized when ISIG is set, and then not passed as input.
VDSUSP
(not in POSIX; not supported under Linux; 031, EM, Ctrl-Y) Delayed suspend character: send SIGTSTP signal when the character is read by the user program. Recognized when IEXTEN and ISIG are set, and the system supports job control, and then not passed as input.
VLNEXT
(not in POSIX; 026, SYN, Ctrl-V) Literal next. Quotes the next input character, depriving it of a possible special meaning. Recognized when IEXTEN is set, and then not passed as input.
VWERASE
(not in POSIX; 027, ETB, Ctrl-W) Word erase. Recognized when ICANON and IEXTEN are set, and then not passed as input.
VREPRINT
(not in POSIX; 022, DC2, Ctrl-R) Reprint unread characters. Recognized when ICANON and IEXTEN are set, and then not passed as input.
VDISCARD
(not in POSIX; not supported under Linux; 017, SI, Ctrl-O) Toggle: start/stop discarding pending output. Recognized when IEXTEN is set, and then not passed as input.
VSTATUS
(not in POSIX; not supported under Linux; status request: 024, DC4, Ctrl-T).

These symbolic subscript values are all different, except that VTIME, VMIN may have the same value as VEOL, VEOF, respectively. In non-canonical mode the special character meaning is replaced by the timeout meaning. For an explanation of VMIN and VTIME, see the description of non-canonical mode below.

Retrieving and changing terminal settings

tcgetattr() gets the parameters associated with the object referred by fd and stores them in the termios structure referenced by termios_p. This function may be invoked from a background process; however, the terminal attributes may be subsequently changed by a foreground process.

tcsetattr() sets the parameters associated with the terminal (unless support is required from the underlying hardware that is not available) from the termios structure referred to by termios_p. optional_actions specifies when the changes take effect:

TCSANOW
the change occurs immediately.
TCSADRAIN
the change occurs after all output written to fd has been transmitted. This function should be used when changing parameters that affect output.
TCSAFLUSH
the change occurs after all output written to the object referred by fd has been transmitted, and all input that has been received but not read will be discarded before the change is made.

Canonical and non-canonical mode

The setting of the ICANON canon flag in c_lflag determines whether the terminal is operating in canonical mode (ICANON set) or non-canonical mode (ICANON unset). By default, ICANON set.

In canonical mode:

*
Input is made available line by line. An input line is available when one of the line delimiters is typed (NL, EOL, EOL2; or EOF at the start of line). Except in the case of EOF, the line delimiter is included in the buffer returned by read(2).
*
Line editing is enabled (ERASE, KILL; and if the IEXTEN flag is set: WERASE, REPRINT, LNEXT). A read(2) returns at most one line of input; if the read(2) requested fewer bytes than are available in the current line of input, then only as many bytes as requested are read, and the remaining characters will be available for a future read(2).

In non-canonical mode input is available immediately (without the user having to type a line-delimiter character), and line editing is disabled. The settings of MIN (c_cc[VMIN]) and TIME (c_cc[VTIME]) determine the circumstances in which a read(2) completes; there are four distinct cases:

*
MIN == 0; TIME == 0: If data is available, read(2) returns immediately, with the lesser of the number of bytes available, or the number of bytes requested. If no data is available, read(2) returns 0.
*
MIN > 0; TIME == 0: read(2) blocks until the lesser of MIN bytes or the number of bytes requested are available, and returns the lesser of these two values.
*
MIN == 0; TIME > 0: TIME specifies the limit for a timer in tenths of a second. The timer is started when read(2) is called. read(2) returns either when at least one byte of data is available, or when the timer expires. If the timer expires without any input becoming available, read(2) returns 0.
*
MIN > 0; TIME > 0: TIME specifies the limit for a timer in tenths of a second. Once an initial byte of input becomes available, the timer is restarted after each further byte is received. read(2) returns either when the lesser of the number of bytes requested or MIN byte have been read, or when the inter-byte timeout expires. Because the timer is only started after the initial byte becomes available, at least one byte will be read.

Raw mode

cfmakeraw() sets the terminal to something like the "raw" mode of the old Version 7 terminal driver: input is available character by character, echoing is disabled, and all special processing of terminal input and output characters is disabled. The terminal attributes are set as follows:

    termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                    | INLCR | IGNCR | ICRNL | IXON);
    termios_p->c_oflag &= ~OPOST;
    termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    termios_p->c_cflag &= ~(CSIZE | PARENB);
    termios_p->c_cflag |= CS8;

Line control

tcsendbreak() transmits a continuous stream of zero-valued bits for a specific duration, if the terminal is using asynchronous serial data transmission. If duration is zero, it transmits zero-valued bits for at least 0.25 seconds, and not more that 0.5 seconds. If duration is not zero, it sends zero-valued bits for some implementation-defined length of time.

If the terminal is not using asynchronous serial data transmission, tcsendbreak() returns without taking any action.

tcdrain() waits until all output written to the object referred to by fd has been transmitted.

tcflush() discards data written to the object referred to by fd but not transmitted, or data received but not read, depending on the value of queue_selector:

TCIFLUSH
flushes data received but not read.
TCOFLUSH
flushes data written but not transmitted.
TCIOFLUSH
flushes both data received but not read, and data written but not transmitted.

tcflow() suspends transmission or reception of data on the object referred to by fd, depending on the value of action:

TCOOFF
suspends output.
TCOON
restarts suspended output.
TCIOFF
transmits a STOP character, which stops the terminal device from transmitting data to the system.
TCION
transmits a START character, which starts the terminal device transmitting data to the system.

The default on open of a terminal file is that neither its input nor its output is suspended.

Line speed

The baud rate functions are provided for getting and setting the values of the input and output baud rates in the termios structure. The new values do not take effect until tcsetattr() is successfully called.

Setting the speed to B0 instructs the modem to "hang up". The actual bit rate corresponding to B38400 may be altered with setserial(8).

The input and output baud rates are stored in the termios structure.

cfgetospeed() returns the output baud rate stored in the termios structure pointed to by termios_p.

cfsetospeed() sets the output baud rate stored in the termios structure pointed to by termios_p to speed, which must be one of these constants:

        B0
        B50
        B75
        B110
        B134
        B150
        B200
        B300
        B600
        B1200
        B1800
        B2400
        B4800
        B9600
        B19200
        B38400
        B57600
        B115200
        B230400
The zero baud rate, B0, is used to terminate the connection. If B0 is specified, the modem control lines shall no longer be asserted. Normally, this will disconnect the line. CBAUDEX is a mask for the speeds beyond those defined in POSIX.1 (57600 and above). Thus, B57600 & CBAUDEX is non-zero.

cfgetispeed() returns the input baud rate stored in the termios structure.

cfsetispeed() sets the input baud rate stored in the termios structure to speed, which must be specified as one of the Bnnn constants listed above for cfsetospeed(). If the input baud rate is set to zero, the input baud rate will be equal to the output baud rate.

cfsetspeed() is a 4.4BSD extension. It takes the same arguments as cfsetispeed(), and sets both input and output speed.

RETURN VALUE

cfgetispeed() returns the input baud rate stored in the termios structure.

cfgetospeed() returns the output baud rate stored in the termios structure.

All other functions return:

0
on success.
-1
on failure and set errno to indicate the error.

Note that tcsetattr() returns success if any of the requested changes could be successfully carried out. Therefore, when making multiple changes it may be necessary to follow this call with a further call to tcgetattr() to check that all changes have been performed successfully.

NOTES

Unix V7 and several later systems have a list of baud rates where after the fourteen values B0, ..., B9600 one finds the two constants EXTA, EXTB ("External A" and "External B"). Many systems extend the list with much higher baud rates.

The effect of a non-zero duration with tcsendbreak() varies. SunOS specifies a break of duration*N seconds, where N is at least 0.25, and not more than 0.5. Linux, AIX, DU, Tru64 send a break of duration milliseconds. FreeBSD and NetBSD and HP-UX and MacOS ignore the value of duration. Under Solaris and Unixware, tcsendbreak() with non-zero duration behaves like tcdrain().

SEE ALSO

stty(1), console_ioctl(4), tty_ioctl(4), feature_test_macros(7), setserial(8)


getpass(3)

GETPASS

Section: Linux Programmer's Manual (3)
Updated: 2000-12-05 Return to Main Contents

NAME

getpass - get a password

SYNOPSIS

#include <unistd.h>

char *getpass( const char * prompt );

DESCRIPTION

This function is obsolete. Do not use it.

The getpass() function opens /dev/tty (the controlling terminal of the process), outputs the string prompt, turns off echoing, reads one line (the "password"), restores the terminal state and closes /dev/tty again.

RETURN VALUE

The function getpass() returns a pointer to a static buffer containing the (first PASS_MAX bytes of) the password without the trailing newline, terminated by a null byte ('\0'). This buffer may be overwritten by a following call. On error, the terminal state is restored, errno is set appropriately, and NULL is returned.

ERRORS

The function may fail if
ENXIO
The process does not have a controlling terminal.

FILES

/dev/tty

CONFORMING TO

Present in SUSv2, but marked LEGACY. Removed in POSIX.1-2001.

NOTES

For libc4 and libc5, the prompt is not written to /dev/tty but to stderr. Moreover, if /dev/tty cannot be opened, the password is read from stdin. The static buffer has length 128 so that only the first 127 bytes of the password are returned. While reading the password, signal generation (SIGINT, SIGQUIT, SIGSTOP, SIGTSTOP) is disabled and the corresponding characters (usually control-C, control-\, control-Z and control-Y) are transmitted as part of the password. Since libc 5.4.19 also line editing is disabled, so that also backspace and the like will be seen as part of the password.

For glibc2, if /dev/tty cannot be opened, the prompt is written to stderr and the password is read from stdin. There is no limit on the length of the password. Line editing is not disabled.

According to the SUSv2, the value of PASS_MAX must be defined in <limits.h> in case it is smaller than 8, and can in any case be obtained using sysconf(_SC_PASS_MAX). However, POSIX.2 withdraws the constants PASS_MAX and _SC_PASS_MAX, and the function getpass(). Libc4 and libc5 have never supported PASS_MAX or _SC_PASS_MAX. Glibc2 accepts _SC_PASS_MAX and returns BUFSIZ (e.g., 8192).

BUGS

The calling process should zero the password as soon as possible to avoid leaving the cleartext password visible in the process's address space.

SEE ALSO

crypt(3)


getpw(3)

GETPW

Section: Linux Programmer's Manual (3)
Updated: 1996-05-27 Return to Main Contents

NAME

getpw - Re-construct password line entry

SYNOPSIS

#include <sys/types.h>
#include <pwd.h>

int getpw(uid_t uid, char *buf);

DESCRIPTION

The getpw() function re-constructs the password line entry for the given user ID uid in the buffer buf. The returned buffer contains a line of format

name:passwd:uid:gid:gecos:dir:shell

The passwd structure is defined in <pwd.h> as follows:

struct passwd {
    char   *pw_name;       /* user name */
    char   *pw_passwd;     /* user password */
    uid_t   pw_uid;        /* user ID */
    gid_t   pw_gid;        /* group ID */
    char   *pw_gecos;      /* real name */
    char   *pw_dir;        /* home directory */
    char   *pw_shell;      /* shell program */
};

RETURN VALUE

The getpw() function returns 0 on success, or -1 if an error occurs.

ERRORS

ENOMEM
Insufficient memory to allocate passwd structure.

FILES

/etc/passwd
password database file

CONFORMING TO

SVr2.

BUGS

The getpw() function is dangerous as it may overflow the provided buffer buf. It is obsoleted by getpwuid(3).

SEE ALSO

endpwent(3), fgetpwent(3), getpwent(3), getpwnam(3), getpwuid(3), putpwent(3), setpwent(3), passwd(5)


mbstowcs(3)

MBSTOWCS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

mbstowcs - convert a multibyte string to a wide-character string

SYNOPSIS

#include <stdlib.h>

size_t mbstowcs(wchar_t *dest, const char *src, size_t n);

DESCRIPTION

If dest is not a NULL pointer, the mbstowcs() function converts the multibyte string src to a wide-character string starting at dest. At most n wide characters are written to dest. The conversion starts in the initial state. The conversion can stop for three reasons:

1. An invalid multibyte sequence has been encountered. In this case (size_t)(-1) is returned.

2. n non-L'\0' wide characters have been stored at dest. In this case the number of wide characters written to dest is returned, but the shift state at this point is lost.

3. The multibyte string has been completely converted, including the terminating '\0'. In this case the number of wide characters written to dest, excluding the terminating L'\0' character, is returned.

The programmer must ensure that there is room for at least n wide characters at dest.

If dest is NULL, n is ignored, and the conversion proceeds as above, except that the converted wide characters are not written out to memory, and that no length limit exists.

In order to avoid the case 2 above, the programmer should make sure n is greater or equal to mbstowcs(NULL,src,0)+1.

RETURN VALUE

The mbstowcs() function returns the number of wide characters that make up the converted part of the wide-character string, not including the terminating null wide character. If an invalid multibyte sequence was encountered, (size_t)(-1) is returned.

CONFORMING TO

C99

NOTES

The behavior of mbstowcs() depends on the LC_CTYPE category of the current locale.

The function mbsrtowcs(3) provides a better interface to the same functionality.

SEE ALSO

mbsrtowcs(3)


res_query (3)

 Continue to this page.


res_querydomain (3)

 Continue to this page.


catopen(3)

CATOPEN

Section: Linux Programmer's Manual (3)
Updated: 2001-12-14 Return to Main Contents

NAME

catopen, catclose - open/close a message catalog

SYNOPSIS

#include <nl_types.h>

nl_catd catopen(const char *name, int flag);
int catclose(nl_catd catalog);

DESCRIPTION

The function catopen() opens a message catalog and returns a catalog descriptor. The descriptor remains valid until catclose() or execve(2). If a file descriptor is used to implement catalog descriptors then the FD_CLOEXEC flag will be set.

The argument name specifies the name of the message catalog to be opened. If name specifies and absolute path (i.e., contains a '/'), then name specifies a pathname for the message catalog. Otherwise, the environment variable NLSPATH is used with name substituted for %N (see locale(7)). It is unspecified whether NLSPATH will be used when the process has root privileges. If NLSPATH does not exist in the environment, or if a message catalog cannot be opened in any of the paths specified by it, then an implementation defined path is used. This latter default path may depend on the LC_MESSAGES locale setting when the flag argument is NL_CAT_LOCALE and on the LANG environment variable when the flag argument is 0. Changing the LC_MESSAGES part of the locale may invalidate open catalog descriptors.

The flag argument to catopen() is used to indicate the source for the language to use. If it is set to NL_CAT_LOCALE then it will use the current locale setting for LC_MESSAGES. Otherwise it will use the LANG environment variable.

The function catclose() closes the message catalog identified by catalog. It invalidates any subsequent references to the message catalog defined by catalog.

RETURN VALUE

The function catopen() returns a message catalog descriptor of type nl_catd on success. On failure, it returns (nl_catd) -1 and sets errno to indicate the error. The possible error values include all possible values for the open(2) call.

The function catclose() returns 0 on success, or -1 on failure.

ENVIRONMENT

LC_MESSAGES
May be the source of the LC_MESSAGES locale setting, and thus determine the language to use if flag is set to NL_CAT_LOCALE.
LANG
The language to use if flag is 0.

CONFORMING TO

POSIX.1-2001. It is unclear what the source was for the constants MCLoadBySet and MCLoadAll (see below).

NOTES

The above is the POSIX.1-2001 description. The glibc value for NL_CAT_LOCALE is 1. (Compare MCLoadAll below.) The default path varies, but usually looks at a number of places below /usr/share/locale.

Linux Notes

These functions are available for Linux since libc 4.4.4c. In the case of linux libc4 and libc5, the catalog descriptor nl_catd is a mmap(2)'ed area of memory and not a file descriptor. The flag argument to catopen() should be either MCLoadBySet (=0) or MCLoadAll (=1). The former value indicates that a set from the catalog is to be loaded when needed, whereas the latter causes the initial call to catopen() to load the entire catalog into memory. The default search path varies, but usually looks at a number of places below /etc/locale and /usr/lib/locale.

SEE ALSO

catgets(3), setlocale(3)


endutent (3)

 Continue to this page.


errno(3)

ERRNO

Section: Linux Programmer's Manual (3)
Updated: 2006-02-09 Return to Main Contents

NAME

errno - number of last error

SYNOPSIS

#include <errno.h>

DESCRIPTION

The <errno.h> header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. Its value is significant only when the call returned an error (usually -1), and a function that does succeed is allowed to change errno.

Sometimes, when -1 is also a valid successful return value one has to zero errno before the call in order to detect possible errors.

errno is defined by the ISO C standard to be a modifiable lvalue of type int, and must not be explicitly declared; errno may be a macro. errno is thread-local; setting it in one thread does not affect its value in any other thread.

Valid error numbers are all non-zero; errno is never set to zero by any library function. All the error names specified by POSIX.1 must have distinct values, with the exception of EAGAIN and EWOULDBLOCK, which may be the same.

Below is a list of the symbolic error names that are defined on Linux. Some of these are marked POSIX.1, indicating that the name is defined by POSIX.1-2001, or C99, indicating that the name is defined by C99.

E2BIG
Argument list too long (POSIX.1)
EACCES
Permission denied (POSIX.1)
EADDRINUSE
Address already in use (POSIX.1)
EADDRNOTAVAIL
Address not available (POSIX.1)
EAFNOSUPPORT
Address family not supported (POSIX.1)
EAGAIN
Resource temporarily unavailable (may be the same value as EWOULDBLOCK) (POSIX.1)
EALREADY
Connection already in progress (POSIX.1)
EBADE
Invalid exchange
EBADF
Bad file descriptor (POSIX.1)
EBADFD
File descriptor in bad state
EBADMSG
Bad message (POSIX.1)
EBADR
Invalid request descriptor
EBADRQC
Invalid request code
EBADSLT
Invalid slot
EBUSY
Device or resource busy (POSIX.1)
ECANCELED
Operation canceled (POSIX.1)
ECHILD
No child processes (POSIX.1)
ECHRNG
Channel number out of range
ECOMM
Communication error on send
ECONNABORTED
Connection aborted (POSIX.1)
ECONNREFUSED
Connection refused (POSIX.1)
ECONNRESET
Connection reset (POSIX.1)
EDEADLK
Resource deadlock avoided (POSIX.1)
EDEADLOCK
Synonym for EDEADLK
EDESTADDRREQ
Destination address required (POSIX.1)
EDOM
Mathematics argument out of domain of function (POSIX.1, C99)
EDQUOT
Disk quota exceeded (POSIX.1)
EEXIST
File exists (POSIX.1)
EFAULT
Bad address (POSIX.1)
EFBIG
File too large (POSIX.1)
EHOSTDOWN
Host is down
EHOSTUNREACH
Host is unreachable (POSIX.1)
EIDRM
Identifier removed (POSIX.1)
EILSEQ
Illegal byte sequence (POSIX.1, C99)
EINPROGRESS
Operation in progress (POSIX.1)
EINTR
Interrupted function call (POSIX.1)
EINVAL
Invalid argument (POSIX.1)
EIO
Input/output error (POSIX.1)
EISCONN
Socket is connected (POSIX.1)
EISDIR
Is a directory (POSIX.1)
EISNAM
Is a named type file
EKEYEXPIRED
Key has expired
EKEYREJECTED
Key was rejected by service
EKEYREVOKED
Key has been revoked
EL2HLT
Level 2 halted
EL2NSYNC
Level 2 not synchronized
EL3HLT
Level 3 halted
EL3RST
Level 3 halted
ELIBACC
Cannot access a needed shared library
ELIBBAD
Accessing a corrupted shared library
ELIBMAX
Attempting to link in too many shared libraries
ELIBSCN
lib section in a.out corrupted
ELIBEXEC
Cannot exec a shared library directly
ELOOP
Too many levels of symbolic links (POSIX.1)
EMEDIUMTYPE
Wrong medium type
EMFILE
Too many open files (POSIX.1)
EMLINK
Too many links (POSIX.1)
EMSGSIZE
Message too long (POSIX.1)
EMULTIHOP
Multihop attempted (POSIX.1)
ENAMETOOLONG
Filename too long (POSIX.1)
ENETDOWN
Network is down (POSIX.1)
ENETRESET
Connection aborted by network (POSIX.1)
ENETUNREACH
Network unreachable (POSIX.1)
ENFILE
Too many open files in system (POSIX.1)
ENOBUFS
No buffer space available (POSIX.1 (XSI STREAMS option))
ENODATA
No message is available on the STREAM head read queue (POSIX.1)
ENODEV
No such device (POSIX.1)
ENOENT
No such file or directory (POSIX.1)
ENOEXEC
Exec format error (POSIX.1)
ENOKEY
Required key not available
ENOLCK
No locks available (POSIX.1)
ENOLINK
Link has been severed (POSIX.1)
ENOMEDIUM
No medium found
ENOMEM
Not enough space (POSIX.1)
ENOMSG
No message of the desired type (POSIX.1)
ENONET
Machine is not on the network
ENOPKG
Package not installed
ENOPROTOOPT
Protocol not available (POSIX.1)
ENOSPC
No space left on device (POSIX.1)
ENOSR
No STREAM resources (POSIX.1 (XSI STREAMS option))
ENOSTR
Not a STREAM (POSIX.1 (XSI STREAMS option))
ENOSYS
Function not implemented (POSIX.1)
ENOTBLK
Block device required
ENOTCONN
The socket is not connected (POSIX.1)
ENOTDIR
Not a directory (POSIX.1)
ENOTEMPTY
Directory not empty (POSIX.1)
ENOTSOCK
Not a socket (POSIX.1)
ENOTSUP
Operation not supported (POSIX.1)
ENOTTY
Inappropriate I/O control operation (POSIX.1)
ENOTUNIQ
Name not unique on network
ENXIO
No such device or address (POSIX.1)
EOPNOTSUPP
Operation not supported on socket (POSIX.1)

(ENOTSUP and EOPNOTSUPP have the same value on Linux, but according to POSIX.1 these error values should be distinct.)

EOVERFLOW
Value too large to be stored in data type (POSIX.1)
EPERM
Operation not permitted (POSIX.1)
EPFNOSUPPORT
Protocol family not supported
EPIPE
Broken pipe (POSIX.1)
EPROTO
Protocol error (POSIX.1)
EPROTONOSUPPORT
Protocol not supported (POSIX.1)
EPROTOTYPE
Protocol wrong type for socket (POSIX.1)
ERANGE
Result too large (POSIX.1, C99)
EREMCHG
Remote address changed
EREMOTE
Object is remote
EREMOTEIO
Remote I/O error
ERESTART
Interrupted system call should be restarted
EROFS
Read-only file system (POSIX.1)
ESHUTDOWN
Cannot send after transport endpoint shutdown
ESPIPE
Invalid seek (POSIX.1)
ESOCKTNOSUPPORT
Socket type not supported
ESRCH
No such process (POSIX.1)
ESTALE
Stale file handle (POSIX.1)

This error can occur for NFS and for other file systems

ESTRPIPE
Streams pipe error
ETIME
Timer expired (POSIX.1 (XSI STREAMS option))

(POSIX.1 says "STREAM ioctl(2) timeout")

ETIMEDOUT
Connection timed out (POSIX.1)
ETXTBSY
Text file busy (POSIX.1)
EUCLEAN
Structure needs cleaning
EUNATCH
Protocol driver not attached
EUSERS
Too many users
EWOULDBLOCK
Operation would block (may be same value as EAGAIN) (POSIX.1)
EXDEV
Improper link (POSIX.1)
EXFULL
Exchange full

NOTES

A common mistake is to do

if (somecall() == -1) {
    printf("somecall() failed\n");
    if (errno == ...) { ... }
}
where errno no longer needs to have the value it had upon return from somecall() (i.e., it may have been changed by the printf(3)). If the value of errno should be preserved across a library call, it must be saved:

if (somecall() == -1) {
    int errsv = errno;
    printf("somecall() failed\n");
    if (errsv == ...) { ... }
}

It was common in traditional C to declare errno manually (i.e., extern int errno) instead of including <errno.h>. Do not do this. It will not work with modern versions of the C library. However, on (very) old Unix systems, there may be no <errno.h> and the declaration is needed.

SEE ALSO

err(3), error(3), perror(3), strerror(3)


exec(3)

EXEC

Section: Linux Programmer's Manual (3)
Updated: 1993-11-29 Return to Main Contents

NAME

execl, execlp, execle, execv, execvp - execute a file

SYNOPSIS

#include <unistd.h>

extern char **environ;

int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,
..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);

DESCRIPTION

The exec() family of functions replaces the current process image with a new process image. The functions described in this manual page are front-ends for the function execve(2). (See the manual page for execve(2) for detailed information about the replacement of the current process.)

The initial argument for these functions is the pathname of a file which is to be executed.

The const char *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.

The execv() and execvp() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.

The execle() function also specifies the environment of the executed process by following the NULL pointer that terminates the list of arguments in the parameter list or the pointer to the argv array with an additional parameter. This additional parameter is an array of pointers to null-terminated strings and must be terminated by a NULL pointer. The other functions take the environment for the new process image from the external variable environ in the current process.

Special semantics for execlp() and execvp()

The functions execlp() and execvp() will duplicate the actions of the shell in searching for an executable file if the specified filename does not contain a slash (/) character. The search path is the path specified in the environment by the PATH variable. If this variable isn't specified, the default path ``:/bin:/usr/bin'' is used. In addition, certain errors are treated specially.

If permission is denied for a file (the attempted execve(2) returned EACCES), these functions will continue searching the rest of the search path. If no other file is found, however, they will return with the global variable errno set to EACCES.

If the header of a file isn't recognized (the attempted execve(2) returned ENOEXEC), these functions will execute the shell (/bin/sh) with the path of the file as its first argument. (If this attempt fails, no further searching is done.)

RETURN VALUE

If any of the exec() functions returns, an error will have occurred. The return value is -1, and the global variable errno will be set to indicate the error.

ERRORS

All of these functions may fail and set errno for any of the errors specified for the library function execve(2).

CONFORMING TO

POSIX.1-2001.

NOTES

On some other systems the default path (used when the environment does not contain the variable PATH) has the current working directory listed after /bin and /usr/bin, as an anti-Trojan-horse measure. Linux uses here the traditional "current directory first" default path.

The behavior of execlp() and execvp() when errors occur while attempting to execute the file is historic practice, but has not traditionally been documented and is not specified by the POSIX standard. BSD (and possibly other systems) do an automatic sleep and retry if ETXTBSY is encountered. Linux treats it as a hard error and returns immediately.

Traditionally, the functions execlp() and execvp() ignored all errors except for the ones described above and ENOMEM and E2BIG, upon which they returned. They now return if any error other than the ones described above occurs.

SEE ALSO

sh(1), execve(2), fork(2), ptrace(2), fexecve(3), environ(7)


execl (3)

 Continue to this page.


getopt_long (3)

 Continue to this page.


getopt_long_only (3)

 Continue to this page.


getprotobyname (3)

 Continue to this page.


getprotobynumber (3)

 Continue to this page.


getprotoent(3)

GETPROTOENT

Section: Linux Programmer's Manual (3)
Updated: 1993-04-24 Return to Main Contents

NAME

getprotoent, getprotobyname, getprotobynumber, setprotoent, endprotoent - get protocol entry

SYNOPSIS

#include <netdb.h>

struct protoent *getprotoent(void);

struct protoent *getprotobyname(const char *name);

struct protoent *getprotobynumber(int proto);

void setprotoent(int stayopen);

void endprotoent(void);

DESCRIPTION

The getprotoent() function reads the next line from the file /etc/protocols and returns a structure protoent containing the broken out fields from the line. The /etc/protocols file is opened if necessary.

The getprotobyname() function returns a protoent structure for the line from /etc/protocols that matches the protocol name name.

The getprotobynumber() function returns a protoent structure for the line that matches the protocol number number.

The setprotoent() function opens and rewinds the /etc/protocols file. If stayopen is true (1), then the file will not be closed between calls to getprotobyname() or getprotobynumber().

The endprotoent() function closes /etc/protocols.

The protoent structure is defined in <netdb.h> as follows:

struct protoent {
    char  *p_name;       /* official protocol name */
    char **p_aliases;    /* alias list */
    int    p_proto;      /* protocol number */
}

The members of the protoent structure are:

p_name
The official name of the protocol.
p_aliases
A zero terminated list of alternative names for the protocol.
p_proto
The protocol number.

RETURN VALUE

The getprotoent(), getprotobyname() and getprotobynumber() functions return the protoent structure, or a NULL pointer if an error occurs or the end of the file is reached.

FILES

/etc/protocols
protocol database file

CONFORMING TO

4.3BSD, POSIX.1-2001.

SEE ALSO

getnetent(3), getservent(3), protocols(5)


getpwuid (3)

 Continue to this page.


gets(3)

GETS

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

fgetc, fgets, getc, getchar, gets, ungetc - input of characters and strings

SYNOPSIS

#include <stdio.h>

int fgetc(FILE *stream);

char *fgets(char *s, int size, FILE *stream);

int getc(FILE *stream);

int getchar(void);

char *gets(char *s);

int ungetc(int c, FILE *stream);

DESCRIPTION

fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.

getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.

getchar() is equivalent to getc(stdin).

gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with '\0'. No check for buffer overrun is performed (see BUGS below).

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.

Calls to the functions described here can be mixed with each other and with calls to other input functions from the stdio library for the same input stream.

For non-locking counterparts, see unlocked_stdio(3).

RETURN VALUE

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

gets() and fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read.

ungetc() returns c on success, or EOF on error.

CONFORMING TO

C89, C99. LSB deprecates gets().

BUGS

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

It is not advisable to mix calls to input functions from the stdio library with low-level calls to read() for the file descriptor associated with the input stream; the results will be undefined and very probably not what you want.

SEE ALSO

read(2), write(2), ferror(3), fgetwc(3), fgetws(3), fopen(3), fread(3), fseek(3), getline(3), getwchar(3), puts(3), scanf(3), ungetwc(3), unlocked_stdio(3)


getutent(3)

GETUTENT

Section: Linux Programmer's Manual (3)
Updated: 1996-07-25 Return to Main Contents

NAME

getutent, getutid, getutline, pututline, setutent, endutent, utmpname - access utmp file entries

SYNOPSIS

#include <utmp.h>

struct utmp *getutent(void);
struct utmp *getutid(struct utmp *ut);
struct utmp *getutline(struct utmp *ut);

struct utmp *pututline(struct utmp *ut);

void setutent(void);
void endutent(void);

void utmpname(const char *file);

DESCRIPTION

utmpname() sets the name of the utmp-format file for the other utmp functions to access. If utmpname() is not used to set the filename before the other functions are used, they assume _PATH_UTMP, as defined in <paths.h>.

setutent() rewinds the file pointer to the beginning of the utmp file. It is generally a Good Idea to call it before any of the other functions.

endutent() closes the utmp file. It should be called when the user code is done accessing the file with the other functions.

getutent() reads a line from the current file position in the utmp file. It returns a pointer to a structure containing the fields of the line.

getutid() searches forward from the current file position in the utmp file based upon ut. If ut->ut_type is one of RUN_LVL, BOOT_TIME, NEW_TIME, or OLD_TIME, getutid() will find the first entry whose ut_type field matches ut->ut_type. If ut->ut_type is one of INIT_PROCESS, LOGIN_PROCESS, USER_PROCESS, or DEAD_PROCESS, getutid() will find the first entry whose ut_id field matches ut->ut_id.

getutline() searches forward from the current file position in the utmp file. It scans entries whose ut_type is USER_PROCESS or LOGIN_PROCESS and returns the first one whose ut_line field matches ut->ut_line.

pututline() writes the utmp structure ut into the utmp file. It uses getutid() to search for the proper place in the file to insert the new entry. If it cannot find an appropriate slot for ut, pututline() will append the new entry to the end of the file.

RETURN VALUE

getutent(), getutid(), getutline() and pututline() return a pointer to a struct utmp on success, and NULL on failure. This struct utmp is allocated in static storage, and may be overwritten by subsequent calls.

FILES

/var/run/utmp  database of currently logged-in users

/var/log/wtmp  database of past user logins

CONFORMING TO

XPG2, SVr4.

In XPG2 and SVID 2 the function pututline() is documented to return void, and that is what it does on many systems (AIX, HP-UX, Linux libc5). HP-UX introduces a new function _pututline() with the prototype given above for pututline() (also found in Linux libc5).

All these functions are obsolete now on non-Linux systems. POSIX.1-2001, following SUSv1, does not have any of these functions, but instead uses

#include <utmpx.h>

struct utmpx *getutxent(void);
struct utmpx *getutxid(const struct utmpx *);
struct utmpx *getutxline(const struct utmpx *);
struct utmpx *pututxline(const struct utmpx *);
void setutxent(void);
void endutxent(void);

The utmpx structure is a superset of the utmp structure, with additional fields, and larger versions of the existing fields. The corresponding files are often /var/*/utmpx and /var/*/wtmpx.

Linux glibc on the other hand does not use utmpx since its utmp structure is already large enough. The functions getutxent etc. are aliases for getutent etc.

NOTES

Glibc Notes

The above functions are not thread-safe. Glibc adds reentrant versions

#define _GNU_SOURCE    /* or _SVID_SOURCE or _BSD_SOURCE */
#include <utmp.h>

int getutent_r(struct utmp *ubuf, struct utmp **ubufp);

int getutid_r(struct utmp *ut,
              struct utmp *ubuf, struct utmp **ubufp);

int getutline_r(struct utmp *ut,
                struct utmp *ubuf, struct utmp **ubufp);

These functions are GNU extensions, analogs of the functions of the same name without the _r suffix. The ubuf parameter gives these functions a place to store their result. On success they return 0, and a pointer to the result is written in *ubufp. On error these functions return -1.

EXAMPLE

The following example adds and removes a utmp record, assuming it is run from within a pseudo terminal. For usage in a real application, you should check the return values of getpwuid(3) and ttyname(3).

#include <string.h>
#include <stdlib.h>
#include <pwd.h>
#include <unistd.h>
#include <utmp.h>

int
main(int argc, char *argv[])
{
    struct utmp entry;

    system("echo before adding entry:;who");

    entry.ut_type = USER_PROCESS;
    entry.ut_pid = getpid();
    strcpy(entry.ut_line, ttyname(STDIN_FILENO) + strlen("/dev/"));
    /* only correct for ptys named /dev/tty[pqr][0-9a-z] */
    strcpy(entry.ut_id, ttyname(STDIN_FILENO) + strlen("/dev/tty"));
    time(&entry.ut_time);
    strcpy(entry.ut_user, getpwuid(getuid())->pw_name);
    memset(entry.ut_host, 0, UT_HOSTSIZE);
    entry.ut_addr = 0;
    setutent();
    pututline(&entry);

    system("echo after adding entry:;who");

    entry.ut_type = DEAD_PROCESS;
    memset(entry.ut_line, 0, UT_LINESIZE);
    entry.ut_time = 0;
    memset(entry.ut_user, 0, UT_NAMESIZE);
    setutent();
    pututline(&entry);

    system("echo after removing entry:;who");

    endutent();
    exit(EXIT_SUCCESS);
}

SEE ALSO

utmp(5), feature_test_macros(7)


getutline (3)

 Continue to this page.


getwd (3)

 Continue to this page.


globfree (3)

 Continue to this page.


hash(3)

HASH

Section: Linux Programmer's Manual (3)
Updated: 1994-08-18 Return to Main Contents

NAME

hash - hash database access method

SYNOPSIS

#include <sys/types.h>
#include <db.h>

DESCRIPTION

The routine dbopen is the library interface to database files. One of the supported file formats is hash files. The general description of the database access methods is in dbopen(3), this manual page describes only the hash specific information.

The hash data structure is an extensible, dynamic hashing scheme.

The access method specific data structure provided to dbopen is defined in the <db.h> include file as follows:

typedef struct {

u_int bsize;
u_int ffactor;
u_int nelem;
u_int cachesize;
u_int32_t (*hash)(const void *, size_t);
int lorder;
} HASHINFO;

The elements of this structure are as follows:

bsize
Bsize defines the hash table bucket size, and is, by default, 256 bytes. It may be preferable to increase the page size for disk-resident tables and tables with large data items.
ffactor
Ffactor indicates a desired density within the hash table. It is an approximation of the number of keys allowed to accumulate in any one bucket, determining when the hash table grows or shrinks. The default value is 8.
nelem
Nelem is an estimate of the final size of the hash table. If not set or set too low, hash tables will expand gracefully as keys are entered, although a slight performance degradation may be noticed. The default value is 1.
cachesize
A suggested maximum size, in bytes, of the memory cache. This value is only advisory, and the access method will allocate more memory rather than fail.
hash
Hash is a user defined hash function. Since no hash function performs equally well on all possible data, the user may find that the built-in hash function does poorly on a particular data set. User specified hash functions must take two arguments (a pointer to a byte string and a length) and return a 32-bit quantity to be used as the hash value.
lorder
The byte order for integers in the stored database metadata. The number should represent the order as an integer; for example, big endian order would be the number 4,321. If lorder is 0 (no order is specified) the current host order is used. If the file already exists, the specified value is ignored and the value specified when the tree was created is used.

If the file already exists (and the O_TRUNC flag is not specified), the values specified for the parameters bsize, ffactor, lorder and nelem are ignored and the values specified when the tree was created are used.

If a hash function is specified, hash_open will attempt to determine if the hash function specified is the same as the one with which the database was created, and will fail if it is not.

Backward compatible interfaces to the routines described in dbm(3), and ndbm(3) are provided, however these interfaces are not compatible with previous file formats.

ERRORS

The hash access method routines may fail and set errno for any of the errors specified for the library routine dbopen(3).

BUGS

Only big and little endian byte order is supported.

SEE ALSO

btree(3), dbopen(3), mpool(3), recno(3)

Dynamic Hash Tables, Per-Ake Larson, Communications of the ACM, April 1988.

A New Hash Package for UNIX, Margo Seltzer, USENIX Proceedings, Winter 1991.


inet_addr (3)

 Continue to this page.


inet_netof (3)

 Continue to this page.


inet_network (3)

 Continue to this page.


inet_ntoa (3)

 Continue to this page.


infnan(3)

INFNAN

Section: Linux Programmer's Manual (3)
Updated: 1993-06-02 Return to Main Contents

NAME

infnan - deal with infinite or not-a-number (NaN) result

SYNOPSIS

#include <math.h>

double infnan(int error);

Link with -lm.

DESCRIPTION

The infnan() function returns a suitable value for infinity and "not-a-number" (NaN) results. The value of error can be ERANGE to represent infinity or anything else to represent NaN. errno is also set.

RETURN VALUE

If error is ERANGE (Infinity), HUGE_VAL is returned.

If error is -ERANGE (-Infinity), -HUGE_VAL is returned.

If error is anything else, NAN is returned.

ERRORS

EDOM
The value of error is "not-a-number" (NaN).
ERANGE
The value of error is positive or negative infinity.

CONFORMING TO

4.3BSD

NOTES

This obsolete function was provided in libc4 and libc5, but is not available in glibc2.


initgroups(3)

INITGROUPS

Section: Linux Programmer's Manual (3)
Updated: 2004-10-10 Return to Main Contents

NAME

initgroups - initialize the supplementary group access list

SYNOPSIS

#include <sys/types.h>
#include <grp.h>

int initgroups(const char *user, gid_t group);

DESCRIPTION

The initgroups() function initializes the group access list by reading the group database /etc/group and using all groups of which user is a member. The additional group group is also added to the list.

The user argument must be non-NULL.

RETURN VALUE

The initgroups() function returns 0 on success. On error, -1 is returned, and errno is set appropriately.

ERRORS

ENOMEM
Insufficient memory to allocate group information structure.
EPERM
The calling process has insufficient privilege. See the underlying system call setgroups(2).

FILES

/etc/group              group database file

CONFORMING TO

SVr4, 4.3BSD

NOTES

The prototype for initgroups() is only available if _BSD_SOURCE is defined.

SEE ALSO

getgroups(2), setgroups(2), credentials(7)


initstate (3)

 Continue to this page.


insque(3)

INSQUE

Section: Linux Programmer's Manual (3)
Updated: 2003-08-11 Return to Main Contents

NAME

insque, remque - insert/remove an item from a queue

SYNOPSIS

#include <search.h>

void insque(void *elem, void *prev);
void remque(void *elem);

DESCRIPTION

insque() and remque() are functions for manipulating doubly-linked lists. Each element in the list is a structure of which the first two structure elements are a forward and a backward pointer.

insque() inserts the element pointed to by elem immediately after the element pointed to by prev, which must not be NULL.

remque() removes the element pointed to by elem from the doubly-linked list.

CONFORMING TO

POSIX.1-2001

NOTES

Traditionally (e.g., SunOS, Linux libc 4,5) the parameters of these functions were of type struct qelem *, where the struct is defined as

struct qelem {
    struct    qelem *q_forw;
    struct    qelem *q_back;
    char      q_data[1];
};

This is still what you will get if _GNU_SOURCE is defined before including <search.h>.

The location of the prototypes for these functions differs among several versions of UNIX. The above is the POSIX version. Some systems place them in <string.h>. Linux libc4,5 placed them in <stdlib.h>.


intro(3)

INTRO

Section: Linux Programmer's Manual (3)
Updated: 1995-12-13 Return to Main Contents

NAME

intro - Introduction to library functions

DESCRIPTION

This chapter describes all library functions excluding the library functions described in chapter 2, which implement system calls.

Authors and Copyright Terms

Look at the header of the manual page for the author(s) and copyright conditions. Note that these can be different from page to page!

SEE ALSO

intro(2), errno(3), feature_test_macros(7), standards(7)


openlog (3)

 Continue to this page.


pathconf (3)

 Continue to this page.


setmntent (3)

 Continue to this page.


setstate (3)

 Continue to this page.


setusershell (3)

 Continue to this page.


setutent (3)

 Continue to this page.


srandom (3)

 Continue to this page.


endmntent (3)

 Continue to this page.


erf(3)

ERF

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

erf, erff, erfl, erfc, erfcf, erfcl - error function and complementary error function

SYNOPSIS

#include <math.h>

double erf(double x);

float erff(float x);

long double erfl(long double x);

double erfc(double x);

float erfcf(float x);

long double erfcl(long double x);
Link with -lm.

DESCRIPTION

The erf() function returns the error function of x; defined as
erf(x) = 2/sqrt(pi)* integral from 0 to x of exp(-t*t) dt

The erfc() function returns the complementary error function of x, that is 1.0 - erf(x).

CONFORMING TO

SVr4, 4.3BSD, C99. The float and long double variants are requirements of C99.

SEE ALSO

cerf(3), exp(3)


res_send (3)

 Continue to this page.


resolver(3)

RESOLVER

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

res_init, res_query, res_search, res_querydomain, res_mkquery, res_send, dn_comp, dn_expand - resolver routines

SYNOPSIS

#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
extern struct state _res;

int res_init(void);

int res_query(const char *dname, int class, int type,

unsigned char *answer, int anslen);

int res_search(const char *dname, int class, int type,

unsigned char *answer, int anslen);

int res_querydomain(const char *name, const char *domain,

int class, int type, unsigned char *answer,
int anslen);

int res_mkquery(int op, const char *dname, int class,

int type, char *data, int datalen, struct rrec *newrr,
char *buf, int buflen);

int res_send(const char *msg, int msglen, char *answer,

int anslen);

int dn_comp(unsigned char *exp_dn, unsigned char *comp_dn,

int length, unsigned char **dnptrs, unsigned char *exp_dn,
unsigned char **lastdnptr);

int dn_expand(unsigned char *msg, unsigned char *eomorig,

unsigned char *comp_dn, unsigned char *exp_dn,
int length);

Link with -lresolv.

DESCRIPTION

These functions make queries to and interpret the responses from Internet domain name servers.

The res_init() function reads the configuration files (see resolv.conf(5)) to get the default domain name, search order and name server address(es). If no server is given, the local host is tried. If no domain is given, that associated with the local host is used. It can be overridden with the environment variable LOCALDOMAIN. res_init() is normally executed by the first call to one of the other functions.

The res_query() function queries the name server for the fully-qualified domain name name of specified type and class. The reply is left in the buffer answer of length anslen supplied by the caller.

The res_search() function makes a query and waits for the response like res_query(), but in addition implements the default and search rules controlled by RES_DEFNAMES and RES_DNSRCH (see description of _res options below).

The res_querydomain() function makes a query using res_query() on the concatenation of name and domain.

The following functions are lower-level routines used by res_query().

The res_mkquery() function constructs a query message in buf of length buflen for the domain name dname. The query type op is usually QUERY, but can be any of the types defined in <arpa/nameser.h>. newrr is currently unused.

The res_send() function sends a pre-formatted query given in msg of length msglen and returns the answer in answer which is of length anslen. It will call res_init(), if it has not already been called.

The dn_comp() function compresses the domain name exp_dn and stores it in the buffer comp_dn of length length. The compression uses an array of pointers dnptrs to previously compressed names in the current message. The first pointer points to the beginning of the message and the list ends with NULL. The limit of the array is specified by lastdnptr. If dnptr is NULL, domain names are not compressed. If lastdnptr is NULL, the list of labels is not updated.

The dn_expand() function expands the compressed domain name comp_dn to a full domain name, which is placed in the buffer exp_dn of size length. The compressed name is contained in a query or reply message, and msg points to the beginning of the message.

The resolver routines use global configuration and state information contained in the structure _res, which is defined in <resolv.h>. The only field that is normally manipulated by the user is _res.options. This field can contain the bitwise ``or'' of the following options:

RES_INIT
True if res_init() has been called.
RES_DEBUG
Print debugging messages.
RES_AAONLY
Accept authoritative answers only. res_send() continues until it fins an authoritative answer or returns an error. [Not currently implemented].
RES_USEVC
Use TCP connections for queries rather than UDP datagrams.
RES_PRIMARY
Query primary domain name server only.
RES_IGNTC
Ignore truncation errors. Don't retry with TCP. [Not currently implemented].
RES_RECURSE
Set the recursion desired bit in queries. Recursion is carried out by the domain name server, not by res_send(). [Enabled by default].
RES_DEFNAMES
If set, res_search() will append the default domain name to single component names, ie. those that do not contain a dot. [Enabled by default].
RES_STAYOPEN
Used with RES_USEVC to keep the TCP connection open between queries.
RES_DNSRCH
If set, res_search() will search for host names in the current domain and in parent domains. This option is used by gethostbyname(3). [Enabled by default].

RETURN VALUE

The res_init() function returns 0 on success, or -1 if an error occurs.

The res_query(), res_search(), res_querydomain(), res_mkquery() and res_send() functions return the length of the response, or -1 if an error occurs.

The dn_comp() and dn_expand() functions return the length of the compressed name, or -1 if an error occurs.

FILES

/etc/resolv.conf          resolver configuration file
/etc/host.conf            resolver configuration file

CONFORMING TO

4.3BSD

SEE ALSO

gethostbyname(3), resolver(5), hostname(7), resolv.conf(5), named(8)


rewind (3)

 Continue to this page.


rewinddir(3)

REWINDDIR

Section: Linux Programmer's Manual (3)
Updated: 1995-06-11 Return to Main Contents

NAME

rewinddir - reset directory stream

SYNOPSIS

#include <sys/types.h>

#include <dirent.h>

void rewinddir(DIR *dir);

DESCRIPTION

The rewinddir() function resets the position of the directory stream dir to the beginning of the directory.

RETURN VALUE

The rewinddir() function returns no value.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

SEE ALSO

closedir(3), opendir(3), readdir(3), scandir(3), seekdir(3), telldir(3)


rindex (3)

 Continue to this page.


rint(3)

RINT

Section: Linux Programmer's Manual (3)
Updated: 2001-05-31 Return to Main Contents

NAME

nearbyint, nearbyintf, nearbyintl, rint, rintf, rintl - round to nearest integer

SYNOPSIS

#include <math.h>

double nearbyint(double x);

float nearbyintf(float x);

long double nearbyintl(long double x);

double rint(double x);

float rintf(float x);

long double rintl(long double x);

Link with -lm.

DESCRIPTION

The nearbyint() functions round their argument to an integer value in floating point format, using the current rounding direction and without raising the inexact exception.

The rint() functions do the same, but will raise the inexact exception when the result differs in value from the argument.

RETURN VALUE

The rounded integer value. If x is integral or infinite, x itself is returned.

ERRORS

No errors other than EDOM and ERANGE can occur. If x is NaN, then NaN is returned and errno may be set to EDOM.

CONFORMING TO

C99.

NOTES

SUSv2 and POSIX.1-2001 contain text about overflow (which might set errno to ERANGE, or raise an exception). In practice, the result cannot overflow on any current machine, so this error-handling stuff is just nonsense. (More precisely, overflow can happen only when the maximum value of the exponent is smaller than the number of mantissa bits. For the IEEE-754 standard 32-bit and 64-bit floating point numbers the maximum value of the exponent is 128 (resp. 1024), and the number of mantissa bits is 24 (resp. 53).)

SEE ALSO

ceil(3), floor(3), lrint(3), nearbyint(3), round(3), trunc(3)


rresvport (3)

 Continue to this page.


acosh(3)

ACOSH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-25 Return to Main Contents

NAME

acosh, acoshf, acoshl - inverse hyperbolic cosine function

SYNOPSIS

#include <math.h>

double acosh(double x);

float acoshf(float x);

long double acoshl(long double x);
Link with -lm.

DESCRIPTION

The acosh() function calculates the inverse hyperbolic cosine of x; that is the value whose hyperbolic cosine is x. If x is less than 1.0, acosh() returns not-a-number (NaN) and errno is set.

ERRORS

EDOM
x is out of range.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

asinh(3), atanh(3), cacosh(3), cosh(3), sinh(3), tanh(3)


assert(3)

ASSERT

Section: Linux Programmer's Manual (3)
Updated: 2002-08-25 Return to Main Contents

NAME

assert - abort the program if assertion is false

SYNOPSIS

#include <assert.h>

void assert(scalar expression);

DESCRIPTION

If the macro NDEBUG was defined at the moment <assert.h> was last included, the macro assert() generates no code, and hence does nothing at all. Otherwise, the macro assert() prints an error message to standard error and terminates the program by calling abort(3) if expression is false (i.e., compares equal to zero).

The purpose of this macro is to help the programmer find bugs in his program. The message "assertion failed in file foo.c, function do_bar(), line 1287" is of no help at all to a user.

RETURN VALUE

No value is returned.

CONFORMING TO

POSIX.1-2001, C89, C99. In C89, expression is required to be of type int and undefined behavior results if it is not, but in C99 it may have any scalar type.

BUGS

assert() is implemented as a macro; if the expression tested has side-effects, program behavior will be different depending on whether NDEBUG is defined. This may create Heisenbugs which go away when debugging is turned on.

SEE ALSO

abort(3), assert_perror(3), exit(3)


atan2(3)

ATAN2

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

atan2, atan2f, atan2l - arc tangent function of two variables

SYNOPSIS

#include <math.h>

double atan2(double y, double x);

float atan2f(float y, float x);

long double atan2l(long double y, long double x);
Link with -lm.

DESCRIPTION

The atan2() function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.

RETURN VALUE

The atan2() function returns the result in radians, which is between -PI and PI (inclusive).

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acos(3), asin(3), atan(3), cos(3), sin(3), tan(3)


atanh(3)

ATANH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

atanh, atanhf, atanhl - inverse hyperbolic tangent function

SYNOPSIS

#include <math.h>

double atanh(double x);

float atanhf(float x);

long double atanhl(long double x);
Link with -lm.

DESCRIPTION

The atanh() function calculates the inverse hyperbolic tangent of x; that is the value whose hyperbolic tangent is x. If the absolute value of x is greater than 1.0, atanh() returns not-a-number (NaN) and errno is set.

ERRORS

EDOM
x is out of range.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acosh(3), asinh(3), catanh(3), cosh(3), sinh(3), tanh(3)


atoi(3)

ATOI

Section: Linux Programmer's Manual (3)
Updated: 2000-12-17 Return to Main Contents

NAME

atoi, atol, atoll, atoq - convert a string to an integer

SYNOPSIS

#include <stdlib.h>

int atoi(const char *nptr);

long atol(const char *nptr);

long long atoll(const char *nptr);

long long atoq(const char *nptr);

DESCRIPTION

The atoi() function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as

strtol(nptr, (char **) NULL, 10);

except that atoi() does not detect errors.

The atol() and atoll() functions behave the same as atoi(), except that they convert the initial portion of the string to their return type of long or long long. atoq() is an obsolete name for atoll().

RETURN VALUE

The converted value.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C99. C89 and POSIX.1-1996 include the functions atoi() and atol() only. atoq(3) is a GNU extension.

NOTES

The non-standard atoq() function is not present in libc 4.6.27 or glibc 2, but is present in libc5 and libc 4.7 (though only as an inline function in <stdlib.h> until libc 5.4.44). The atoll() function is present in glibc 2 since version 2.0.2, but not in libc4 or libc5.

SEE ALSO

atof(3), strtod(3), strtol(3), strtoul(3)


atol (3)

 Continue to this page.


closelog (3)

 Continue to this page.


cmsg(3)

CMSG

Section: Linux Programmer's Manual (3)
Updated: 1998-10-02 Return to Main Contents

NAME

CMSG_ALIGN, CMSG_SPACE, CMSG_NXTHDR, CMSG_FIRSTHDR - Access ancillary data

SYNOPSIS

#include <sys/socket.h>

struct cmsghdr *CMSG_FIRSTHDR(struct msghdr *msgh);
struct cmsghdr *CMSG_NXTHDR(struct msghdr *msgh, struct cmsghdr *cmsg);
size_t CMSG_ALIGN(size_t length);
size_t CMSG_SPACE(size_t length);
size_t CMSG_LEN(size_t length);
unsigned char *CMSG_DATA(struct cmsghdr *cmsg);

struct cmsghdr {
    socklen_t cmsg_len;    /* data byte count, including header */
    int       cmsg_level;  /* originating protocol */
    int       cmsg_type;   /* protocol-specific type */
    /* followed by unsigned char cmsg_data[]; */
};

DESCRIPTION

These macros are used to create and access control messages (also called ancillary data) that are not a part of the socket payload. This control information may include the interface the packet was received on, various rarely used header fields, an extended error description, a set of file descriptors or Unix credentials. For instance, control messages can be used to send additional header fields such as IP options. Ancillary data is sent by calling sendmsg(2) and received by calling recvmsg(2). See their manual pages for more information.

Ancillary data is a sequence of struct cmsghdr structures with appended data. This sequence should only be accessed using the macros described in this manual page and never directly. See the specific protocol man pages for the available control message types. The maximum ancillary buffer size allowed per socket can be set using the net.core.optmem_max sysctl; see socket(7).

CMSG_FIRSTHDR() returns a pointer to the first cmsghdr in the ancillary data buffer associated with the passed msghdr.

CMSG_NXTHDR() returns the next valid cmsghdr after the passed cmsghdr. It returns NULL when there isn't enough space left in the buffer.

CMSG_ALIGN(), given a length, returns it including the required alignment. This is a constant expression.

CMSG_SPACE() returns the number of bytes an ancillary element with payload of the passed data length occupies. This is a constant expression.

CMSG_DATA returns a pointer to the data portion of a cmsghdr.

CMSG_LEN returns the value to store in the cmsg_len member of the cmsghdr structure, taking into account any necessary alignment. It takes the data length as an argument. This is a constant expression.

To create ancillary data, first initialize the msg_controllen member of the msghdr with the length of the control message buffer. Use CMSG_FIRSTHDR() on the msghdr to get the first control message and CMSG_NEXTHDR to get all subsequent ones. In each control message, initialize cmsg_len (with CMSG_LEN), the other cmsghdr header fields, and the data portion using CMSG_DATA. Finally, the msg_controllen field of the msghdr should be set to the sum of the CMSG_SPACE() of the length of all control messages in the buffer. For more information on the msghdr, see recvmsg(2).

When the control message buffer is too short to store all messages, the MSG_CTRUNC flag is set in the msg_flags member of the msghdr.

CONFORMING TO

This ancillary data model conforms to the POSIX.1g draft, 4.4BSD-Lite, the IPv6 advanced API described in RFC 2292 and the SUSv2. CMSG_ALIGN is a Linux extension.

NOTES

For portability, ancillary data should be accessed only using the macros described here. CMSG_ALIGN() is a Linux extension and should be not used in portable programs.

In Linux, CMSG_LEN, CMSG_DATA, and CMSG_ALIGN() are constant expressions (assuming their argument is constant); this could be used to declare the size of global variables. This may be not portable, however.

EXAMPLE

This code looks for the IP_TTL option in a received ancillary buffer:

struct msghdr msgh;
struct cmsghdr *cmsg;
int *ttlptr;
int received_ttl;

/* Receive auxiliary data in msgh */
for (cmsg = CMSG_FIRSTHDR(&msgh);
    cmsg != NULL;
    cmsg = CMSG_NXTHDR(&msgh,cmsg)) {
        if (cmsg->cmsg_level == IPPROTO_IP
                && cmsg->cmsg_type == IP_TTL) {
            ttlptr = (int *) CMSG_DATA(cmsg);
            received_ttl = *ttlptr;
            break;
        }
    }
if (cmsg == NULL) {
    /*
     * Error: IP_TTL not enabled or small buffer
     * or I/O error.
     */
}

The code below passes an array of file descriptors over a Unix socket using SCM_RIGHTS:

struct msghdr msg = {0};
struct cmsghdr *cmsg;
int myfds[NUM_FD]; /* Contains the file descriptors to pass. */
char buf[CMSG_SPACE(sizeof myfds)];  /* ancillary data buffer */
int *fdptr;

msg.msg_control = buf;
msg.msg_controllen = sizeof buf;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * NUM_FD);
/* Initialize the payload: */
fdptr = (int *) CMSG_DATA(cmsg);
memcpy(fdptr, myfds, NUM_FD * sizeof(int));
/* Sum of the length of all control messages in the buffer: */
msg.msg_controllen = cmsg->cmsg_len;

SEE ALSO

recvmsg(2), sendmsg(2)

RFC 2292


cuserid (3)

 Continue to this page.


difftime(3)

DIFFTIME

Section: Linux Programmer's Manual (3)
Updated: 2002-02-28 Return to Main Contents

NAME

difftime - calculate time difference

SYNOPSIS

#include <time.h>

double difftime(time_t time1, time_t time0);

DESCRIPTION

The difftime() function returns the number of seconds elapsed between time time1 and time time0, represented as a double. The two times are specified in calendar time, which represents the time elapsed since the Epoch (00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)).

CONFORMING TO

SVr4, 4.3BSD, C89, C99

NOTES

On a POSIX system, time_t is an arithmetic type, and one could just define

#define difftime(t1,t0) (double)(t1 - t0)
when the possible overflow in the subtraction is not a concern. On other systems, the data type time_t might use some other encoding where subtraction doesn't work directly.

SEE ALSO

date(1), gettimeofday(2), time(2), ctime(3), gmtime(3), localtime(3)


execle (3)

 Continue to this page.


execlp (3)

 Continue to this page.


fopen(3)

FOPEN

Section: Linux Programmer's Manual (3)
Updated: 2006-05-04 Return to Main Contents

NAME

fopen, fdopen, freopen - stream open functions

SYNOPSIS

#include <stdio.h>

FILE *fopen(const char *path, const char *mode);
FILE *fdopen(int fildes, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);

DESCRIPTION

The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it.

The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):

r
Open text file for reading. The stream is positioned at the beginning of the file.
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
w
Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
w+
Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
a
Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

The mode string can also include the letter ``b'' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the ``b'' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the ``b'' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)

Any created files will have mode S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH (0666), as modified by the process' umask value (see umask(2)).

Reads and writes may be intermixed on read/write streams in any order. Note that ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file. (If this condition is not met, then a read is allowed to return the result of writes other than the most recent.) Therefore it is good practice (and indeed sometimes necessary under Linux) to put an fseek(3) or fgetpos(3) operation between write and read operations on such a stream. This operation may be an apparent no-op (as in fseek(..., 0L, SEEK_CUR) called for its synchronizing side effect.

Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded by an

fseek(stream,0,SEEK_END);
call.

The fdopen() function associates a stream with the existing file descriptor, fildes. The mode of the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be compatible with the mode of the file descriptor. The file position indicator of the new stream is set to that belonging to fildes, and the error and end-of-file indicators are cleared. Modes "w" or "w+" do not cause truncation of the file. The file descriptor is not dup'ed, and will be closed when the stream created by fdopen() is closed. The result of applying fdopen() to a shared memory object is undefined.

The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the fopen() function. The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout).

RETURN VALUE

Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

ERRORS

EINVAL
The mode provided to fopen(), fdopen(), or freopen() was invalid.

The fopen(), fdopen() and freopen() functions may also fail and set errno for any of the errors specified for the routine malloc(3).

The fopen() function may also fail and set errno for any of the errors specified for the routine open(2).

The fdopen() function may also fail and set errno for any of the errors specified for the routine fcntl(2).

The freopen() function may also fail and set errno for any of the errors specified for the routines open(2), fclose(3) and fflush(3).

CONFORMING TO

The fopen() and freopen() functions conform to C89. The fdopen() function conforms to POSIX.1-1990.

NOTES

Glibc Notes

The GNU C library allows the following extensions for the string specified in mode:
c (since glibc 2.3.3)
Do not make the open operation, or subsequent read and write operations, thread cancellation points.
m (since glibc 2.3)
Attempt to access the file using mmap(2), rather than I/O system calls (read(2), write(2)). Currently, use of mmap(2) is only attempted for a file opened for reading.
x
Open the file exclusively (like the O_EXCL flag of open(2)). If the file already exists, fopen() fails, and sets errno to EEXIST. This flag is ignored for fdopen().

SEE ALSO

open(2), fclose(3), fileno(3)


fprintf (3)

 Continue to this page.


fputs (3)

 Continue to this page.


ftell (3)

 Continue to this page.


ftime(3)

FTIME

Section: Linux Programmer's Manual (3)
Updated: 2001-12-14 Return to Main Contents

NAME

ftime - return date and time

SYNOPSIS

#include <sys/timeb.h>

int ftime(struct timeb *tp);

DESCRIPTION

Return current date and time in tp, which is declared as follows:

struct timeb {
    time_t   time;
    unsigned short millitm;
    short    timezone;
    short    dstflag;
};

Here time is the number of seconds since the epoch, millitm is the number of milliseconds since time seconds since the epoch, timezone is the local time zone measured in minutes of time west of Greenwich, and dstflag is a flag that, if non-zero, indicates that Daylight Saving time applies locally during the appropriate part of the year.

These days the contents of the timezone and dstflag fields are undefined.

RETURN VALUE

This function always returns 0.

CONFORMING TO

4.2BSD, POSIX.1-2001.

BUGS

This function is obsolete. Don't use it. If the time in seconds suffices, time(2) can be used; gettimeofday(2) gives microseconds; clock_gettime(3) gives nanoseconds but is not yet widely available.

Under libc4 and libc5 the millitm field is meaningful. But early glibc2 is buggy and returns 0 there; glibc 2.1.1 is correct again.

SEE ALSO

gettimeofday(2), time(2)


isupper (3)

 Continue to this page.


localtime (3)

 Continue to this page.


mbtowc(3)

MBTOWC

Section: Linux Programmer's Manual (3)
Updated: 2001-07-04 Return to Main Contents

NAME

mbtowc - convert a multibyte sequence to a wide character

SYNOPSIS

#include <stdlib.h>

int mbtowc(wchar_t *pwc, const char *s, size_t n);

DESCRIPTION

The main case for this function is when s is not NULL and pwc is not NULL. In this case, the mbtowc() function inspects at most n bytes of the multibyte string starting at s, extracts the next complete multibyte character, converts it to a wide character and stores it at *pwc. It updates an internal shift state only known to the mbtowc function. If s does not point to a '\0' byte, it returns the number of bytes that were consumed from s, otherwise it returns 0.

If the n bytes starting at s do not contain a complete multibyte character, or if they contain an invalid multibyte sequence, mbtowc() returns -1. This can happen even if n >= MB_CUR_MAX, if the multibyte string contains redundant shift sequences.

A different case is when s is not NULL but pwc is NULL. In this case the mbtowc() function behaves as above, excepts that it does not store the converted wide character in memory.

A third case is when s is NULL. In this case, pwc and n are ignored. The mbtowc() function resets the shift state, only known to this function, to the initial state, and returns non-zero if the encoding has non-trivial shift state, or zero if the encoding is stateless.

RETURN VALUE

If s is not NULL, the mbtowc() function returns the number of consumed bytes starting at s, or 0 if s points to a null byte, or -1 upon failure.

If s is NULL, the mbtowc() function returns non-zero if the encoding has non-trivial shift state, or zero if the encoding is stateless.

CONFORMING TO

C99

NOTES

The behavior of mbtowc() depends on the LC_CTYPE category of the current locale.

This function is not multi-thread safe. The function mbrtowc(3) provides a better interface to the same functionality.

SEE ALSO

MB_CUR_MAX(3), mbrtowc(3), mbstowcs(3)


ntohs (3)

 Continue to this page.


popen(3)

POPEN

Section: Linux Programmer's Manual (3)
Updated: 1998-05-07 Return to Main Contents

NAME

popen, pclose - process I/O

SYNOPSIS

#include <stdio.h>

FILE *popen(const char *command, const char *type);

int pclose(FILE *stream);

DESCRIPTION

The popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only or write-only.

The command argument is a pointer to a null-terminated string containing a shell command line. This command is passed to /bin/sh using the -c flag; interpretation, if any, is performed by the shell. The type argument is a pointer to a null-terminated string which must be either `r' for reading or `w' for writing.

The return value from popen() is a normal standard I/O stream in all respects save that it must be closed with pclose() rather than fclose(3). Writing to such a stream writes to the standard input of the command; the command's standard output is the same as that of the process that called popen(), unless this is altered by the command itself. Conversely, reading from a ``popened'' stream reads the command's standard output, and the command's standard input is the same as that of the process that called popen().

Note that output popen() streams are fully buffered by default.

The pclose() function waits for the associated process to terminate and returns the exit status of the command as returned by wait4(2).

RETURN VALUE

The popen() function returns NULL if the fork(2) or pipe(2) calls fail, or if it cannot allocate memory.

The pclose() function returns -1 if wait4(2) returns an error, or some other error is detected.

ERRORS

The popen() function does not set errno if memory allocation fails. If the underlying fork(2) or pipe(2) fails, errno is set appropriately. If the type argument is invalid, and this condition is detected, errno is set to EINVAL.

If pclose() cannot obtain the child status, errno is set to ECHILD.

CONFORMING TO

POSIX.1-2001.

BUGS

Since the standard input of a command opened for reading shares its seek offset with the process that called popen(), if the original process has done a buffered read, the command's input position may not be as expected. Similarly, the output from a command opened for writing may become intermingled with that of the original process. The latter can be avoided by calling fflush(3) before popen().

Failure to execute the shell is indistinguishable from the shell's failure to execute command, or an immediate exit of the command. The only hint is an exit status of 127.

SEE ALSO

sh(1), fork(2), pipe(2), wait4(2), fclose(3), fflush(3), fopen(3), stdio(3), system(3)


srand (3)

 Continue to this page.


tfind (3)

 Continue to this page.


ttyname(3)

TTYNAME

Section: Linux Programmer's Manual (3)
Updated: 2002-07-20 Return to Main Contents

NAME

ttyname, ttyname_r - return name of a terminal

SYNOPSIS

#include <unistd.h>

char *ttyname(int fd);

int ttyname_r(int fd, char *buf, size_t buflen);

DESCRIPTION

The function ttyname() returns a pointer to the null-terminated pathname of the terminal device that is open on the file descriptor fd, or NULL on error (for example, if fd is not connected to a terminal). The return value may point to static data, possibly overwritten by the next call. The function ttyname_r() stores this pathname in the buffer buf of length buflen.

RETURN VALUE

The function ttyname() returns a pointer to a pathname on success. On error, NULL is returned, and errno is set appropriately. The function ttyname_r() returns 0 on success, and an error number upon error.

ERRORS

Values stored in errno by a failing ttyname() or returned by a failing ttyname_r():
EBADF
Bad file descriptor.
ENOTTY
File descriptor does not refer to a terminal device.
ERANGE
buflen was too small to allow storing the pathname.

CONFORMING TO

4.2BSD, POSIX.1-2001.

SEE ALSO

fstat(2), isatty(3)


alloca(3)

ALLOCA

Section: Linux Programmer's Manual (3)
Updated: 2002-07-17 Return to Main Contents

NAME

alloca - memory allocator

SYNOPSIS

#include <alloca.h>

void *alloca(size_t size);

DESCRIPTION

The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.

RETURN VALUE

The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.

CONFORMING TO

There is evidence that the alloca() function appeared in 32v, pwb, pwb.2, 3bsd, and 4bsd. There is a man page for it in 4.3BSD. Linux uses the GNU version. This function is not in POSIX.1-2001.

NOTES

Notes on the GNU Version

Normally, gcc translates calls to alloca() by inlined code. This is not done when either the -ansi or the -fno-builtin option is given. But beware! By default the glibc version of <stdlib.h> includes <alloca.h> and that contains the line:

    # define alloca(size)   __builtin_alloca (size)
with messy consequences if one has a private version of this function.

The fact that the code is inlined, means that it is impossible to take the address of this function, or to change its behavior by linking with a different library.

The inlined code often consists of a single instruction adjusting the stack pointer, and does not check for stack overflow. Thus, there is no NULL error return.

BUGS

The alloca() function is machine and compiler dependent. On many systems its implementation is buggy. Its use is discouraged.

On many systems alloca() cannot be used inside the list of arguments of a function call, because the stack space reserved by alloca() would appear on the stack in the middle of the space for the function arguments.

SEE ALSO

brk(2), getpagesize(2), calloc(3), malloc(3), realloc(3)


asinh(3)

ASINH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

asinh, asinhf, asinhl - inverse hyperbolic sine function

SYNOPSIS

#include <math.h>

double asinh(double x);

float asinhf(float x);

long double asinhl(long double x);

Link with -lm.

DESCRIPTION

The asinh() function calculates the inverse hyperbolic sine of x; that is the value whose hyperbolic sine is x.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acosh(3), atanh(3), casinh(3), cosh(3), sinh(3), tanh(3)


execv (3)

 Continue to this page.


log(3)

LOG

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

log, logf, logl - natural logarithmic function

SYNOPSIS

#include <math.h>

double log(double x);

float logf(float x);

long double logl(long double x);

Link with -lm.

DESCRIPTION

The log() function returns the natural logarithm of x.

ERRORS

The log() function can return the following errors:
EDOM
The argument x is negative.
ERANGE
The argument x is zero. The log of zero is not defined (minus infinity).

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

cbrt(3), clog(3), log1p(3), sqrt(3)


memchr(3)

MEMCHR

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

memchr, memrchr - scan memory for a character

SYNOPSIS

#include <string.h>

void *memchr(const void *s, int c, size_t n);

void *memrchr(const void *s, int c, size_t n);

DESCRIPTION

The memchr() function scans the first n bytes of the memory area pointed to by s for the character c. The first byte to match c (interpreted as an unsigned character) stops the operation.

The memrchr() function is like the memchr() function, except that it searches backwards from the end of the n bytes pointed to by s instead of forwards from the front.

RETURN VALUE

The memchr() and memrchr() functions return a pointer to the matching byte or NULL if the character does not occur in the given memory area.

CONFORMING TO

The memchr() function conforms to SVr4, 4.3BSD, C89, C99, POSIX.1-2001. The memrchr() function is a GNU extension, available since glibc 2.1.91.

SEE ALSO

index(3), rindex(3), strchr(3), strpbrk(3), strrchr(3), strsep(3), strspn(3), strstr(3), wmemchr(3)


memcpy(3)

MEMCPY

Section: Linux Programmer's Manual (3)
Updated: 1993-04-10 Return to Main Contents

NAME

memcpy - copy memory area

SYNOPSIS

#include <string.h>

void *memcpy(void *dest, const void *src, size_t n);

DESCRIPTION

The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas should not overlap. Use memmove(3) if the memory areas do overlap.

RETURN VALUE

The memcpy() function returns a pointer to dest.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001.

SEE ALSO

bcopy(3), memccpy(3), memmove(3), mempcpy(3), strcpy(3), strncpy(3), wmemcpy(3)


hasmntopt (3)

 Continue to this page.


hsearch(3)

HSEARCH

Section: Linux Programmer's Manual (3)
Updated: 2004-05-20 Return to Main Contents

NAME

hcreate, hdestroy, hsearch - hash table management

SYNOPSIS

#include <search.h>

int hcreate(size_t nel);

ENTRY *hsearch(ENTRY item, ACTION action);

void hdestroy(void);

#define _GNU_SOURCE

#include <search.h>

int hcreate_r(size_t nel, struct hsearch_data *tab);

int hsearch_r(ENTRY item, ACTION action, ENTRY **ret,
              struct hsearch_data *tab);

void hdestroy_r(struct hsearch_data *tab);

DESCRIPTION

The three functions hcreate(), hsearch(), and hdestroy() allow the user to create a hash table (only one at a time) which associates a key with any data.

First the table must be created with the function hcreate(). The argument nel is an estimate of the maximum number of entries in the table. The function hcreate() may adjust this value upward to improve the performance of the resulting hash table.

The corresponding function hdestroy() frees the memory occupied by the hash table so that a new table can be constructed.

The argument item is of type ENTRY, which is a typedef defined in <search.h> and includes these elements:

typedef struct entry {
    char *key;
    void *data;
} ENTRY;

The field key points to the null-terminated string which is the search key. The field data points to the data associated with that key. The function hsearch() searches the hash table for an item with the same key as item (where "the same" is determined using strcmp(3)), and if successful returns a pointer to it. The argument action determines what hsearch() does after an unsuccessful search. A value of ENTER instructs it to insert a copy of item, while a value of FIND means to return NULL.

The three functions hcreate_r(), hsearch_r(), hdestroy_r() are reentrant versions that allow the use of more than one table. The last argument used identifies the table. The struct it points to must be zeroed before the first call to hcreate_r().

RETURN VALUE

hcreate() and hcreate_r() return 0 when allocation of the memory for the hash table fails, non-zero otherwise.

hsearch() returns NULL if action is ENTER and the hash table is full, or action is FIND and item cannot be found in the hash table.

hsearch_r() returns 0 if action is ENTER and the hash table is full, and non-zero otherwise.

ERRORS

POSIX documents
ENOMEM
Out of memory.

The glibc implementation will return the following two errors.

ENOMEM
Table full with action set to ENTER.
ESRCH
The action parameter is FIND and no corresponding element is found in the table.

CONFORMING TO

The functions hcreate(), hsearch(), and hdestroy() are from SVr4, and are described in POSIX.1-2001. The functions hcreate_r(), hsearch_r(), hdestroy_r() are GNU extensions.

BUGS

SVr4 and POSIX.1-2001 specify that action is significant only for unsuccessful searches, so that an ENTER should not do anything for a successful search. The libc and glibc implementations update the data for the given key in this case.

Individual hash table entries can be added, but not deleted.

EXAMPLE

The following program inserts 24 items in to a hash table, then prints some of them.

#include <stdio.h>
#include <stdlib.h>
#include <search.h>

char *data[] = { "alpha", "bravo", "charlie", "delta",
     "echo", "foxtrot", "golf", "hotel", "india", "juliet",
     "kilo", "lima", "mike", "november", "oscar", "papa",
     "quebec", "romeo", "sierra", "tango", "uniform",
     "victor", "whisky", "x-ray", "yankee", "zulu"
};

int
main(void)
{
    ENTRY e, *ep;
    int i;

    /* starting with small table, and letting it grow does not work */
    hcreate(30);
    for (i = 0; i < 24; i++) {
        e.key = data[i];
        /* data is just an integer, instead of a
           pointer to something */
        e.data = (void *) i;
        ep = hsearch(e, ENTER);
        /* there should be no failures */
        if (ep == NULL) {
            fprintf(stderr, "entry failed\n");
            exit(EXIT_FAILURE);
        }
    }
    for (i = 22; i < 26; i++) {
        /* print two entries from the table, and
           show that two are not in the table */
        e.key = data[i];
        ep = hsearch(e, FIND);
        printf("%9.9s -> %9.9s:%d\n", e.key,
               ep ? ep->key : "NULL", ep ? (int)(ep->data) : 0);
    }
    exit(EXIT_SUCCESS);
}

SEE ALSO

bsearch(3), lsearch(3), malloc(3), tsearch(3), feature_test_macros(7)


log1p(3)

LOG1P

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

log1p - logarithm of 1 plus argument

SYNOPSIS

#include <math.h>

double log1p(double x);

float log1pf(float x);

long double log1pl(long double x);
Compile with -std=c99; link with -lm.

DESCRIPTION

log1p(x) returns a value equivalent to `log (1 + x)'. It is computed in a way that is accurate even if the value of x is near zero.

CONFORMING TO

BSD, C99. The float and long double variants are C99 requirements.

SEE ALSO

exp(3), expm1(3), log(3)


lsearch(3)

LSEARCH

Section: Linux Programmer's Manual (3)
Updated: 1999-09-27 Return to Main Contents

NAME

lfind, lsearch - linear search of an array

SYNOPSIS

#include <search.h>

void *lfind(const void *key, const void *base, size_t *nmemb,

size_t size, int(*compar)(const void *, const void *));

void *lsearch(const void *key, void *base, size_t *nmemb,

size_t size, int(*compar)(const void *, const void *));

DESCRIPTION

lfind() and lsearch() perform a linear search for key in the array base which has *nmemb elements of size bytes each. The comparison function referenced by compar is expected to have two arguments which point to the key object and to an array member, in that order, and which returns zero if the key object matches the array member, and non-zero otherwise.

If lsearch() does not find a matching element, then the key object is inserted at the end of the table, and *nmemb is incremented. In particular, one should know that a matching element exists, or that more room is available.

RETURN VALUE

lfind() returns a pointer to a matching member of the array, or NULL if no match is found. lsearch() returns a pointer to a matching member of the array, or to the newly added member if no match is found.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001. Present in libc since libc-4.6.27.

BUGS

The naming is unfortunate.

SEE ALSO

bsearch(3), hsearch(3), tsearch(3)


malloc(3)

MALLOC

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

calloc, malloc, free, realloc - Allocate and free dynamic memory

SYNOPSIS

#include <stdlib.h>

void *calloc(size_t nmemb, size_t size);

void *malloc(size_t size);

void free(void *ptr);

void *realloc(void *ptr, size_t size);

DESCRIPTION

calloc() allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero.

malloc() allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared.

free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.

realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to malloc(size); if size is equal to zero, the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done.

RETURN VALUE

For calloc() and malloc(), the value returned is a pointer to the allocated memory, which is suitably aligned for any kind of variable, or NULL if the request fails.

free() returns no value.

realloc() returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails the original block is left untouched; it is not freed or moved.

CONFORMING TO

C89, C99.

NOTES

The Unix98 standard requires malloc(), calloc(), and realloc() to set errno to ENOMEM upon failure. Glibc assumes that this is done (and the glibc versions of these routines do this); if you use a private malloc implementation that does not set errno, then certain library routines may fail without having a reason in errno.

Crashes in malloc(), calloc(), realloc(), or free() are almost always related to heap corruption, such as overflowing an allocated chunk or freeing the same pointer twice.

Recent versions of Linux libc (later than 5.4.23) and GNU libc (2.x) include a malloc implementation which is tunable via environment variables. When MALLOC_CHECK_ is set, a special (less efficient) implementation is used which is designed to be tolerant against simple errors, such as double calls of free() with the same argument, or overruns of a single byte (off-by-one bugs). Not all such errors can be protected against, however, and memory leaks can result. If MALLOC_CHECK_ is set to 0, any detected heap corruption is silently ignored; if set to 1, a diagnostic is printed on stderr; if set to 2, abort(3) is called immediately. This can be useful because otherwise a crash may happen much later, and the true cause for the problem is then very hard to track down.

BUGS

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer. In case Linux is employed under circumstances where it would be less desirable to suddenly lose some randomly picked processes, and moreover the kernel version is sufficiently recent, one can switch off this overcommitting behavior using a command like
# echo 2 > /proc/sys/vm/overcommit_memory
See also the kernel Documentation directory, files vm/overcommit-accounting and sysctl/vm.txt.

SEE ALSO

brk(2), posix_memalign(3)


mblen(3)

MBLEN

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

mblen - determine number of bytes in next multibyte character

SYNOPSIS

#include <stdlib.h>

int mblen(const char *s, size_t n);

DESCRIPTION

If s is not a NULL pointer, the mblen() function inspects at most n bytes of the multibyte string starting at s and extracts the next complete multibyte character. It uses a static anonymous shift state only known to the mblen function. If the multibyte character is not the null wide character, it returns the number of bytes that were consumed from s. If the multibyte character is the null wide character, it returns 0.

If the n bytes starting at s do not contain a complete multibyte character, mblen() returns -1. This can happen even if n >= MB_CUR_MAX, if the multibyte string contains redundant shift sequences.

If the multibyte string starting at s contains an invalid multibyte sequence before the next complete character, mblen() also returns -1.

If s is a NULL pointer, the mblen() function resets the shift state, only known to this function, to the initial state, and returns non-zero if the encoding has non-trivial shift state, or zero if the encoding is stateless.

RETURN VALUE

The mblen() function returns the number of bytes parsed from the multibyte sequence starting at s, if a non-null wide character was recognized. It returns 0, if a null wide character was recognized. It returns -1, if an invalid multibyte sequence was encountered or if it couldn't parse a complete multibyte character.

CONFORMING TO

C99

NOTES

The behavior of mblen() depends on the LC_CTYPE category of the current locale.

The function mbrlen(3) provides a better interface to the same functionality.

SEE ALSO

mbrlen(3)


memmem(3)

MEMMEM

Section: Linux Programmer's Manual (3)
Updated: 1998-01-13 Return to Main Contents

NAME

memmem - locate a substring

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

void *memmem(const void *haystack, size_t haystacklen,
const void *needle, size_t needlelen);

DESCRIPTION

The memmem() function finds the start of the first occurrence of the substring needle of length needlelen in the memory area haystack of length haystacklen.

RETURN VALUE

The memmem() function returns a pointer to the beginning of the substring, or NULL if the substring is not found.

CONFORMING TO

This function is a GNU extension.

BUGS

This function was broken in Linux libraries up to and including libc 5.0.9; there the `needle' and `haystack' arguments were interchanged, and a pointer to the end of the first occurrence of needle was returned. Since libc 5.0.9 is still widely used, this is a dangerous function to use.
Both old and new libc's have the bug that if needle is empty haystack-1 (instead of haystack) is returned. And glibc 2.0 makes it worse, and returns a pointer to the last byte of `haystack'. This is fixed in glibc 2.1.

SEE ALSO

strstr(3), feature_test_macros(7)


putchar (3)

 Continue to this page.


setservent (3)

 Continue to this page.


sscanf (3)

 Continue to this page.


readdir(3)

READDIR

Section: Linux Programmer's Manual (3)
Updated: 1996-04-22 Return to Main Contents

NAME

readdir - read a directory

SYNOPSIS

#include <sys/types.h>

#include <dirent.h>

struct dirent *readdir(DIR *dir);

DESCRIPTION

The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dir. It returns NULL on reaching the end-of-file or if an error occurred.

On Linux, the dirent structure is defined as follows:

struct dirent {
    ino_t          d_ino;       /* inode number */
    off_t          d_off;       /* offset to the next dirent */
    unsigned short d_reclen;    /* length of this record */
    unsigned char  d_type;      /* type of file */
    char           d_name[256]; /* filename */
};

According to POSIX, the dirent structure contains a field char d_name[] of unspecified size, with at most NAME_MAX characters preceding the terminating null byte. POSIX.1-2001 also documents the field ino_t d_ino as an XSI extension. Use of other fields will harm the portability of your programs.

The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.

RETURN VALUE

The readdir() function returns a pointer to a dirent structure, or NULL if an error occurs or end-of-file is reached. On error, errno is set appropriately.

ERRORS

EBADF
Invalid directory stream descriptor dir.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001

SEE ALSO

read(2), closedir(3), dirfd(3), ftw(3), opendir(3), rewinddir(3), scandir(3), seekdir(3), telldir(3)


asin(3)

ASIN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-25 Return to Main Contents

NAME

asin, asinf, asinl - arc sine function

SYNOPSIS

#include <math.h>

double asin(double x);

float asinf(float x);

long double asinl(long double x);

Link with -lm.

DESCRIPTION

The asin() function calculates the arc sine of x; that is the value whose sine is x. If x falls outside the range -1 to 1, asin() fails and errno is set.

RETURN VALUE

The asin() function returns the arc sine in radians and the value is mathematically defined to be between -PI/2 and PI/2 (inclusive).

ERRORS

EDOM
x is out of range.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89, C99. The float and long double variants are C99 requirements.

SEE ALSO

acos(3), casin(3), atan(3), atan2(3), cos(3), sin(3), tan(3)


drem (3)

 Continue to this page.


endprotoent (3)

 Continue to this page.


execvp (3)

 Continue to this page.


re_exec (3)

 Continue to this page.


hdestroy (3)

 Continue to this page.


herror (3)

 Continue to this page.


memccpy(3)

MEMCCPY

Section: Linux Programmer's Manual (3)
Updated: 1993-04-10 Return to Main Contents

NAME

memccpy - copy memory area

SYNOPSIS

#include <string.h>

void *memccpy(void *dest, const void *src, int c, size_t n);

DESCRIPTION

The memccpy() function copies no more than n bytes from memory area src to memory area dest, stopping when the character c is found.

RETURN VALUE

The memccpy() function returns a pointer to the next character in dest after c, or NULL if c was not found in the first n characters of src.

CONFORMING TO

SVr4, 4.3BSD, C99

SEE ALSO

bcopy(3), memcpy(3), memmove(3), strcpy(3), strncpy(3)


modf(3)

MODF

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

modf, modff, modfl - extract signed integral and fractional values from floating-point number

SYNOPSIS

#include <math.h>

double modf(double x, double *iptr);

float modff(float x, float *iptr);

long double modfl(long double x, long double *iptr);

Link with -lm.

DESCRIPTION

The modf() function breaks the argument x into an integral part and a fractional part, each of which has the same sign as x. The integral part is stored in iptr.

RETURN VALUE

The modf() function returns the fractional part of x.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

frexp(3), ldexp(3)


mpool(3)

MPOOL

Section: Linux Programmer's Manual (3)
Updated: 1993-06-04 Return to Main Contents

NAME

mpool - shared memory buffer pool

SYNOPSIS

#include <db.h>
#include <mpool.h>

MPOOL *
mpool_open (DBT *key, int fd, pgno_t pagesize, pgno_t maxcache);

void
mpool_filter (MPOOL *mp, void (*pgin)(void *, pgno_t, void *),

     void (*pgout)(void *, pgno_t, void *), void *pgcookie);

void *
mpool_new (MPOOL *mp, pgno_t *pgnoaddr);

void *
mpool_get (MPOOL *mp, pgno_t pgno, u_int flags);

int
mpool_put (MPOOL *mp, void *pgaddr, u_int flags);

int
mpool_sync (MPOOL *mp);

int
mpool_close (MPOOL *mp);

DESCRIPTION

Mpool is the library interface intended to provide page oriented buffer management of files. The buffers may be shared between processes.

The function mpool_open() initializes a memory pool. The key argument is the byte string used to negotiate between multiple processes wishing to share buffers. If the file buffers are mapped in shared memory, all processes using the same key will share the buffers. If key is NULL, the buffers are mapped into private memory. The fd argument is a file descriptor for the underlying file, which must be seekable. If key is non-NULL and matches a file already being mapped, the fd argument is ignored.

The pagesize argument is the size, in bytes, of the pages into which the file is broken up. The maxcache argument is the maximum number of pages from the underlying file to cache at any one time. This value is not relative to the number of processes which share a file's buffers, but will be the largest value specified by any of the processes sharing the file.

The mpool_filter() function is intended to make transparent input and output processing of the pages possible. If the pgin function is specified, it is called each time a buffer is read into the memory pool from the backing file. If the pgout function is specified, it is called each time a buffer is written into the backing file. Both functions are called with the pgcookie pointer, the page number and a pointer to the page to being read or written.

The function mpool_new() takes an MPOOL pointer and an address as arguments. If a new page can be allocated, a pointer to the page is returned and the page number is stored into the pgnoaddr address. Otherwise, NULL is returned and errno is set.

The function mpool_get() takes a MPOOL pointer and a page number as arguments. If the page exists, a pointer to the page is returned. Otherwise, NULL is returned and errno is set. The flags parameter is not currently used.

The function mpool_put() unpins the page referenced by pgaddr. pgaddr must be an address previously returned by mpool_get() or mpool_new(). The flag value is specified by or'ing any of the following values:

MPOOL_DIRTY
The page has been modified and needs to be written to the backing file.

mpool_put() returns 0 on success and -1 if an error occurs.

The function mpool_sync() writes all modified pages associated with the MPOOL pointer to the backing file. mpool_sync() returns 0 on success and -1 if an error occurs.

The mpool_close() function free's up any allocated memory associated with the memory pool cookie. Modified pages are not written to the backing file. mpool_close() returns 0 on success and -1 if an error occurs.

ERRORS

The mpool_open() function may fail and set errno for any of the errors specified for the library routine malloc(3).

The mpool_get() function may fail and set errno for the following:

[EINVAL]
The requested record doesn't exist.

The mpool_new() and mpool_get() functions may fail and set errno for any of the errors specified for the library routines read(2), write(2), and malloc(3).

The mpool_sync() function may fail and set errno for any of the errors specified for the library routine write(2).

The mpool_close() function may fail and set errno for any of the errors specified for the library routine free(3).

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs.

SEE ALSO

dbopen(3), btree(3), hash(3), recno(3)


netlink(3)

NETLINK

Section: Linux Programmer's Manual (3)
Updated: 1999-05-14 Return to Main Contents

NAME

netlink - Netlink macros

SYNOPSIS

#include <asm/types.h>

#include <linux/netlink.h>

int NLMSG_ALIGN(size_t len);

int NLMSG_LENGTH(size_t len);

int NLMSG_SPACE(size_t len);

void *NLMSG_DATA(struct nlmsghdr *nlh);

struct nlmsghdr *NLMSG_NEXT(struct nlmsghdr *nlh, int len);

int NLMSG_OK(struct nlmsghdr *nlh, int len);

int NLMSG_PAYLOAD(struct nlmsghdr *nlh, int len);

DESCRIPTION

<linux/netlink.h> defines several standard macros to access or create a netlink datagram. They are similar in spirit to the macros defined in cmsg(3) for auxiliary data. The buffer passed to and from a netlink socket should be only accessed using these macros.
NLMSG_ALIGN
Round the length of a netlink message up to align it properly.
NLMSG_LENGTH
Gets the payload length as argument and returns the aligned length to store in the nlmsg_len field of the nlmsghdr.
NLMSG_SPACE
Return the number of bytes a netlink message with payload of the passed length would occupy.
NLMSG_DATA
Return a pointer to the payload associated with the passed nlmsghdr.
NLMSG_NEXT Get the next nlmsghdr in a multipart message. The caller must check if the current nlmsghdr didn't have the NLMSG_DONE set --- this function doesn't return NULL on end. The length parameter is an lvalue containing the remaining length of the message buffer. This macro decrements it by the length of the message header.
NLMSG_OK
Return true if the netlink message is not truncated and ok to parse.
NLMSG_PAYLOAD
Return the length of the payload associated with the nlmsghdr.

NOTES

It is often better to use netlink via libnetlink than via the low level kernel interface.

SEE ALSO

netlink(7)

and ftp://ftp.inr.ac.ru/ip-routing/iproute2* for libnetlink


on_exit(3)

ON_EXIT

Section: Linux Programmer's Manual (3)
Updated: 1993-04-02 Return to Main Contents

NAME

on_exit - register a function to be called at normal process termination

SYNOPSIS

#include <stdlib.h>

int on_exit(void (*function)(int , void *), void *arg);

DESCRIPTION

The on_exit() function registers the given function to be called at normal process termination, whether via exit(3) or via return from the program's main(). The function is passed the argument to exit(3) and the arg argument from on_exit().

RETURN VALUE

The on_exit() function returns the value 0 if successful; otherwise it returns a non-zero value.

CONFORMING TO

This function comes from SunOS 4, but is also present in libc4, libc5 and glibc. It no longer occurs in Solaris (SunOS 5). Avoid this function, and use the standard atexit(3) instead.

SEE ALSO

_exit(2), atexit(3), exit(3)


pow(3)

POW

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

pow, powf, powl - power functions

SYNOPSIS

#include <math.h>

double pow(double x, double y);

float powf(float x, float y);

long double powl(long double x, long double y);

Link with -lm.

DESCRIPTION

The pow() function returns the value of x raised to the power of y.

ERRORS

The pow() function can return the following error:
EDOM
The argument x is negative and y is not an integral value. This would result in a complex number.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

cbrt(3), cpow(3), sqrt(3)


putc (3)

 Continue to this page.


putenv(3)

PUTENV

Section: Linux Programmer's Manual (3)
Updated: 1993-04-08 Return to Main Contents

NAME

putenv - change or add an environment variable

SYNOPSIS

#include <stdlib.h>

int putenv(char *string);

DESCRIPTION

The putenv() function adds or changes the value of environment variables. The argument string is of the form name=value. If name does not already exist in the environment, then string is added to the environment. If name does exist, then the value of name in the environment is changed to value. The string pointed to by string becomes part of the environment, so altering the string changes the environment.

RETURN VALUE

The putenv() function returns zero on success, or non-zero if an error occurs.

ERRORS

ENOMEM
Insufficient space to allocate new environment.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD

NOTES

The putenv() function is not required to be reentrant, and the one in libc4, libc5 and glibc 2.0 is not, but the glibc 2.1 version is.

Description for libc4, libc5, glibc: If the argument string is of the form name, and does not contain an `=' character, then the variable name is removed from the environment. If putenv() has to allocate a new array environ, and the previous array was also allocated by putenv(), then it will be freed. In no case will the old storage associated to the environment variable itself be freed.

The libc4 and libc5 and glibc 2.1.2 versions conform to SUSv2: the pointer string given to putenv() is used. In particular, this string becomes part of the environment; changing it later will change the environment. (Thus, it is an error is to call putenv() with an automatic variable as the argument, then return from the calling function while string is still part of the environment.) However, glibc 2.0-2.1.1 differs: a copy of the string is used. On the one hand this causes a memory leak, and on the other hand it violates SUSv2. This has been fixed in glibc 2.1.2.

The 4.4BSD version, like glibc 2.0, uses a copy.

SUSv2 removes the `const' from the prototype, and so does glibc 2.1.3.

SEE ALSO

clearenv(3), getenv(3), setenv(3), unsetenv(3), environ(7)


rcmd(3)

RCMD

Section: C Library Functions (3) Return to Main Contents

BSD mandoc
4.2BSD

NAME

rcmd rresvport iruserok ruserok - routines for returning a stream to a remote command

SYNOPSIS

Fd #include <netdb.h> /* Or <unistd.h> on some systems */ Ft int Fn rcmd char **ahost int inport const char *locuser const char *remuser const char *cmd int *fd2p Ft int Fn rresvport int *port Ft int Fn iruserok u_int32_t raddr int superuser const char *ruser const char *luser Ft int Fn ruserok const char *rhost int superuser const char *ruser const char *luser

DESCRIPTION

The Fn rcmd function is used by the superuser to execute a command on a remote machine using an authentication scheme based on reserved port numbers. The Fn rresvport function returns a descriptor to a socket with an address in the privileged port space. The Fn iruserok and Fn ruserok functions are used by servers to authenticate clients requesting service with Fn rcmd . All four functions are present in the same file and are used by the rshd(8) server (among others).

The Fn rcmd function looks up the host Fa *ahost using gethostbyname(3), returning -1 if the host does not exist. Otherwise Fa *ahost is set to the standard name of the host and a connection is established to a server residing at the well-known Internet port Fa inport .

If the connection succeeds, a socket in the Internet domain of type SOCK_STREAM is returned to the caller, and given to the remote command as stdin and stdout If Fa fd2p is non-zero, then an auxiliary channel to a control process will be set up, and a descriptor for it will be placed in Fa *fd2p . The control process will return diagnostic output from the command (unit 2) on this channel, and will also accept bytes on this channel as being UNIX signal numbers, to be forwarded to the process group of the command. If Fa fd2p is 0, then the stderr (unit 2 of the remote command) will be made the same as the stdout and no provision is made for sending arbitrary signals to the remote process, although you may be able to get its attention by using out-of-band data.

The protocol is described in detail in rshd(8).

The Fn rresvport function is used to obtain a socket with a privileged address bound to it. This socket is suitable for use by Fn rcmd and several other functions. Privileged Internet ports are those in the range 0 to 1023. Only the superuser is allowed to bind an address of this sort to a socket.

The Fn iruserok and Fn ruserok functions take a remote host's IP address or name, respectively, two user names and a flag indicating whether the local user's name is that of the superuser. Then, if the user is NOT the superuser, it checks the /etc/hosts.equiv file. If that lookup is not done, or is unsuccessful, the .rhosts in the local user's home directory is checked to see if the request for service is allowed.

If this file does not exist, is not a regular file, is owned by anyone other than the user or the superuser, or is writable by anyone other than the owner, the check automatically fails. Zero is returned if the machine name is listed in the ``hosts.equiv '' file, or the host and remote user name are found in the ``.rhosts '' file; otherwise Fn iruserok and Fn ruserok return -1. If the local domain (as obtained from gethostname(2)) is the same as the remote domain, only the machine name need be specified.

If the IP address of the remote host is known, Fn iruserok should be used in preference to Fn ruserok , as it does not require trusting the DNS server for the remote host's domain.

RETURN VALUE

The Fn rcmd function returns a valid socket descriptor on success. It returns -1 on error and prints a diagnostic message on the standard error.

The Fn rresvport function returns a valid, bound socket descriptor on success. It returns -1 on error with the global value errno set according to the reason for failure. The error code EAGAIN is overloaded to mean ``All network ports in use.''

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs, Solaris, and many other systems. These functions appeared in BSD 4.2

SEE ALSO

rlogin(1), rsh(1), intro(2), rexec(3), rexecd(8), rlogind(8), rshd(8)


sigfillset (3)

 Continue to this page.


stderr (3)

 Continue to this page.


stpcpy(3)

STPCPY

Section: Linux Programmer's Manual (3)
Updated: 1995-09-03 Return to Main Contents

NAME

stpcpy - copy a string returning a pointer to its end

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

char *stpcpy(char *dest, const char *src);

DESCRIPTION

The stpcpy() function copies the string pointed to by src (including the terminating `\0' character) to the array pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

RETURN VALUE

stpcpy() returns a pointer to the end of the string dest (that is, the address of the terminating null byte) rather than the beginning.

CONFORMING TO

This function is not part of the C or POSIX.1 standards, and is not customary on Unix systems, but is not a GNU invention either. Perhaps it comes from MS-DOS.

EXAMPLE

For example, this program uses stpcpy() to concatenate foo and bar to produce foobar, which it then prints.

#include <string.h>

int
main (void)
{
    char *to = buffer;
    to = stpcpy(to, "foo");
    to = stpcpy(to, "bar");
    printf("%s\n", buffer);
}

SEE ALSO

bcopy(3), memccpy(3), memcpy(3), memmove(3), strcpy(3), wcpcpy(3), feature_test_macros(7)


strncmp (3)

 Continue to this page.


atan(3)

ATAN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

atan, atanf, atanl - arc tangent function

SYNOPSIS

#include <math.h>

double atan(double x);

float atanf(float x);

long double atanl( long double x);
Link with -lm.

DESCRIPTION

The atan() function calculates the arc tangent of x; that is the value whose tangent is x.

RETURN VALUE

The atan() function returns the arc tangent in radians and the value is mathematically defined to be between -PI/2 and PI/2 (inclusive).

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acos(3), asin(3), atan2(3), carg(3), catan(3), cos(3), sin(3), tan(3)


htons (3)

 Continue to this page.


atexit(3)

ATEXIT

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

atexit - register a function to be called at normal process termination

SYNOPSIS

#include <stdlib.h>

int atexit(void (*function)(void));

DESCRIPTION

The atexit() function registers the given function to be called at normal process termination, either via exit(3) or via return from the program's main(). Functions so registered are called in the reverse order of their registration; no arguments are passed.

POSIX.1-2001 requires that an implementation allow at least ATEXIT_MAX (32) such functions to be registered. The actual limit supported by an implementation can be obtained using sysconf(3).

When a child process is created via fork(2), it inherits copies of its parent's registrations. Upon a successful call to one of the exec(3) functions, all registrations are removed.

RETURN VALUE

The atexit() function returns the value 0 if successful; otherwise it returns a non-zero value.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001.

NOTES

Functions registered using atexit() (and on_exit(3)) are not called if a process terminates abnormally because of the delivery of a signal.

Linux Notes

Since glibc 2.2.3, atexit() (and on_exit(3)) can be used within a shared library to establish functions that are called when the shared library is unloaded.

EXAMPLE

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void
bye(void)
{
    printf("That was all, folks\n");
}

int
main(void)
{
    long a;
    int i;

    a = sysconf(_SC_ATEXIT_MAX);
    printf("ATEXIT_MAX = %ld\n", a);

    i = atexit(bye);
    if (i != 0) {
       fprintf(stderr, "cannot set exit function\n");
       return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

SEE ALSO

_exit(2), exit(3), on_exit(3)


getenv(3)

GETENV

Section: Linux Programmer's Manual (3)
Updated: 1993-04-03 Return to Main Contents

NAME

getenv - get an environment variable

SYNOPSIS

#include <stdlib.h>

char *getenv(const char *name);

DESCRIPTION

The getenv() function searches the environment list for a string that matches the string pointed to by name. The strings are of the form name = value.

RETURN VALUE

The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89, C99.

SEE ALSO

clearenv(3), putenv(3), setenv(3), unsetenv(3), environ(7)


gethostbyaddr (3)

 Continue to this page.


isinf (3)

 Continue to this page.


index(3)

INDEX

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

index, rindex - locate character in string

SYNOPSIS

#include <strings.h>

char *index(const char *s, int c);

char *rindex(const char *s, int c);

DESCRIPTION

The index() function returns a pointer to the first occurrence of the character c in the string s.

The rindex() function returns a pointer to the last occurrence of the character c in the string s.

The terminating NULL character is considered to be a part of the strings.

RETURN VALUE

The index() and rindex() functions return a pointer to the matched character or NULL if the character is not found.

CONFORMING TO

4.3BSD; marked as LEGACY in POSIX.1-2001.

SEE ALSO

memchr(3), strchr(3), strpbrk(3), strrchr(3), strsep(3), strspn(3), strstr(3), strtok(3)


inet(3)

INET

Section: Linux Programmer's Manual (3)
Updated: 2001-07-25 Return to Main Contents

NAME

inet_aton, inet_addr, inet_network, inet_ntoa, inet_makeaddr, inet_lnaof, inet_netof - Internet address manipulation routines

SYNOPSIS

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int inet_aton(const char *cp, struct in_addr *inp);

in_addr_t inet_addr(const char *cp);

in_addr_t inet_network(const char *cp);

char *inet_ntoa(struct in_addr in);

struct in_addr inet_makeaddr(int net, int host);

in_addr_t inet_lnaof(struct in_addr in);

in_addr_t inet_netof(struct in_addr in);

DESCRIPTION

inet_aton() converts the Internet host address cp from the standard numbers-and-dots notation into binary data and stores it in the structure that inp points to. inet_aton() returns non-zero if the address is valid, zero if not.

The inet_addr() function converts the Internet host address cp from numbers-and-dots notation into binary data in network byte order. If the input is invalid, INADDR_NONE (usually -1) is returned. This is an obsolete interface to inet_aton(), described immediately above; it is obsolete because -1 is a valid address (255.255.255.255), and inet_aton() provides a cleaner way to indicate error return.

The inet_network() function extracts a number in host byte order suitable for use as an Internet address from cp, which is a string in numbers-and-dots notation. If the input is invalid, -1 is returned.

The inet_ntoa() function converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.

The inet_makeaddr() function makes an Internet host address in network byte order by combining the network number net with the local address host in network net, both in local host byte order.

The inet_lnaof() function returns the local host address part of the Internet address in. The local host address is returned in local host byte order.

The inet_netof() function returns the network number part of the Internet Address in. The network number is returned in local host byte order.

The structure in_addr as used in inet_ntoa(), inet_makeaddr(), inet_lnoaf() and inet_netof() is defined in netinet/in.h as:

struct in_addr {
    unsigned long int s_addr;
}

Note that on the i80x86 the host byte order is Least Significant Byte first (little endian), whereas the network byte order, as used on the Internet, is Most Significant Byte first (big endian).

CONFORMING TO

4.3BSD. inet_addr(), inet_aton(), and inet_ntoa() are specified in POSIX.1-2001.

NOTES

When you using numbers-and-dots notation for addresses, be aware that each number will be interpreted as octal if preceded by a 0 and as hexadecimal if preceded by 0x. For example, inet_aton("226.000.000.037", &t) will interpret the address as 226.0.0.31 and not 226.0.0.37.

Glibc Notes

In order to expose the declaration of inet_aton(), one of the feature test macros _BSD_SOURCE, _SVID_SOURCE, or _GNU_SOURCE must be defined.

SEE ALSO

gethostbyname(3), getnetent(3), inet_ntop(3), inet_pton(3), hosts(5), networks(5)


inet_aton (3)

 Continue to this page.


res_search (3)

 Continue to this page.


rtnetlink(3)

RTNETLINK

Section: Linux Programmer's Manual (3)
Updated: 1999-05-14 Return to Main Contents

NAME

rtnetlink - Macros to manipulate rtnetlink messages

SYNOPSIS

#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/socket.h>

rtnetlink_socket = socket(PF_NETLINK, int socket_type, NETLINK_ROUTE);

int RTA_OK(struct rtattr *rta, int rtabuflen);

void *RTA_DATA(struct rtattr *rta);

unsigned int RTA_PAYLOAD(struct rtattr *rta);

struct rtattr *RTA_NEXT(struct rtattr *rta, unsigned int rtabuflen);

unsigned int RTA_LENGTH(unsigned int length);

unsigned int RTA_SPACE(unsigned int length);

DESCRIPTION

All rtnetlink(7) messages consist of a netlink(7) message header and appended attributes. The attributes should be only manipulated using the macros provided here.

RTA_OK(rta, attrlen) returns true if rta points to a valid routing attribute; attrlen is the running length of the attribute buffer. When not true then you must assume there are no more attributes in the message, even if attrlen is non-zero.
RTA_DATA(rta) returns a pointer to the start of this attribute's data.
RTA_PAYLOAD(rta) returns the length of this attribute's data.
RTA_NEXT(rta, attrlen) gets the next attribute after rta. Calling this macro will update attrlen. You should use RTA_OK to check for the validity of the returned pointer.
RTA_LENGTH(len) returns the length which is required for len bytes of data plus the header.
RTA_SPACE(len) returns the amount of space which will be needed in the message with len bytes of data.

BUGS

This manual page is lacking and incomplete.

EXAMPLE

Creating a rtnetlink message to set a MTU of a device.

    struct {
        struct nlmsghdr  nh;
        struct ifinfomsg if;
        char             attrbuf[512];
    } req;

    struct rtattr *rta;
    unsigned int mtu = 1000;

    int rtnetlink_sk = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);

    memset(&req, 0, sizeof(req));
    req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
    req.nh.nlmsg_flags = NLM_F_REQUEST;
    req.nh.nlmsg_type = RTML_NEWLINK;
    req.if.ifi_family = AF_UNSPEC;
    req.if.ifi_index = INTERFACE_INDEX;
    req.if.ifi_change = 0xffffffff; /* ???*/
    rta = (struct rtattr *)(((char *) &req) +
                                  NLMSG_ALIGN(n->nlmsg_len));
    rta->rta_type = IFLA_MTU;
    rta->rta_len = sizeof(unsigned int);
    req.n.nlmsg_len = NLMSG_ALIGN(req.n.nlmsg_len) +
                                  RTA_LENGTH(sizeof(mtu));
    memcpy(RTA_DATA(rta), &mtu, sizeof(mtu));
    send(rtnetlink_sk, &req, req.n.nlmsg_len);

SEE ALSO

netlink(3), netlink(7), rtnetlink(7)


setbuffer (3)

 Continue to this page.


regerror (3)

 Continue to this page.


fscanf (3)

 Continue to this page.


getchar (3)

 Continue to this page.


getcwd(3)

GETCWD

Section: Linux Programmer's Manual (3)
Updated: 2002-04-22 Return to Main Contents

NAME

getcwd, get_current_dir_name, getwd - Get current working directory

SYNOPSIS

#include <unistd.h>

char *getcwd(char *buf, size_t size);

#define _BSD_SOURCE     /* Or: #define _XOPEN_SOURCE 500 */
#include <unistd.h>

char *getwd(char *buf);

#define _GNU_SOURCE
#include <unistd.h>

char *get_current_dir_name(void);

DESCRIPTION

The getcwd() function copies an absolute pathname of the current working directory to the array pointed to by buf, which is of length size.

If the current absolute pathname would require a buffer longer than size elements, NULL is returned, and errno is set to ERANGE; an application should check for this error, and allocate a larger buffer if necessary.

If buf is NULL, the behavior of getcwd() is undefined.

As an extension to the POSIX.1-2001 standard, Linux (libc4, libc5, glibc) getcwd() allocates the buffer dynamically using malloc(3) if buf is NULL on call. In this case, the allocated buffer has the length size unless size is zero, when buf is allocated as big as necessary. It is possible (and, indeed, advisable) to free(3) the buffers if they have been obtained this way.

get_current_dir_name(), will malloc(3) an array big enough to hold the current directory name. If the environment variable PWD is set, and its value is correct, then that value will be returned.

getwd(), does not malloc(3) any memory. The buf argument should be a pointer to an array at least PATH_MAX bytes long. getwd() does only return the first PATH_MAX bytes of the actual pathname. Note that PATH_MAX need not be a compile-time constant; it may depend on the filesystem and may even be unlimited. For portability and security reasons, use of getwd() is deprecated.

RETURN VALUE

NULL on failure with errno set accordingly, and buf on success. The contents of the array pointed to by buf is undefined on error.

ERRORS

EACCES
Permission to read or search a component of the filename was denied.
EFAULT
buf points to a bad address.
EINVAL
The size argument is zero and buf is not a null pointer.
ENOENT
The current working directory has been unlinked.
ERANGE
The size argument is less than the length of the working directory name. You need to allocate a bigger array and try again.

CONFORMING TO

getcwd() conforms to POSIX.1-2001. getwd() is present in POSIX.1-2001, but marked LEGACY. get_current_dir_name() is a GNU extension.

NOTES

Under Linux, the function getcwd() is a system call (since 2.1.92). On older systems it would query /proc/self/cwd. If both system call and proc file system are missing, a generic implementation is called. Only in that case can these calls fail under Linux with EACCES.

These functions are often used to save the location of the current working directory for the purpose of returning to it later. Opening the current directory (".") and calling fchdir(2) to return is usually a faster and more reliable alternative when sufficiently many file descriptors are available, especially on platforms other than Linux.

SEE ALSO

chdir(2), fchdir(2), open(2), unlink(2), free(3), malloc(3), feature_test_macros(7)


tzset(3)

TZSET

Section: Linux Programmer's Manual (3)
Updated: 2001-11-13 Return to Main Contents

NAME

tzset, tzname, timezone, daylight - initialize time conversion information

SYNOPSIS

#include <time.h>

void tzset (void);

extern char *tzname[2];
extern long timezone;
extern int daylight;

DESCRIPTION

The tzset() function initializes the tzname variable from the TZ environment variable. This function is automatically called by the other time conversion functions that depend on the time zone. In a SysV-like environment it will also set the variables timezone (seconds West of GMT) and daylight (0 if this time zone does not have any daylight saving time rules, non-zero if there is a time during the year when daylight saving time applies).

If the TZ variable does not appear in the environment, the tzname variable is initialized with the best approximation of local wall clock time, as specified by the tzfile(5)-format file localtime found in the system timezone directory (see below). (One also often sees /etc/localtime used here, a symlink to the right file in the system timezone directory.)

If the TZ variable does appear in the environment but its value is empty or its value cannot be interpreted using any of the formats specified below, Coordinated Universal Time (UTC) is used.

The value of TZ can be one of three formats. The first format is used when there is no daylight saving time in the local time zone:

std offset

The std string specifies the name of the time zone and must be three or more alphabetic characters. The offset string immediately follows std and specifies the time value to be added to the local time to get Coordinated Universal Time (UTC). The offset is positive if the local time zone is west of the Prime Meridian and negative if it is east. The hour must be between 0 and 24, and the minutes and seconds 0 and 59.

The second format is used when there is daylight saving time:

std offset dst [offset],start[/time],end[/time]

There are no spaces in the specification. The initial std and offset specify the standard time zone, as described above. The dst string and offset specify the name and offset for the corresponding daylight saving time zone. If the offset is omitted, it default to one hour ahead of standard time.

The start field specifies when daylight saving time goes into effect and the end field specifies when the change is made back to standard time. These fields may have the following formats:

Jn
This specifies the Julian day with n between 1 and 365. February 29 is never counted even in leap years.
n
This specifies the Julian day with n between 1 and 365. February 29 is counted in leap years.
Mm.w.d
This specifies day d (0 <= d <= 6) of week w (1 <= w <= 5) of month m (1 <= m <= 12). Week 1 is the first week in which day d occurs and week 5 is the last week in which day d occurs. Day 0 is a Sunday.

The time fields specify when, in the local time currently in effect, the change to the other time occurs. If omitted, the default is 02:00:00.

Here is an example for New Zealand, where the standard time (NZST) is 12 hours ahead of UTC, and daylight saving time (NZDT), 13 hours ahead of UTC, runs from the first Sunday in October to the third Sunday in March, and the changeovers happen at the default time of 02:00:00:

    TZ="NZST-12.00:00NZDT-13:00:00,M10.1.0,M3.3.0"

The third format specifies that the time zone information should be read from a file:

:[filespec]

If the file specification filespec is omitted, the time zone information is read from the file localtime in the system timezone directory, which nowadays usually is /usr/share/zoneinfo. This file is in tzfile(5) format. If filespec is given, it specifies another tzfile(5)-format file to read the time zone information from. If filespec does not begin with a `/', the file specification is relative to the system timezone directory.

Here's an example, once more for New Zealand:

    TZ=":Pacific/Auckland"

FILES

The system time zone directory used depends on the (g)libc version. Libc4 and libc5 use /usr/lib/zoneinfo, and, since libc-5.4.6, when this doesn't work, will try /usr/share/zoneinfo. Glibc2 will use the environment variable TZDIR, when that exists. Its default depends on how it was installed, but normally is /usr/share/zoneinfo.

This timezone directory contains the files

localtime      local time zone file
posixrules     rules for POSIX-style TZ's

Often /etc/localtime is a symlink to the file localtime or to the correct time zone file in the system time zone directory.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD

NOTES

Note that the variable daylight does not indicate that daylight saving time applies right now. It used to give the number of some algorithm (see the variable tz_dsttime in gettimeofday(2)). It has been obsolete for many years but is required by SUSv2.

4.3BSD had a function char *timezone(zone, dst) that returned the name of the time zone corresponding to its first argument (minutes West of GMT). If the second argument was 0, the standard name was used, otherwise the daylight saving time version.

SEE ALSO

date(1), gettimeofday(2), time(2), ctime(3), getenv(3), tzfile(5)


confstr(3)

CONFSTR

Section: Linux Programmer's Manual (3)
Updated: 1993-04-17 Return to Main Contents

NAME

confstr - get configuration dependent string variables

SYNOPSIS

#define _POSIX_C_SOURCE 2
or
#define _XOPEN_SOURCE

#include <unistd.h>

size_t confstr(int name, char *buf, size_t len);

DESCRIPTION

confstr() gets the value of configuration-dependent string variables.

The name argument is the system variable to be queried. The following variables are supported:

_CS_GNU_LIBC_VERSION (GNU C library only; since glibc 2.3.2)
A string which identifies the GNU C library version on this system (e.g, "glibc 2.3.4").
_CS_GNU_LIBPTHREAD_VERSION (GNU C library only; since glibc 2.3.2)
A string which identifies the POSIX implementation supplied by this C library (e.g, "NPTL 2.3.4" or "linuxthreads-0.10").
_CS_PATH
A value for the PATH variable which indicates where all the POSIX.2 standard utilities can be found.

If buf is not NULL and len is not zero, confstr() copies the value of the string to buf truncated to len - 1 characters if necessary, with a null byte ('\0') as terminator. This can be detected by comparing the return value of confstr() against len.

If len is zero and buf is NULL, confstr() just returns the value as defined below.

RETURN VALUE

If name is a valid configuration variable, confstr() returns the number of bytes (including the terminating null byte) that would be required to hold the entire value of that variable. This value may be greater than len, which means that the value in buf is truncated.

If name is a valid configuration variable, but that variable does not have a value, then confstr() returns 0. If name does not correspond to a valid configuration variable, confstr() returns 0, and errno is set to EINVAL.

ERRORS

EINVAL
If the value of name is invalid.

CONFORMING TO

POSIX.1-2001

EXAMPLE

The following code fragment determines the path where to find the POSIX.2 system utilities:

char *pathbuf; size_t n;

n = confstr(_CS_PATH,NULL,(size_t) 0);
if ((pathbuf = malloc(n)) == NULL) abort();
confstr(_CS_PATH, pathbuf, n);

SEE ALSO

sh(1), exec(3), system(3), feature_test_macros(7)


fgetgrent(3)

FGETGRENT

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

fgetgrent - get group file entry

SYNOPSIS

#include <stdio.h>
#include <sys/types.h>
#include <grp.h>

struct group *fgetgrent(FILE *stream);

DESCRIPTION

The fgetgrent() function returns a pointer to a structure containing the group information from the file stream. The first time it is called it returns the first entry; thereafter, it returns successive entries. The file stream must have the same format as /etc/group.

The group structure is defined in <grp.h> as follows:

struct group {
        char    *gr_name;        /* group name */
        char    *gr_passwd;      /* group password */
        gid_t   gr_gid;          /* group ID */
        char    **gr_mem;        /* group members */
};

RETURN VALUE

The fgetgrent() function returns the group information structure, or NULL if there are no more entries or an error occurs.

ERRORS

ENOMEM
Insufficient memory to allocate group information structure.

CONFORMING TO

SVr4

SEE ALSO

endgrent(3), fgetgrent_r(3), getgrent(3), getgrgid(3), getgrnam(3), putgrent(3), setgrent(3)


fgetpos (3)

 Continue to this page.


finite(3)

FINITE

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

finite, finitef, finitel, isinf, isinff, isinfl, isnan, isnanf, isnanl - BSD floating point classification functions

SYNOPSIS

#define _BSD_SOURCE

#include <math.h>

int finite(double x);

int finitef(float x);

int finitel(long double x);

int isinf(double x);

int isinff(float x);

int isinfl(long double x);

int isnan(double x);

int isnanf(float x);

int isnanl(long double x);

DESCRIPTION

The finite() functions return a non-zero value if x is neither infinite nor a "not-a-number" (NaN) value, and 0 otherwise.

The isnan() functions return a non-zero value if x is a NaN value, and 0 otherwise.

The isinf() functions return 1 if x is plus infinity, -1 is x is minus infinity, and 0 otherwise.

NOTES

Note that these functions are obsolete. C99 defines macros isfinite(), isinf() and isnan() (for all types) replacing them. Further note that the C99 isinf() has weaker guarantees on the return value. See fpclassify(3).

On a glibc system, these functions are declared by <math.h> when _BSD_SOURCE or _SVID_SOURCE or _GNU_SOURCE is defined. The isnan() functions will also be declared when _XOPEN_SOURCE is defined.

SEE ALSO

fpclassify(3), feature_test_macros(7)


floor(3)

FLOOR

Section: Linux Programmer's Manual (3)
Updated: 2001-05-31 Return to Main Contents

NAME

floor, floorf, floorl - largest integral value not greater than argument

SYNOPSIS

#include <math.h>

double floor(double x);

float floorf(float x);

long double floorl(long double x);

Link with -lm.

DESCRIPTION

These functions round x down to the nearest integer.

RETURN VALUE

The rounded integer value. If x is integral or infinite, x itself is returned.

ERRORS

No errors other than EDOM and ERANGE can occur. If x is NaN, then NaN is returned and errno may be set to EDOM.

CONFORMING TO

The floor() function conforms to SVr4, 4.3BSD, C89. The other functions are from C99.

NOTES

SUSv2 and POSIX.1-2001 contain text about overflow (which might set errno to ERANGE, or raise an exception). In practice, the result cannot overflow on any current machine, so this error-handling stuff is just nonsense. (More precisely, overflow can happen only when the maximum value of the exponent is smaller than the number of mantissa bits. For the IEEE-754 standard 32-bit and 64-bit floating point numbers the maximum value of the exponent is 128 (resp. 1024), and the number of mantissa bits is 24 (resp. 53).)

SEE ALSO

ceil(3), lrint(3), nearbyint(3), rint(3), round(3), trunc(3)


gcvt(3)

GCVT

Section: Linux Programmer's Manual (3)
Updated: 1993-03-29 Return to Main Contents

NAME

gcvt - convert a floating-point number to a string

SYNOPSIS

#include <stdlib.h>

char *gcvt(double number, size_t ndigit, char *buf);

DESCRIPTION

The gcvt() function converts number to a minimal length NULL terminated ASCII string and stores the result in buf. It produces ndigit significant digits in either printf(3) F format or E format.

RETURN VALUE

The gcvt() function returns the address of the string pointed to by buf.

CONFORMING TO

marked as LEGACY in POSIX.1-2001.

NOTES

This function is obsolete. Instead, sprintf(3) is recommended.

SEE ALSO

ecvt(3), fcvt(3), sprintf(3)


fabs(3)

FABS

Section: Linux Programmer's Manual (3)
Updated: 2001-06-07 Return to Main Contents

NAME

fabs, fabsf, fabsl - absolute value of floating-point number

SYNOPSIS

#include <math.h>

double fabs(double x);

float fabsf(float x);

long double fabsl(long double x);

Link with -lm.

DESCRIPTION

The fabs() functions return the absolute value of the floating-point number x.

ERRORS

No errors can occur.

CONFORMING TO

The fabs() function conforms to SVr4, POSIX.1-2001, 4.3BSD, C89. The other functions are from C99.

SEE ALSO

abs(3), ceil(3), cabs(3), floor(3), labs(3), rint(3)


fclose(3)

FCLOSE

Section: Linux Programmer's Manual (3)
Updated: 1993-11-29 Return to Main Contents

NAME

fclose - close a stream

SYNOPSIS

#include <stdio.h>

int fclose(FILE *fp);

DESCRIPTION

The fclose() function will flush the stream pointed to by fp (writing any buffered output data using fflush(3)) and close the underlying file descriptor.

RETURN VALUE

Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error. In either case any further access (including another call to fclose()) to the stream results in undefined behavior.

ERRORS

EBADF
The file descriptor underlying fp is not valid.

The fclose() function may also fail and set errno for any of the errors specified for the routines close(2), write(2) or fflush(3).

CONFORMING TO

C89, C99.

NOTES

Note that fclose() only flushes the user space buffers provided by the C library. To ensure that the data is physically stored on disk the kernel buffers must be flushed too, for example, with sync(2) or fsync(2).

SEE ALSO

close(2), fcloseall(3), fflush(3), fopen(3), setbuf(3)


fcvt (3)

 Continue to this page.


ferror(3)

FERROR

Section: Linux Programmer's Manual (3)
Updated: 2001-10-16 Return to Main Contents

NAME

clearerr, feof, ferror, fileno - check and reset stream status

SYNOPSIS

#include <stdio.h>

void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
int fileno(FILE *stream);

DESCRIPTION

The function clearerr() clears the end-of-file and error indicators for the stream pointed to by stream.

The function feof() tests the end-of-file indicator for the stream pointed to by stream, returning non-zero if it is set. The end-of-file indicator can only be cleared by the function clearerr().

The function ferror() tests the error indicator for the stream pointed to by stream, returning non-zero if it is set. The error indicator can only be reset by the clearerr() function.

The function fileno() examines the argument stream and returns its integer descriptor.

For non-locking counterparts, see unlocked_stdio(3).

ERRORS

These functions should not fail and do not set the external variable errno. (However, in case fileno() detects that its argument is not a valid stream, it must return -1 and set errno to EBADF.)

CONFORMING TO

The functions clearerr(), feof(), and ferror() conform to C89 and C99.

SEE ALSO

open(2), fdopen(3), stdio(3), unlocked_stdio(3)


fgetpwent(3)

FGETPWENT

Section: Linux Programmer's Manual (3)
Updated: 1996-05-17 Return to Main Contents

NAME

fgetpwent - get password file entry

SYNOPSIS

#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>

struct passwd *fgetpwent(FILE *stream);

DESCRIPTION

The fgetpwent() function returns a pointer to a structure containing the broken out fields of a line in the file stream. The first time it is called it returns the first entry; thereafter, it returns successive entries. The file stream must have the same format as /etc/passwd.

The passwd structure is defined in <pwd.h> as follows:

struct passwd {
    char   *pw_name;       /* user name */
    char   *pw_passwd;     /* user password */
    uid_t   pw_uid;        /* user ID */
    gid_t   pw_gid;        /* group ID */
    char   *pw_gecos;      /* real name */
    char   *pw_dir;        /* home directory */
    char   *pw_shell;      /* shell program */
};

RETURN VALUE

The fgetpwent() function returns the passwd structure, or NULL if there are no more entries or an error occurs.

ERRORS

ENOMEM
Insufficient memory to allocate passwd structure.

FILES

/etc/passwd
password database file

CONFORMING TO

SVr4

SEE ALSO

endpwent(3), fgetpwent_r(3), getpw(3), getpwent(3), getpwnam(3), getpwuid(3), putpwent(3), setpwent(3), passwd(5)


stdarg(3)

STDARG

Section: Linux Programmer's Manual (3)
Updated: 2001-10-14 Return to Main Contents

NAME

stdarg, va_start, va_arg, va_end, va_copy - variable argument lists

SYNOPSIS

#include <stdarg.h>

void va_start(va_list ap, last);
type va_arg(va_list ap, type);
void va_end(va_list ap);
void va_copy(va_list dest, va_list src);

DESCRIPTION

A function may be called with a varying number of arguments of varying types. The include file <stdarg.h> declares a type va_list and defines three macros for stepping through a list of arguments whose number and types are not known to the called function.

The called function must declare an object of type va_list which is used by the macros va_start(), va_arg(), and va_end().

va_start

The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.

The parameter last is the name of the last parameter before the variable argument list, that is, the last parameter of which the calling function knows the type.

Because the address of this parameter may be used in the va_start() macro, it should not be declared as a register variable, or as a function or an array type.

va_arg

The va_arg() macro expands to an expression that has the type and value of the next argument in the call. The parameter ap is the va_list ap initialized by va_start(). Each call to va_arg() modifies ap so that the next call returns the next argument. The parameter type is a type name specified so that the type of a pointer to an object that has the specified type can be obtained simply by adding a * to type.

The first use of the va_arg() macro after that of the va_start() macro returns the argument after last. Successive invocations return the values of the remaining arguments.

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

If ap is passed to a function that uses va_arg(ap,type) then the value of ap is undefined after the return of that function.

va_end

Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function. After the call va_end(ap) the variable ap is undefined. Multiple traversals of the list, each bracketed by va_start() and va_end() are possible. va_end() may be a macro or a function.

va_copy

An obvious implementation would have a va_list be a pointer to the stack frame of the variadic function. In such a setup (by far the most common) there seems nothing against an assignment
    va_list aq = ap;
Unfortunately, there are also systems that make it an array of pointers (of length 1), and there one needs
    va_list aq;
    *aq = *ap;
Finally, on systems where parameters are passed in registers, it may be necessary for va_start() to allocate memory, store the parameters there, and also an indication of which parameter is next, so that va_arg() can step through the list. Now va_end() can free the allocated memory again. To accommodate this situation, C99 adds a macro va_copy(), so that the above assignment can be replaced by
    va_list aq;
    va_copy(aq, ap);
    ...
    va_end(aq);
Each invocation of va_copy() must be matched by a corresponding invocation of va_end() in the same function. Some systems that do not supply va_copy() have __va_copy instead, since that was the name used in the draft proposal.

CONFORMING TO

The va_start(), va_arg(), and va_end() macros conform to C89. C99 defines the va_copy() macro.

NOTES

These macros are not compatible with the historic macros they replace. A backward compatible version can be found in the include file varargs.h.

The historic setup is:

#include <varargs.h>

void
foo(va_alist)
    va_dcl
{
    va_list ap;

    va_start(ap);
    while(...) {
        ...
        x = va_arg(ap, type);
        ...
    }
    va_end(ap);
}
On some systems, va_end contains a closing '}' matching a '{' in va_start, so that both macros must occur in the same function, and in a way that allows this.

BUGS

Unlike the varargs macros, the stdarg macros do not permit programmers to code a function with no fixed arguments. This problem generates work mainly when converting varargs code to stdarg code, but it also creates difficulties for variadic functions that wish to pass all of their arguments on to a function that takes a va_list argument, such as vfprintf(3).

EXAMPLE

The function foo takes a string of format characters and prints out the argument associated with each format character based on the type.

#include <stdio.h>
#include <stdarg.h>

void
foo(char *fmt, ...)
{
    va_list ap;
    int d;
    char c, *s;

    va_start(ap, fmt);
    while (*fmt)
        switch(*fmt++) {
        case 's':              /* string */
            s = va_arg(ap, char *);
            printf("string %s\n", s);
            break;
        case 'd':              /* int */
            d = va_arg(ap, int);
            printf("int %d\n", d);
            break;
        case 'c':              /* char */
            /* need a cast here since va_arg only
               takes fully promoted types */
            c = (char) va_arg(ap, int);
            printf("char %c\n", c);
            break;
        }
    va_end(ap);
}


wcstombs(3)

WCSTOMBS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcstombs - convert a wide-character string to a multibyte string

SYNOPSIS

#include <stdlib.h>

size_t wcstombs(char *dest, const wchar_t *src, size_t n);

DESCRIPTION

If dest is not a NULL pointer, the wcstombs() function converts the wide-character string src to a multibyte string starting at dest. At most n bytes are written to dest. The conversion starts in the initial state. The conversion can stop for three reasons:

1. A wide character has been encountered that can not be represented as a multibyte sequence (according to the current locale). In this case (size_t)(-1) is returned.

2. The length limit forces a stop. In this case the number of bytes written to dest is returned, but the shift state at this point is lost.

3. The wide-character string has been completely converted, including the terminating L'\0'. In this case the conversion ends in the initial state. The number of bytes written to dest, excluding the terminating '\0' byte, is returned.

The programmer must ensure that there is room for at least n bytes at dest.

If dest is NULL, n is ignored, and the conversion proceeds as above, except that the converted bytes are not written out to memory, and that no length limit exists.

In order to avoid the case 2 above, the programmer should make sure n is greater or equal to wcstombs(NULL,src,0)+1.

RETURN VALUE

The wcstombs() function returns the number of bytes that make up the converted part of multibyte sequence, not including the terminating null byte. If a wide character was encountered which could not be converted, (size_t)(-1) is returned.

CONFORMING TO

C99.

NOTES

The behavior of wcstombs() depends on the LC_CTYPE category of the current locale.

The function wcsrtombs(3) provides a thread safe interface to the same functionality.

SEE ALSO

wcsrtombs(3)


atof(3)

ATOF

Section: Linux Programmer's Manual (3)
Updated: 1993-03-29 Return to Main Contents

NAME

atof - convert a string to a double

SYNOPSIS

#include <stdlib.h>

double atof(const char *nptr);

DESCRIPTION

The atof() function converts the initial portion of the string pointed to by nptr to double. The behavior is the same as

strtod(nptr, (char **) NULL);

except that atof() does not detect errors.

RETURN VALUE

The converted value.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89, C99.

SEE ALSO

atoi(3), atol(3), strtod(3), strtol(3), strtoul(3)


vsnprintf (3)

 Continue to this page.


inet_lnaof (3)

 Continue to this page.


inet_makeaddr (3)

 Continue to this page.


setlinebuf (3)

 Continue to this page.


fsetpos (3)

 Continue to this page.


siginterrupt(3)

SIGINTERRUPT

Section: Linux Programmer's Manual (3)
Updated: 1993-04-13 Return to Main Contents

NAME

siginterrupt - allow signals to interrupt system calls

SYNOPSIS

#include <signal.h>

int siginterrupt(int sig, int flag);

DESCRIPTION

The siginterrupt() function changes the restart behavior when a system call is interrupted by the signal sig. If the flag argument is false (0), then system calls will be restarted if interrupted by the specified signal sig. This is the default behavior in Linux. However, when a new signal handler is specified with the signal(2) function, the system call is interrupted by default.

If the flags argument is true (1) and no data has been transferred, then a system call interrupted by the signal sig will return -1 and the global variable errno will be set to EINTR.

If the flags argument is true (1) and data transfer has started, then the system call will be interrupted and will return the actual amount of data transferred.

RETURN VALUE

The siginterrupt() function returns 0 on success, or -1 if the signal number sig is invalid.

ERRORS

EINVAL
The specified signal number is invalid.

CONFORMING TO

4.3BSD, POSIX.1-2001.

SEE ALSO

signal(2)


sigaddset (3)

 Continue to this page.


sigdelset (3)

 Continue to this page.


sin(3)

SIN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

sin, sinf, sinl - sine function

SYNOPSIS

#include <math.h>

double sin(double x);

float sinf(float x);

long double sinl(long double x);

Link with -lm.

DESCRIPTION

The sin() function returns the sine of x, where x is given in radians.

RETURN VALUE

The sin() function returns a value between -1 and 1.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), csin(3), cos(3), tan(3)


strchr(3)

STRCHR

Section: Linux Programmer's Manual (3)
Updated: 2006-05-19 Return to Main Contents

NAME

strchr, strrchr, strchrnul - locate character in string

SYNOPSIS

#include <string.h>

char *strchr(const char *s, int c);

char *strrchr(const char *s, int c);

#define _GNU_SOURCE
#include <string.h>

char *strchrnul(const char *s, int c);

DESCRIPTION

The strchr() function returns a pointer to the first occurrence of the character c in the string s.

The strrchr() function returns a pointer to the last occurrence of the character c in the string s.

The strchrnul() function is like strchr() except that if c is not found in s, then it returns a pointer to the null byte at the end of s, rather than NULL.

Here "character" means "byte"; these functions do not work with wide or multi-byte characters.

RETURN VALUE

The strchr() and strrchr() functions return a pointer to the matched character or NULL if the character is not found.

The strchrnul() function returns a pointer to the matched character, or a pointer to the null byte at the end of s (i.e., s+strlen(s)) if the character is not found.

CONFORMING TO

strchr() and strrchr() are in SVr4, 4.3BSD, C89, C99. strchrnul() is a GNU extension.

SEE ALSO

index(3), memchr(3), rindex(3), strlen(3), strpbrk(3), strsep(3), strspn(3), strstr(3), strtok(3), wcschr(3), wcsrchr(3), feature_test_macros(7)


strcmp(3)

STRCMP

Section: Linux Programmer's Manual (3)
Updated: 1993-04-11 Return to Main Contents

NAME

strcmp, strncmp - compare two strings

SYNOPSIS

#include <string.h>

int strcmp(const char *s1, const char *s2);

int strncmp(const char *s1, const char *s2, size_t n);

DESCRIPTION

The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

The strncmp() function is similar, except it only compares the first (at most) n characters of s1 and s2.

RETURN VALUE

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

SEE ALSO

bcmp(3), memcmp(3), strcasecmp(3), strcoll(3), strncasecmp(3), wcscmp(3), wcsncmp(3)


strcoll(3)

STRCOLL

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strcoll - compare two strings using the current locale

SYNOPSIS

#include <string.h>

int strcoll(const char *s1, const char *s2);

DESCRIPTION

The strcoll() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2. The comparison is based on strings interpreted as appropriate for the program's current locale for category LC_COLLATE. (See setlocale(3)).

RETURN VALUE

The strcoll() function returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2, when both are interpreted as appropriate for the current locale.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

NOTES

In the "POSIX" or "C" locales strcoll() is equivalent to strcmp(3).

SEE ALSO

bcmp(3), memcmp(3), setlocale(3), strcasecmp(3), strcmp(3), strxfrm(3)


wctomb(3)

WCTOMB

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wctomb - convert a wide character to a multibyte sequence

SYNOPSIS

#include <stdlib.h>

int wctomb(char *s, wchar_t wc);

DESCRIPTION

If s is not NULL, the wctomb() function converts the wide character wc to its multibyte representation and stores it at the beginning of the character array pointed to by s. It updates the shift state, which is stored in a static anonymous variable only known to the wctomb function, and returns the length of said multibyte representation, that is, the number of bytes written at s.

The programmer must ensure that there is room for at least MB_CUR_MAX bytes at s.

If s is NULL, the wctomb() function resets the shift state, only known to this function, to the initial state, and returns non-zero if the encoding has non-trivial shift state, or zero if the encoding is stateless.

RETURN VALUE

If s is not NULL, the wctomb() function returns the number of bytes that have been written to the byte array at s. If wc can not be represented as a multibyte sequence (according to the current locale), -1 is returned.

If s is NULL, the wctomb() function returns non-zero if the encoding has non-trivial shift state, or zero if the encoding is stateless.

CONFORMING TO

C99.

NOTES

The behavior of wctomb() depends on the LC_CTYPE category of the current locale.

This function is not multi-thread safe. The function wcrtomb(3) provides a better interface to the same functionality.

SEE ALSO

MB_CUR_MAX(3), wcrtomb(3), wcstombs(3)


bindresvport(3)

BINDRESVPORT

Section: Linux Programmer's Manual (3)
Updated: 2007-05-31 Return to Main Contents

NAME

bindresvport - bind a socket to a privileged IP port

SYNOPSIS

#include <sys/types.h>
#include <netinet/in.h>

int bindresvport(int sd, struct sockaddr_in **sin);

DESCRIPTION

bindresvport() is used to bind a socket descriptor to a privileged IP port, that is, a port number in the range 0-1023.

If in->sin_port is 0 then an anonymous port in the range 600 to 1023 be chosen. If the bind(2) performed by bindresvport() is successful, then sin->sin_port returns the port number actually allocated.

sin can be NULL, in which case sin->sin_family is implicitly taken to be AF_INET, and an anonymous port is allocated (as above). However, in this case, bindresvport() has no way to return the port number actually allocated.

RETURN VALUE

bindresvport() returns 0 if it is successful, otherwise -1 is returned and errno set to indicate the cause of the error.

ERRORS

bindresvport() can fail for any of the same reasons as bind(2).

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs, Solaris, and many other systems.

NOTES

Only root can bind to a privileged port; this call will fail for any other users. In addition, the following error may occur:

EPFNOSUPPORT
sin is not NULL and sin->sin_family is not AF_INET.

SEE ALSO

bind(2)


vsprintf (3)

 Continue to this page.


ceil(3)

CEIL

Section: Linux Programmer's Manual (3)
Updated: 2001-05-31 Return to Main Contents

NAME

ceil, ceilf, ceill - ceiling function: smallest integral value not less than argument

SYNOPSIS

#include <math.h>

double ceil(double x);

float ceilf(float x);

long double ceill(long double x);

Link with -lm.

DESCRIPTION

These functions round x up to the nearest integer.

RETURN VALUE

The rounded integer value. If x is integral or infinite, x itself is returned.

ERRORS

No errors other than EDOM and ERANGE can occur. If x is NaN, then NaN is returned and errno may be set to EDOM.

CONFORMING TO

The ceil() function conforms to SVr4, POSIX.1-2001, 4.3BSD, C89, C99. The other functions are from C99.

NOTES

SUSv2 and POSIX.1-2001 contain text about overflow (which might set errno to ERANGE, or raise an exception). In practice, the result cannot overflow on any current machine, so this error-handling stuff is just nonsense. (More precisely, overflow can happen only when the maximum value of the exponent is smaller than the number of mantissa bits. For the IEEE-754 standard 32-bit and 64-bit floating point numbers the maximum value of the exponent is 128 (resp. 1024), and the number of mantissa bits is 24 (resp. 53).)

SEE ALSO

floor(3), lrint(3), nearbyint(3), rint(3), round(3), trunc(3)


updwtmp(3)

UPDWTMP

Section: Linux Programmer's Manual (3)
Updated: 2003-07-18 Return to Main Contents

NAME

updwtmp, logwtmp - append an entry to the wtmp file

SYNOPSIS

#include <utmp.h>

void updwtmp(const char *wtmp_file, const struct utmp *ut);

void logwtmp(const char *line, const char *name, const char *host);

DESCRIPTION

updwtmp() appends the utmp structure ut to the wtmp file.

logwtmp() constructs a utmp structure using line, name, host, current time and current process ID. Then it calls updwtmp() to append the structure to the utmp file.

FILES

/var/log/wtmp
database of past user logins

CONFORMING TO

Not in POSIX.1-2001. Present on Solaris, NetBSD, and perhaps other systems.

AVAILABILITY

Both functions are available under glibc2, but not under libc5. However, logwtmp() used to occur in the old libbsd. These days, the logwtmp() function is included in libutil. (Hence you'll need to add -lutil to your compiler command line to get it.)

SEE ALSO

wtmp(5)


usleep(3)

USLEEP

Section: Linux Programmer's Manual (3)
Updated: 2007-02-01 Return to Main Contents

NAME

usleep - suspend execution for microsecond intervals

SYNOPSIS

#define _XOPEN_SOURCE 500     /* Or: #define _BSD_SOURCE */

#include <unistd.h>

int usleep(useconds_t usec);

DESCRIPTION

The usleep() function suspends execution of the calling process for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.

RETURN VALUE

0 on success, -1 on error.

ERRORS

EINTR
Interrupted by a signal.
EINVAL
usec is not smaller than 1000000. (On systems where that is considered an error.)

CONFORMING TO

4.3BSD, POSIX.1-2001. POSIX.1-2001 declares this function obsolete; use nanosleep(2) instead.

On the original BSD implementation, and in glibc before version 2.2.2, the return type of this function is void. The POSIX version returns int, and this is also the prototype used since glibc 2.2.2.

Only the EINVAL error return is documented by SUSv2.

NOTES

The type useconds_t is an unsigned integer type capable of holding integers in the range [0,1000000]. Programs will be more portable if they never mention this type explicitly. Use

#include <unistd.h>
...
    unsigned int usecs;
.
    usleep(usecs);

The interaction of this function with the SIGALRM signal, and with
other timer functions such as
alarm(2),

sleep(3),

nanosleep(2),

setitimer(2),

timer_create(3),

timer_delete(3),

timer_getoverrun(3),

timer_gettime(3),

timer_settime(3),

ualarm(3)

is unspecified.

SEE ALSO

alarm(2), getitimer(2), nanosleep(2), select(2), setitimer(2), ualarm(3), sleep(3), feature_test_macros(7), time(7)


sethostent (3)

 Continue to this page.


closedir(3)

CLOSEDIR

Section: Linux Programmer's Manual (3)
Updated: 1995-06-11 Return to Main Contents

NAME

closedir - close a directory

SYNOPSIS

#include <sys/types.h>

#include <dirent.h>

int closedir(DIR *dir);

DESCRIPTION

The closedir() function closes the directory stream associated with dir. The directory stream descriptor dir is not available after this call.

RETURN VALUE

The closedir() function returns 0 on success. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
Invalid directory stream descriptor dir.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD

SEE ALSO

close(2), opendir(3), readdir(3), rewinddir(3), scandir(3), seekdir(3), telldir(3)


fmod(3)

FMOD

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

fmod, fmodf, fmodl - floating-point remainder function

SYNOPSIS

#include <math.h>

double fmod(double x, double y);

float fmodf(float x, float y);

long double fmodl(long double x, long double y);

Link with -lm.

DESCRIPTION

The fmod() function computes the remainder of dividing x by y. The return value is x - n * y, where n is the quotient of x / y, rounded towards zero to an integer.

RETURN VALUE

The fmod() function returns the remainder, unless y is zero, when the function fails and errno is set.

ERRORS

EDOM
The denominator y is zero.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

remainder(3)


ctermid(3)

CTERMID

Section: Linux Programmer's Manual (3)
Updated: 1993-04-06 Return to Main Contents

NAME

ctermid - get controlling terminal name

SYNOPSIS

#include <stdio.h>

char *ctermid(char *s);

DESCRIPTION

ctermid() returns a string which is the pathname for the current controlling terminal for this process. If s is NULL, a static buffer is used, otherwise s points to a buffer used to hold the terminal pathname. The symbolic constant L_ctermid is the maximum number of characters in the returned pathname.

RETURN VALUE

The pointer to the pathname.

CONFORMING TO

Svr4, POSIX.1-2001.

BUGS

The path returned may not uniquely identify the controlling terminal; it may, for example, be /dev/tty.

It is not assured that the program can open the terminal.

SEE ALSO

ttyname(3)


setnetent (3)

 Continue to this page.


tcgetpgrp(3)

TCGETPGRP

Section: Linux Programmer's Manual (3)
Updated: 2003-01-28 Return to Main Contents

NAME

tcgetpgrp, tcsetpgrp - get and set terminal foreground process group

SYNOPSIS

#include <unistd.h>

pid_t tcgetpgrp(int fd);

int tcsetpgrp(int fd, pid_t pgrp);

DESCRIPTION

The function tcgetpgrp() returns the process group ID of the foreground process group on the terminal associated to fd, which must be the controlling terminal of the calling process.

The function tcsetpgrp() makes the process group with process group ID pgrp the foreground process group on the terminal associated to fd, which must be the controlling terminal of the calling process, and still be associated with its session. Moreover, pgrp must be a (nonempty) process group belonging to the same session as the calling process.

If tcsetpgrp() is called by a member of a background process group in its session, and the calling process is not blocking or ignoring SIGTTOU, a SIGTTOU signal is sent to all members of this background process group.

RETURN VALUE

When fd refers to the controlling terminal of the calling process, the function tcgetpgrp() will return the foreground process group ID of that terminal if there is one, and some value larger than 1 that is not presently a process group ID otherwise. When fd does not refer to the controlling terminal of the calling process, -1 is returned, and errno is set appropriately.

When successful, tcsetpgrp() returns 0. Otherwise, it returns -1, and errno is set appropriately.

ERRORS

EBADF
fd is not a valid file descriptor.
EINVAL
pgrp has an unsupported value.
ENOTTY
The calling process does not have a controlling terminal, or it has one but it is not described by fd, or, for tcsetpgrp(), this controlling terminal is no longer associated with the session of the calling process.
EPERM
pgrp has a supported value, but is not the process group ID of a process in the same session as the calling process.

CONFORMING TO

POSIX.1-2001.

NOTES

These functions are implemented via the TIOCGPGRP and TIOCSPGRP ioctls.

History

The ioctls appeared in 4.2BSD. The functions are POSIX inventions.

SEE ALSO

setpgid(2), setsid(2), credentials(7)


tcsendbreak (3)

 Continue to this page.


utmpname (3)

 Continue to this page.


siglongjmp (3)

 Continue to this page.


sigsetjmp (3)

 Continue to this page.


stdio(3)

STDIO

Section: Linux Programmer's Manual (3)
Updated: 2001-12-26 Return to Main Contents

NAME

stdio - standard input/output library functions

SYNOPSIS

#include <stdio.h>

FILE *stdin;
FILE *stdout;
FILE *stderr;

DESCRIPTION

The standard I/O library provides a simple and efficient buffered stream I/O interface. Input and output is mapped into logical data streams and the physical I/O characteristics are concealed. The functions and macros are listed below; more information is available from the individual man pages.

A stream is associated with an external file (which may be a physical device) by opening a file, which may involve creating a new file. Creating an existing file causes its former contents to be discarded. If a file can support positioning requests (such as a disk file, as opposed to a terminal) then a file position indicator associated with the stream is positioned at the start of the file (byte zero), unless the file is opened with append mode. If append mode is used, it is unspecified whether the position indicator will be placed at the start or the end of the file. The position indicator is maintained by subsequent reads, writes and positioning requests. All input occurs as if the characters were read by successive calls to the fgetc(3) function; all output takes place as if all characters were written by successive calls to the fputc(3) function.

A file is disassociated from a stream by closing the file. Output streams are flushed (any unwritten buffer contents are transferred to the host environment) before the stream is disassociated from the file. The value of a pointer to a FILE object is indeterminate after a file is closed (garbage).

A file may be subsequently reopened, by the same or another program execution, and its contents reclaimed or modified (if it can be repositioned at the start). If the main function returns to its original caller, or the exit(3) function is called, all open files are closed (hence all output streams are flushed) before program termination. Other methods of program termination, such as abort(3) do not bother about closing files properly.

At program startup, three text streams are predefined and need not be opened explicitly --- standard input (for reading conventional input), --- standard output (for writing conventional input), and standard error (for writing diagnostic output). These streams are abbreviated stdin,stdout and stderr. When opened, the standard error stream is not fully buffered; the standard input and output streams are fully buffered if and only if the streams do not to refer to an interactive device.

Output streams that refer to terminal devices are always line buffered by default; pending output to such streams is written automatically whenever an input stream that refers to a terminal device is read. In cases where a large amount of computation is done after printing part of a line on an output terminal, it is necessary to fflush(3) the standard output before going off and computing so that the output will appear.

The stdio library is a part of the library libc and routines are automatically loaded as needed by the compilers cc(1) and pc(1). The SYNOPSIS sections of the following manual pages indicate which include files are to be used, what the compiler declaration for the function looks like and which external variables are of interest.

The following are defined as macros; these names may not be re-used without first removing their current definitions with #undef: BUFSIZ, EOF, FILENAME_MAX, FOPEN_MAX, L_cuserid, L_ctermid, L_tmpnam, NULL, SEEK_END, SEEK_SET, SEE_CUR, TMP_MAX, clearerr, feof, ferror, fileno, getc, getchar, putc, putchar, stderr, stdin, stdout. Function versions of the macro functions feof, ferror, clearerr, fileno, getc, getchar, putc, and putchar exist and will be used if the macros definitions are explicitly removed.

List of Functions

Function
Description
clearerr
check and reset stream status
fclose
close a stream
fdopen
stream open functions
feof
check and reset stream status
ferror
check and reset stream status
fflush
flush a stream
fgetc
get next character or word from input stream
fgetpos
reposition a stream
fgets
get a line from a stream
fileno
return the integer descriptor of the argument stream
fopen
stream open functions
fprintf
formatted output conversion
fpurge
flush a stream
fputc
output a character or word to a stream
fputs
output a line to a stream
fread
binary stream input/output
freopen
stream open functions
fscanf
input format conversion
fseek
reposition a stream
fsetpos
reposition a stream
ftell
reposition a stream
fwrite
binary stream input/output
getc
get next character or word from input stream
getchar
get next character or word from input stream
gets
get a line from a stream
getw
get next character or word from input stream
mktemp
make temporary filename (unique)
perror
system error messages
printf
formatted output conversion
putc
output a character or word to a stream
putchar
output a character or word to a stream
puts
output a line to a stream
putw
output a character or word to a stream
remove
remove directory entry
rewind
reposition a stream
scanf
input format conversion
setbuf
stream buffering operations
setbuffer
stream buffering operations
setlinebuf
stream buffering operations
setvbuf
stream buffering operations
sprintf
formatted output conversion
sscanf
input format conversion
strerror
system error messages
sys_errlist
system error messages
sys_nerr
system error messages
tempnam
temporary file routines
tmpfile
temporary file routines
tmpnam
temporary file routines
ungetc
un-get character from input stream
vfprintf
formatted output conversion
vfscanf
input format conversion
vprintf
formatted output conversion
vscanf
input format conversion
vsprintf
formatted output conversion
vsscanf
input format conversion

CONFORMING TO

The stdio library conforms to C89.

SEE ALSO

close(2), open(2), read(2), write(2), stdout(3), unlocked_stdio(3)


vprintf (3)

 Continue to this page.


vscanf (3)

 Continue to this page.


rpc(3)

RPC

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

rpc - library routines for remote procedure calls

SYNOPSIS AND DESCRIPTION

These routines allow C programs to make procedure calls on other machines across the network. First, the client calls a procedure to send a data packet to the server. Upon receipt of the packet, the server calls a dispatch routine to perform the requested service, and then sends back a reply. Finally, the procedure call returns to the client.

#include <rpc/rpc.h>

void
auth_destroy(auth)
AUTH *auth;
A macro that destroys the authentication information associated with auth. Destruction usually involves deallocation of private data structures. The use of auth is undefined after calling auth_destroy().

AUTH *
authnone_create()
Create and returns an RPC authentication handle that passes nonusable authentication information with each remote procedure call. This is the default authentication used by RPC.

AUTH *
authunix_create(host, uid, gid, len, aup_gids)
char *host;
int uid, gid, len, *aup.gids;
Create and return an RPC authentication handle that contains authentication information. The parameter host is the name of the machine on which the information was created; uid is the user's user ID ; gid is the user's current group ID ; len and aup_gids refer to a counted array of groups to which the user belongs. It is easy to impersonate a user.

AUTH *
authunix_create_default()
Calls authunix_create() with the appropriate parameters.

callrpc(host, prognum, versnum, procnum, inproc, in, outproc, out)
char *host;
u_long prognum, versnum, procnum;
char *in, *out;
xdrproc_t inproc, outproc;
Call the remote procedure associated with prognum, versnum, and procnum on the machine, host. The parameter in is the address of the procedure's argument(s), and out is the address of where to place the result(s); inproc is used to encode the procedure's parameters, and outproc is used to decode the procedure's results. This routine returns zero if it succeeds, or the value of enum clnt_stat cast to an integer if it fails. The routine clnt_perrno() is handy for translating failure statuses into messages.
Warning: calling remote procedures with this routine uses UDP/IP as a transport; see clntudp_create() for restrictions. You do not have control of timeouts or authentication using this routine.

enum clnt_stat
clnt_broadcast(prognum, versnum, procnum, inproc, in, outproc, out, eachresult)
u_long prognum, versnum, procnum;
char *in, *out;
xdrproc_t inproc, outproc;
resultproc_t eachresult;
Like callrpc(), except the call message is broadcast to all locally connected broadcast nets. Each time it receives a response, this routine calls eachresult(), whose form is:
eachresult(out, addr)
char *out;
struct sockaddr_in *addr;
where out is the same as out passed to clnt_broadcast(), except that the remote procedure's output is decoded there; addr points to the address of the machine that sent the results. If eachresult() returns zero, clnt_broadcast() waits for more replies; otherwise it returns with appropriate status.
Warning: broadcast sockets are limited in size to the maximum transfer unit of the data link. For ethernet, this value is 1500 bytes.

enum clnt_stat
clnt_call(clnt, procnum, inproc, in, outproc, out, tout)
CLIENT *clnt;
u_long
procnum;
xdrproc_t inproc, outproc;
char *in, *out;
struct timeval tout;
A macro that calls the remote procedure procnum associated with the client handle, clnt, which is obtained with an RPC client creation routine such as clnt_create(). The parameter in is the address of the procedure's argument(s), and out is the address of where to place the result(s); inproc is used to encode the procedure's parameters, and outproc is used to decode the procedure's results; tout is the time allowed for results to come back.

clnt_destroy(clnt)
CLIENT *clnt;
A macro that destroys the client's RPC handle. Destruction usually involves deallocation of private data structures, including clnt itself. Use of clnt is undefined after calling clnt_destroy(). If the RPC library opened the associated socket, it will close it also. Otherwise, the socket remains open.

CLIENT *
clnt_create(host, prog, vers, proto)
char *host;
u_long prog, vers;
char *proto;
Generic client creation routine. host identifies the name of the remote host where the server is located. proto indicates which kind of transport protocol to use. The currently supported values for this field are "udp" and "tcp". Default timeouts are set, but can be modified using clnt_control().
Warning: Using UDP has its shortcomings. Since UDP-based RPC messages can only hold up to 8 Kbytes of encoded data, this transport cannot be used for procedures that take large arguments or return huge results.

bool_t
clnt_control(cl, req, info)
CLIENT *cl;
char *info;
A macro used to change or retrieve various information about a client object. req indicates the type of operation, and info is a pointer to the information. For both UDP and TCP, the supported values of req and their argument types and what they do are:

CLSET_TIMEOUT       struct timeval      set total timeoutCLGET_TIMEOUTstruct timevalget total timeout
Note: if you set the timeout using
clnt_control(), the timeout parameter passed to clnt_call() will be ignored in all future calls.
CLGET_SERVER_ADDR   struct sockaddr_in  get server's address

The following operations are valid for
UDP only:

CLSET_RETRY_TIMEOUT struct timeval      set the retry timeoutCLGET_RETRY_TIMEOUTstruct timevalget the retry timeout

The retry timeout is the time that
UDP RPC waits for the server to reply before retransmitting the request.

clnt_freeres(clnt, outproc, out)
CLIENT *clnt;
xdrproc_t outproc;
char *out;
A macro that frees any data allocated by the RPC/XDR system when it decoded the results of an RPC call. The parameter out is the address of the results, and outproc is the XDR routine describing the results. This routine returns one if the results were successfully freed, and zero otherwise.

void
clnt_geterr(clnt, errp)
CLIENT *clnt;
struct rpc_err *errp;
A macro that copies the error structure out of the client handle to the structure at address errp.

void
clnt_pcreateerror(s)
char *s;
Print a message to standard error indicating why a client RPC handle could not be created. The message is prepended with string s and a colon. Used when a clnt_create(), clntraw_create(), clnttcp_create(), or clntudp_create() call fails.

void
clnt_perrno(stat)
enum clnt_stat stat;
Print a message to standard error corresponding to the condition indicated by stat. Used after callrpc().

clnt_perror(clnt, s)
CLIENT *clnt;
char *s;
Print a message to standard error indicating why an RPC call failed; clnt is the handle used to do the call. The message is prepended with string s and a colon. Used after clnt_call().

char *
clnt_spcreateerror
char *s;
Like clnt_pcreateerror(), except that it returns a string instead of printing to the standard error.
Bugs: returns pointer to static data that is overwritten on each call.

char *
clnt_sperrno(stat)
enum clnt_stat stat;
Take the same arguments as clnt_perrno(), but instead of sending a message to the standard error indicating why an RPC call failed, return a pointer to a string which contains the message. The string ends with a NEWLINE.
clnt_sperrno() is used instead of clnt_perrno() if the program does not have a standard error (as a program running as a server quite likely does not), or if the programmer does not want the message to be output with printf(), or if a message format different than that supported by clnt_perrno() is to be used. Note: unlike clnt_sperror() and clnt_spcreaterror(), clnt_sperrno() returns pointer to static data, but the result will not get overwritten on each call.

char *
clnt_sperror(rpch, s)
CLIENT *rpch;
char *s;
Like clnt_perror(), except that (like clnt_sperrno()) it returns a string instead of printing to standard error.
Bugs: returns pointer to static data that is overwritten on each call.

CLIENT *
clntraw_create(prognum, versnum)
u_long prognum, versnum;
This routine creates a toy RPC client for the remote program prognum, version versnum. The transport used to pass messages to the service is actually a buffer within the process's address space, so the corresponding RPC server should live in the same address space; see svcraw_create(). This allows simulation of RPC and acquisition of RPC overheads, such as round trip times, without any kernel interference. This routine returns NULL if it fails.

CLIENT *
clnttcp_create(addr, prognum, versnum, sockp, sendsz, recvsz)
struct sockaddr_in *addr;
u_long prognum, versnum;
int *sockp;
u_int sendsz, recvsz;
This routine creates an RPC client for the remote program prognum, version versnum; the client uses TCP/IP as a transport. The remote program is located at Internet address *addr. If addr->sin_port is zero, then it is set to the actual port that the remote program is listening on (the remote portmap service is consulted for this information). The parameter sockp is a socket; if it is RPC_ANYSOCK, then this routine opens a new one and sets sockp. Since TCP-based RPC uses buffered I/O , the user may specify the size of the send and receive buffers with the parameters sendsz and recvsz; values of zero choose suitable defaults. This routine returns NULL if it fails.

CLIENT *
clntudp_create(addr, prognum, versnum, wait, sockp)
struct sockaddr_in *addr;
u_long prognum, versnum;
struct timeval wait;
int *sockp;
This routine creates an RPC client for the remote program prognum, version versnum; the client uses use UDP/IP as a transport. The remote program is located at Internet address addr. If addr->sin_port is zero, then it is set to actual port that the remote program is listening on (the remote portmap service is consulted for this information). The parameter sockp is a socket; if it is RPC_ANYSOCK, then this routine opens a new one and sets sockp. The UDP transport resends the call message in intervals of wait time until a response is received or until the call times out. The total time for the call to time out is specified by clnt_call().
Warning: since UDP-based RPC messages can only hold up to 8 Kbytes of encoded data, this transport cannot be used for procedures that take large arguments or return huge results.

CLIENT *
clntudp_bufcreate(addr, prognum, versnum, wait, sockp, sendsize, recosize)
struct sockaddr_in *addr;
u_long prognum, versnum;
struct timeval wait;
int *sockp;
unsigned int sendsize;
unsigned int recosize;
This routine creates an RPC client for the remote program prognum, on versnum; the client uses use UDP/IP as a transport. The remote program is located at Internet address addr. If addr->sin_port is zero, then it is set to actual port that the remote program is listening on (the remote portmap service is consulted for this information). The parameter sockp is a socket; if it is RPC_ANYSOCK, then this routine opens a new one and sets sockp. The UDP transport resends the call message in intervals of wait time until a response is received or until the call times out. The total time for the call to time out is specified by clnt_call().
This allows the user to specify the maximum packet size for sending and receiving UDP-based RPC messages.

void
get_myaddress(addr)
struct sockaddr_in *addr;
Stuff the machine's IP address into *addr, without consulting the library routines that deal with /etc/hosts. The port number is always set to htons(PMAPPORT).

struct pmaplist *
pmap_getmaps(addr)
struct sockaddr_in *addr;
A user interface to the portmap service, which returns a list of the current RPC program-to-port mappings on the host located at IP address *addr. This routine can return NULL . The command `rpcinfo -p' uses this routine.

u_short
pmap_getport(addr, prognum, versnum, protocol)
struct sockaddr_in *addr;
u_long prognum, versnum, protocol;
A user interface to the portmap service, which returns the port number on which waits a service that supports program number prognum, version versnum, and speaks the transport protocol associated with protocol. The value of protocol is most likely IPPROTO_UDP or IPPROTO_TCP. A return value of zero means that the mapping does not exist or that the RPC system failed to contact the remote portmap service. In the latter case, the global variable rpc_createerr() contains the RPC status.

enum clnt_stat
pmap_rmtcall(addr, prognum, versnum, procnum, inproc, in, outproc, out, tout, portp)
struct sockaddr_in *addr;
u_long prognum, versnum, procnum;
char *in, *out;
xdrproc_t inproc, outproc;
struct timeval tout;
u_long *portp;
A user interface to the portmap service, which instructs portmap on the host at IP address *addr to make an RPC call on your behalf to a procedure on that host. The parameter *portp will be modified to the program's port number if the procedure succeeds. The definitions of other parameters are discussed in callrpc() and clnt_call(). This procedure should be used for a "ping" and nothing else. See also clnt_broadcast().

pmap_set(prognum, versnum, protocol, port)
u_long prognum, versnum, protocol;
u_short port;
A user interface to the portmap service, which establishes a mapping between the triple [prognum,versnum,protocol] and port on the machine's portmap service. The value of protocol is most likely IPPROTO_UDP or IPPROTO_TCP. This routine returns one if it succeeds, zero otherwise. Automatically done by svc_register().

pmap_unset(prognum, versnum)
u_long prognum, versnum;
A user interface to the portmap service, which destroys all mapping between the triple [prognum,versnum,*] and ports on the machine's portmap service. This routine returns one if it succeeds, zero otherwise.

registerrpc(prognum, versnum, procnum, procname, inproc, outproc)
u_long prognum, versnum, procnum;
char *(*procname) () ;
xdrproc_t inproc, outproc;
Register procedure procname with the RPC service package. If a request arrives for program prognum, version versnum, and procedure procnum, procname is called with a pointer to its parameter(s); progname should return a pointer to its static result(s); inproc is used to decode the parameters while outproc is used to encode the results. This routine returns zero if the registration succeeded, -1 otherwise.
Warning: remote procedures registered in this form are accessed using the UDP/IP transport; see svcudp_create() for restrictions.

struct rpc_createerr     rpc_createerr;
A global variable whose value is set by any RPC client creation routine that does not succeed. Use the routine clnt_pcreateerror() to print the reason why.

svc_destroy(xprt)
SVCXPRT *
xprt;
A macro that destroys the RPC service transport handle, xprt. Destruction usually involves deallocation of private data structures, including xprt itself. Use of xprt is undefined after calling this routine.

fd_set svc_fdset;
A global variable reflecting the RPC service side's read file descriptor bit mask; it is suitable as a parameter to the select() system call. This is only of interest if a service implementor does not call svc_run(), but rather does his own asynchronous event processing. This variable is read-only (do not pass its address to select()!), yet it may change after calls to svc_getreqset() or any creation routines.

int svc_fds;
Similar to svc_fdset, but limited to 32 descriptors. This interface is obsoleted by svc_fdset.

svc_freeargs(xprt, inproc, in)
SVCXPRT *xprt;
xdrproc_t inproc;
char *in;
A macro that frees any data allocated by the RPC/XDR system when it decoded the arguments to a service procedure using svc_getargs(). This routine returns 1 if the results were successfully freed, and zero otherwise.

svc_getargs(xprt, inproc, in)
SVCXPRT *xprt;
xdrproc_t inproc;
char *in;
A macro that decodes the arguments of an RPC request associated with the RPC service transport handle, xprt. The parameter in is the address where the arguments will be placed; inproc is the XDR routine used to decode the arguments. This routine returns one if decoding succeeds, and zero otherwise.

struct sockaddr_in *
svc_getcaller(xprt)
SVCXPRT *xprt;
The approved way of getting the network address of the caller of a procedure associated with the RPC service transport handle, xprt.

svc_getreqset(rdfds)
fd_set *rdfds;
This routine is only of interest if a service implementor does not call svc_run(), but instead implements custom asynchronous event processing. It is called when the select() system call has determined that an RPC request has arrived on some RPC socket(s) ; rdfds is the resultant read file descriptor bit mask. The routine returns when all sockets associated with the value of rdfds have been serviced.

svc_getreq(rdfds)
int rdfds;
Similar to svc_getreqset(), but limited to 32 descriptors. This interface is obsoleted by svc_getreqset().

svc_register(xprt, prognum, versnum, dispatch, protocol)
SVCXPRT *xprt;
u_long prognum, versnum;
void (*dispatch) ();
u_long protocol;
Associates prognum and versnum with the service dispatch procedure, dispatch. If protocol is zero, the service is not registered with the portmap service. If protocol is non-zero, then a mapping of the triple [prognum,versnum,protocol] to xprt->xp_port is established with the local portmap service (generally protocol is zero, IPPROTO_UDP or IPPROTO_TCP ). The procedure dispatch has the following form:
dispatch(request, xprt)
struct svc_req *request;
SVCXPRT *xprt;
The svc_register() routine returns one if it succeeds, and zero otherwise.

svc_run()
This routine never returns. It waits for RPC requests to arrive, and calls the appropriate service procedure using svc_getreq() when one arrives. This procedure is usually waiting for a select() system call to return.

svc_sendreply(xprt, outproc, out)
SVCXPRT *xprt;
xdrproc_t outproc;
char *out;
Called by an RPC service's dispatch routine to send the results of a remote procedure call. The parameter xprt is the request's associated transport handle; outproc is the XDR routine which is used to encode the results; and out is the address of the results. This routine returns one if it succeeds, zero otherwise.

void
svc_unregister(prognum, versnum)
u_long prognum, versnum;
Remove all mapping of the double [prognum,versnum] to dispatch routines, and of the triple [prognum,versnum,*] to port number.

void
svcerr_auth(xprt, why)
SVCXPRT *xprt;
enum auth_stat why;
Called by a service dispatch routine that refuses to perform a remote procedure call due to an authentication error.

void
svcerr_decode(xprt)
SVCXPRT *xprt;
Called by a service dispatch routine that cannot successfully decode its parameters. See also svc_getargs().

void
svcerr_noproc(xprt)
SVCXPRT *xprt;
Called by a service dispatch routine that does not implement the procedure number that the caller requests.

void
svcerr_noprog(xprt)
SVCXPRT *xprt;
Called when the desired program is not registered with the RPC package. Service implementors usually do not need this routine.

void
svcerr_progvers(xprt)
SVCXPRT *xprt;
Called when the desired version of a program is not registered with the RPC package. Service implementors usually do not need this routine.

void
svcerr_systemerr(xprt)
SVCXPRT *xprt;
Called by a service dispatch routine when it detects a system error not covered by any particular protocol. For example, if a service can no longer allocate storage, it may call this routine.

void
svcerr_weakauth(xprt)
SVCXPRT *xprt;
Called by a service dispatch routine that refuses to perform a remote procedure call due to insufficient authentication parameters. The routine calls svcerr_auth(xprt, AUTH_TOOWEAK).

SVCXPRT *
svcfd_create(fd, sendsize, recvsize)
int fd;
u_int sendsize;
u_int recvsize;
Create a service on top of any open descriptor. Typically, this descriptor is a connected socket for a stream protocol such as TCP. sendsize and recvsize indicate sizes for the send and receive buffers. If they are zero, a reasonable default is chosen.

SVCXPRT *
svcraw_create()
This routine creates a toy RPC service transport, to which it returns a pointer. The transport is really a buffer within the process's address space, so the corresponding RPC client should live in the same address space; see clntraw_create(). This routine allows simulation of RPC and acquisition of RPC overheads (such as round trip times), without any kernel interference. This routine returns NULL if it fails.

SVCXPRT *
svctcp_create(sock, send_buf_size, recv_buf_size)
int sock;
u_int send_buf_size, recv_buf_size;
This routine creates a TCP/IP-based RPC service transport, to which it returns a pointer. The transport is associated with the socket sock, which may be RPC_ANYSOCK, in which case a new socket is created. If the socket is not bound to a local TCP port, then this routine binds it to an arbitrary port. Upon completion, xprt->xp_sock is the transport's socket descriptor, and xprt->xp_port is the transport's port number. This routine returns NULL if it fails. Since TCP-based RPC uses buffered I/O , users may specify the size of buffers; values of zero choose suitable defaults.

SVCXPRT *
svcudp_bufcreate(sock, sendsize, recosize)
int sock;
This routine creates a UDP/IP-based RPC service transport, to which it returns a pointer. The transport is associated with the socket sock, which may be RPC_ANYSOCK, in which case a new socket is created. If the socket is not bound to a local UDP port, then this routine binds it to an arbitrary port. Upon completion, xprt->xp_sock is the transport's socket descriptor, and xprt->xp_port is the transport's port number. This routine returns NULL if it fails.
This allows the user to specify the maximum packet size for sending and receiving UDP-based RPC messages.

SVCXPRT *
svcudp_create(sock)
int sock;
This call is equivalent to svcudp_bufcreate(sock,SZ,SZ) for some default size SZ.

xdr_accepted_reply(xdrs, ar)
XDR *xdrs;
struct accepted_reply *ar;
Used for encoding RPC reply messages. This routine is useful for users who wish to generate RPC-style messages without using the RPC package.

xdr_authunix_parms(xdrs, aupp)
XDR *xdrs;
struct authunix_parms *aupp;
Used for describing UNIX credentials. This routine is useful for users who wish to generate these credentials without using the RPC authentication package.

void
xdr_callhdr(xdrs, chdr)
XDR *xdrs;
struct rpc_msg *chdr;
Used for describing RPC call header messages. This routine is useful for users who wish to generate RPC-style messages without using the RPC package.

xdr_callmsg(xdrs, cmsg)
XDR *xdrs;
struct rpc_msg *cmsg;
Used for describing RPC call messages. This routine is useful for users who wish to generate RPC-style messages without using the RPC package.

xdr_opaque_auth(xdrs, ap)
XDR *xdrs;
struct opaque_auth *ap;
Used for describing RPC authentication information messages. This routine is useful for users who wish to generate RPC-style messages without using the RPC package.

xdr_pmap(xdrs, regs)
XDR *xdrs;
struct pmap *regs;
Used for describing parameters to various portmap procedures, externally. This routine is useful for users who wish to generate these parameters without using the pmap interface.

xdr_pmaplist(xdrs, rp)
XDR *xdrs;
struct pmaplist **rp;
Used for describing a list of port mappings, externally. This routine is useful for users who wish to generate these parameters without using the pmap interface.

xdr_rejected_reply(xdrs, rr)
XDR *xdrs;
struct rejected_reply *rr;
Used for describing RPC reply messages. This routine is useful for users who wish to generate RPC-style messages without using the RPC package.

xdr_replymsg(xdrs, rmsg)
XDR *xdrs;
struct rpc_msg *rmsg;
Used for describing RPC reply messages. This routine is useful for users who wish to generate RPC style messages without using the RPC package.

void
xprt_register(xprt)
SVCXPRT *xprt;
After RPC service transport handles are created, they should register themselves with the RPC service package. This routine modifies the global variable svc_fds(). Service implementors usually do not need this routine.

void
xprt_unregister(xprt)
SVCXPRT *xprt;
Before an RPC service transport handle is destroyed, it should unregister itself with the RPC service package. This routine modifies the global variable svc_fds(). Service implementors usually do not need this routine.

SEE ALSO

xdr(3)
The following manuals:
Remote Procedure Calls: Protocol Specification
Remote Procedure Call Programming Guide
rpcgen Programming Guide
RPC: Remote Procedure Call Protocol Specification, RFC 1050, Sun Microsystems, Inc., USC-ISI.


addmntent (3)

 Continue to this page.


regexec (3)

 Continue to this page.


iruserok (3)

 Continue to this page.


isalnum (3)

 Continue to this page.


ldexp(3)

LDEXP

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

ldexp, ldexpf, ldexpl - multiply floating-point number by integral power of 2

SYNOPSIS

#include <math.h>

double ldexp(double x, int exp);

float ldexpf(float x, int exp);

long double ldexpl(long double x, int exp);

Link with -lm.

DESCRIPTION

The ldexp() function returns the result of multiplying the floating-point number x by 2 raised to the power exp.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

frexp(3), modf(3), scalb(3)


ntohl (3)

 Continue to this page.


regfree (3)

 Continue to this page.


remove(3)

REMOVE

Section: Linux Programmer's Manual (3)
Updated: 1994-07-13 Return to Main Contents

NAME

remove - delete a name and possibly the file it refers to

SYNOPSIS

#include <stdio.h>

int remove(const char *pathname);

DESCRIPTION

remove() deletes a name from the filesystem. It calls unlink(2) for files, and rmdir(2) for directories.

If the removed name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.

If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.

If the name referred to a symbolic link the link is removed.

If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

The errors that occur are those for unlink(2) and rmdir(2).

CONFORMING TO

C89, C99, 4.3BSD, POSIX.1-2001.

NOTES

Under libc4 and libc5, remove() was an alias for unlink(2) (and hence would not remove directories).

BUGS

Infelicities in the protocol underlying NFS can cause the unexpected disappearance of files which are still being used.

SEE ALSO

rm(1), link(2), mknod(2), open(2), rename(2), rmdir(2), unlink(2), mkfifo(3), unlink(8)


fdopen (3)

 Continue to this page.


remque (3)

 Continue to this page.


alphasort (3)

 Continue to this page.


btree(3)

BTREE

Section: Linux Programmer's Manual (3)
Updated: 1994-08-18 Return to Main Contents

NAME

btree - btree database access method

SYNOPSIS

#include <sys/types.h>
#include <db.h>

DESCRIPTION

The routine dbopen(3) is the library interface to database files. One of the supported file formats is btree files. The general description of the database access methods is in dbopen(3), this manual page describes only the btree specific information.

The btree data structure is a sorted, balanced tree structure storing associated key/data pairs.

The btree access method specific data structure provided to dbopen(3) is defined in the <db.h> include file as follows:

typedef struct {

u_long flags;
u_int cachesize;
int maxkeypage;
int minkeypage;
u_int psize;
int (*compare)(const DBT *key1, const DBT *key2);
size_t (*prefix)(const DBT *key1, const DBT *key2);
int lorder;
} BTREEINFO;

The elements of this structure are as follows:

flags
The flag value is specified by or'ing any of the following values:
R_DUP
Permit duplicate keys in the tree, that is, permit insertion if the key to be inserted already exists in the tree. The default behavior, as described in dbopen(3), is to overwrite a matching key when inserting a new key or to fail if the R_NOOVERWRITE flag is specified. The R_DUP flag is overridden by the R_NOOVERWRITE flag, and if the R_NOOVERWRITE flag is specified, attempts to insert duplicate keys into the tree will fail.
If the database contains duplicate keys, the order of retrieval of key/data pairs is undefined if the get routine is used, however, seq routine calls with the R_CURSOR flag set will always return the logical ``first'' of any group of duplicate keys.
cachesize
A suggested maximum size (in bytes) of the memory cache. This value is only advisory, and the access method will allocate more memory rather than fail. Since every search examines the root page of the tree, caching the most recently used pages substantially improves access time. In addition, physical writes are delayed as long as possible, so a moderate cache can reduce the number of I/O operations significantly. Obviously, using a cache increases (but only increases) the likelihood of corruption or lost data if the system crashes while a tree is being modified. If cachesize is 0 (no size is specified) a default cache is used.
maxkeypage
The maximum number of keys which will be stored on any single page. Not currently implemented.
minkeypage
The minimum number of keys which will be stored on any single page. This value is used to determine which keys will be stored on overflow pages, that is, if a key or data item is longer than the pagesize divided by the minkeypage value, it will be stored on overflow pages instead of in the page itself. If minkeypage is 0 (no minimum number of keys is specified) a value of 2 is used.
psize
Page size is the size (in bytes) of the pages used for nodes in the tree. The minimum page size is 512 bytes and the maximum page size is 64K. If psize is 0 (no page size is specified) a page size is chosen based on the underlying file system I/O block size.
compare
Compare is the key comparison function. It must return an integer less than, equal to, or greater than zero if the first key argument is considered to be respectively less than, equal to, or greater than the second key argument. The same comparison function must be used on a given tree every time it is opened. If compare is NULL (no comparison function is specified), the keys are compared lexically, with shorter keys considered less than longer keys.
prefix
Prefix is the prefix comparison function. If specified, this routine must return the number of bytes of the second key argument which are necessary to determine that it is greater than the first key argument. If the keys are equal, the key length should be returned. Note, the usefulness of this routine is very data dependent, but, in some data sets can produce significantly reduced tree sizes and search times. If prefix is NULL (no prefix function is specified), and no comparison function is specified, a default lexical comparison routine is used. If prefix is NULL and a comparison routine is specified, no prefix comparison is done.
lorder
The byte order for integers in the stored database metadata. The number should represent the order as an integer; for example, big endian order would be the number 4,321. If lorder is 0 (no order is specified) the current host order is used.

If the file already exists (and the O_TRUNC flag is not specified), the values specified for the parameters flags, lorder and psize are ignored in favor of the values used when the tree was created.

Forward sequential scans of a tree are from the least key to the greatest.

Space freed up by deleting key/data pairs from the tree is never reclaimed, although it is normally made available for reuse. This means that the btree storage structure is grow-only. The only solutions are to avoid excessive deletions, or to create a fresh tree periodically from a scan of an existing one.

Searches, insertions, and deletions in a btree will all complete in O lg base N where base is the average fill factor. Often, inserting ordered data into btrees results in a low fill factor. This implementation has been modified to make ordered insertion the best case, resulting in a much better than normal page fill factor.

ERRORS

The btree access method routines may fail and set errno for any of the errors specified for the library routine dbopen(3).

BUGS

Only big and little endian byte order is supported.

SEE ALSO

dbopen(3), hash(3), mpool(3), recno(3)

The Ubiquitous B-tree, Douglas Comer, ACM Comput. Surv. 11, 2 (June 1979), 121-138.

Prefix B-trees, Bayer and Unterauer, ACM Transactions on Database Systems, Vol. 2, 1 (March 1977), 11-26.

The Art of Computer Programming Vol. 3: Sorting and Searching, D.E. Knuth, 1968, pp 471-480.


byteorder(3)

BYTEORDER

Section: Linux Programmer's Manual (3)
Updated: 1993-04-15 Return to Main Contents

NAME

htonl, htons, ntohl, ntohs - convert values between host and network byte order

SYNOPSIS

#include <arpa/inet.h>

uint32_t htonl(uint32_t hostlong);

uint16_t htons(uint16_t hostshort);

uint32_t ntohl(uint32_t netlong);

uint16_t ntohs(uint16_t netshort);

DESCRIPTION

The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.

The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.

The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.

The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order.

On the i80x86 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first.

CONFORMING TO

POSIX.1-2001.

Some systems require the inclusion of <netinet/in.h> instead of <arpa/inet.h>.

SEE ALSO

gethostbyname(3), getservent(3)


bzero(3)

BZERO

Section: Linux Programmer's Manual (3)
Updated: 2002-12-31 Return to Main Contents

NAME

bzero - write zero-valued bytes

SYNOPSIS

#include <strings.h>

void bzero(void *s, size_t n);

DESCRIPTION

The bzero() function sets the first n bytes of the byte area starting at s to zero (bytes containing '\0').

RETURN VALUE

None.

CONFORMING TO

4.3BSD. This function is deprecated (marked as LEGACY in POSIX.1-2001): use memset(3) in new programs.

SEE ALSO

memset(3), swab(3)


cbrt(3)

CBRT

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

cbrt, cbrtf, cbrtl - cube root function

SYNOPSIS

#include <math.h>

double cbrt(double x);

float cbrtf(float x);

long double cbrtl(long double x);

Link with -lm.

DESCRIPTION

The cbrt() function returns the (real) cube root of x. This function cannot fail; every representable real value has a representable real cube root.

CONFORMING TO

C99

SEE ALSO

pow(3), sqrt(3)


ecvt(3)

ECVT

Section: Linux Programmer's Manual (3)
Updated: 1999-06-25 Return to Main Contents

NAME

ecvt, fcvt - convert a floating-point number to a string

SYNOPSIS

#include <stdlib.h>

char *ecvt(double number, int ndigits, int *decpt, int *sign);

char *fcvt(double number, int ndigits, int *decpt, int *sign);

DESCRIPTION

The ecvt() function converts number to a null-terminated string of ndigits digits (where ndigits is reduced to an system-specific limit determined by the precision of a double), and returns a pointer to the string. The high-order digit is non-zero, unless number is zero. The low order digit is rounded. The string itself does not contain a decimal point; however, the position of the decimal point relative to the start of the string is stored in *decpt. A negative value for *decpt means that the decimal point is to the left of the start of the string. If the sign of number is negative, *sign is set to a non-zero value, otherwise it is set to 0. If number is zero, it is unspecified whether *decpt is 0 or 1.

The fcvt() function is identical to ecvt(), except that ndigits specifies the number of digits after the decimal point.

RETURN VALUE

Both the ecvt() and fcvt() functions return a pointer to a static string containing the ASCII representation of number. The static string is overwritten by each call to ecvt() or fcvt().

CONFORMING TO

SVr2; marked as LEGACY in POSIX.1-2001.

NOTES

These functions are obsolete. Instead, sprintf(3) is recommended. Linux libc4 and libc5 specified the type of ndigits as size_t. Not all locales use a point as the radix character (`decimal point').

SEE ALSO

ecvt_r(3), gcvt(3), qecvt(3), setlocale(3), sprintf(3)


endgrent (3)

 Continue to this page.


endservent (3)

 Continue to this page.


exit(3)

EXIT

Section: Linux Programmer's Manual (3)
Updated: 2007-06-12 Return to Main Contents

NAME

exit - cause normal process termination

SYNOPSIS

#include <stdlib.h>

void exit(int status);

DESCRIPTION

The exit() function causes normal process termination and the value of status & 0377 is returned to the parent (see wait(2)).

All functions registered with atexit(3) and on_exit(3) are called, in the reverse order of their registration. (It is possible for one of these functions to use atexit(3) or on_exit(3) to register an additional function to be executed during exit processing; the new registration is added to the front of the list of functions that remain to be called.) If one of these functions does not return (e.g., it calls _exit(2), or kills itself with a signal), then none of the remaining functions is called, and further exit processing (in particular, flushing of stdio(3) streams) is abandoned. If a function has been registered multiple times using atexit(3) or on_exit(3), then it is called as many times as it was registered.

All open stdio(3) streams are flushed and closed. Files created by tmpfile(3) are removed.

The C standard specifies two constants, EXIT_SUCCESS and EXIT_FAILURE, that may be passed to exit() to indicate successful or unsuccessful termination, respectively.

RETURN VALUE

The exit() function does not return.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001, C89, C99.

NOTES

It is undefined what happens if one of the functions registered using atexit(3) and on_exit(3) calls either exit() or longjmp(3).

The use of EXIT_SUCCESS and EXIT_FAILURE is slightly more portable (to non-Unix environments) than the use of 0 and some non-zero value like 1 or -1. In particular, VMS uses a different convention.

BSD has attempted to standardize exit codes; see the file <sysexits.h>.

After exit(), the exit status must be transmitted to the parent process. There are three cases. If the parent has set SA_NOCLDWAIT, or has set the SIGCHLD handler to SIG_IGN, the status is discarded. If the parent was waiting on the child it is notified of the exit status. In both cases the exiting process dies immediately. If the parent has not indicated that it is not interested in the exit status, but is not waiting, the exiting process turns into a "zombie" process (which is nothing but a container for the single byte representing the exit status) so that the parent can learn the exit status when it later calls one of the wait(2) functions.

If the implementation supports the SIGCHLD signal, this signal is sent to the parent. If the parent has set SA_NOCLDWAIT, it is undefined whether a SIGCHLD signal is sent.

If the process is a session leader and its controlling terminal is the controlling terminal of the session, then each process in the foreground process group of this controlling terminal is sent a SIGHUP signal, and the terminal is disassociated from this session, allowing it to be acquired by a new controlling process.

If the exit of the process causes a process group to become orphaned, and if any member of the newly orphaned process group is stopped, then a SIGHUP signal followed by a SIGCONT signal will be sent to each process in this process group.

SEE ALSO

_exit(2), wait(2), atexit(3), on_exit(3), tmpfile(3)


fpathconf(3)

FPATHCONF

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

fpathconf, pathconf - get configuration values for files

SYNOPSIS

#include <unistd.h>

long fpathconf(int filedes, int name);

long pathconf(char *path, int name);

DESCRIPTION

fpathconf() gets a value for the configuration option name for the open file descriptor filedes.

pathconf() gets a value for configuration option name for the filename path.

The corresponding macros defined in <unistd.h> are minimum values; if an application wants to take advantage of values which may change, a call to fpathconf() or pathconf() can be made, which may yield more liberal results.

Setting name equal to one of the following constants returns the following configuration options:

_PC_LINK_MAX
returns the maximum number of links to the file. If filedes or path refer to a directory, then the value applies to the whole directory. The corresponding macro is _POSIX_LINK_MAX.
_PC_MAX_CANON
returns the maximum length of a formatted input line, where filedes or path must refer to a terminal. The corresponding macro is _POSIX_MAX_CANON.
_PC_MAX_INPUT
returns the maximum length of an input line, where filedes or path must refer to a terminal. The corresponding macro is _POSIX_MAX_INPUT.
_PC_NAME_MAX
returns the maximum length of a filename in the directory path or filedes. the process is allowed to create. The corresponding macro is _POSIX_NAME_MAX.
_PC_PATH_MAX
returns the maximum length of a relative pathname when path or filedes is the current working directory. The corresponding macro is _POSIX_PATH_MAX.
_PC_PIPE_BUF
returns the size of the pipe buffer, where filedes must refer to a pipe or FIFO and path must refer to a FIFO. The corresponding macro is _POSIX_PIPE_BUF.
_PC_CHOWN_RESTRICTED
returns non-zero if the chown(2) call may not be used on this file. If filedes or path refer to a directory, then this applies to all files in that directory. The corresponding macro is _POSIX_CHOWN_RESTRICTED.
_PC_NO_TRUNC
returns non-zero if accessing filenames longer than _POSIX_NAME_MAX generates an error. The corresponding macro is _POSIX_NO_TRUNC.
_PC_VDISABLE
returns non-zero if special character processing can be disabled, where filedes or path must refer to a terminal.

RETURN VALUE

The limit is returned, if one exists. If the system does not have a limit for the requested resource, -1 is returned, and errno is unchanged. If there is an error, -1 is returned, and errno is set to reflect the nature of the error.

CONFORMING TO

POSIX.1-2001.

NOTES

Files with name lengths longer than the value returned for name equal to _PC_NAME_MAX may exist in the given directory.

Some returned values may be huge; they are not suitable for allocating memory.

SEE ALSO

getconf(1), open(2), statfs(2), sysconf(3)


freopen (3)

 Continue to this page.


ftok(3)

FTOK

Section: Linux Programmer's Manual (3)
Updated: 2001-11-28 Return to Main Contents

NAME

ftok - convert a pathname and a project identifier to a System V IPC key

SYNOPSIS

# include <sys/types.h>
# include <sys/ipc.h>

key_t ftok(const char *pathname, int proj_id);

DESCRIPTION

The ftok() function uses the identity of the file named by the given pathname (which must refer to an existing, accessible file) and the least significant 8 bits of proj_id (which must be non-zero) to generate a key_t type System V IPC key, suitable for use with msgget(2), semget(2), or shmget(2).

The resulting value is the same for all pathnames that name the same file, when the same value of proj_id is used. The value returned should be different when the (simultaneously existing) files or the project IDs differ.

RETURN VALUE

On success the generated key_t value is returned. On failure -1 is returned, with errno indicating the error as for the stat(2) system call.

CONFORMING TO

POSIX.1-2001.

NOTES

Under libc4 and libc5 (and under SunOS 4.x) the prototype was
key_t ftok(char *pathname, char proj_id);
Today proj_id is an int, but still only 8 bits are used. Typical usage has an ASCII character proj_id, that is why the behavior is said to be undefined when proj_id is zero.

Of course no guarantee can be given that the resulting key_t is unique. Typically, a best effort attempt combines the given proj_id byte, the lower 16 bits of the i-node number, and the lower 8 bits of the device number into a 32-bit result. Collisions may easily happen, for example between files on /dev/hda1 and files on /dev/sda1.

SEE ALSO

msgget(2), semget(2), shmget(2), stat(2), svipc(7)


ftw(3)

FTW

Section: Linux Programmer's Manual (3)
Updated: 2006-05-24 Return to Main Contents

NAME

ftw, nftw - file tree walk

SYNOPSIS

#include <ftw.h>

int ftw(const char *dirpath,
        int (*fn) (const char *fpath, const struct stat *sb,
                   int typeflag),
        int nopenfd);

#define _XOPEN_SOURCE 500
#include <ftw.h>

int nftw(const char *dirpath,
        int (*fn) (const char *fpath, const struct stat *sb,
                   int typeflag, struct FTW *ftwbuf),
        int nopenfd, int flags);

DESCRIPTION

ftw() walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree. By default, directories are handled before the files and subdirectories they contain (pre-order traversal).

To avoid using up all of the calling process's file descriptors, nopenfd specifies the maximum number of directories that ftw() will hold open simultaneously. When the search depth exceeds this, ftw() will become slower because directories have to be closed and reopened. ftw() uses at most one file descriptor for each level in the directory tree.

For each entry found in the tree, ftw() calls fn() with three arguments: fpath, sb, and typeflag. fpath is the pathname of the entry relative to dirpath. sb is a pointer to the stat structure returned by a call to stat(2) for fpath. typeflag is an integer that has one of the following values:

FTW_F
fpath is a normal file.
FTW_D
fpath is a directory.
FTW_DNR
fpath is a directory which can't be read.
FTW_NS
The stat(2) call failed on fpath, which is not a symbolic link.

If fpath is a symbolic link and stat(2) failed, POSIX.1-2001 states that it is undefined whether FTW_NS or FTW_SL (see below) is passed in typeflag.

To stop the tree walk, fn() returns a non-zero value; this value will become the return value of ftw(). As long as fn() returns 0, ftw() will continue either until it has traversed the entire tree, in which case it will return zero, or until it encounters an error (such as a malloc(3) failure), in which case it will return -1.

Because ftw() uses dynamic data structures, the only safe way to exit out of a tree walk is to return a non-zero value from fn(). To allow a signal to terminate the walk without causing a memory leak, have the handler set a global flag that is checked by fn(). Don't use longjmp(3) unless the program is going to terminate.

nftw()

The function nftw() is the same as ftw(), except that it has one additional argument, flags, and calls fn() with one more argument, ftwbuf.

This flags argument is formed by ORing zero or more of the following flags:

FTW_ACTIONRETVAL (since glibc 2.3.3)
If this glibc-specific flag is set, then nftw() handles the return value from fn() differently. fn() should return one of the following values:
FTW_CONTINUE
Instructs nftw() to continue normally.
FTW_SKIP_SIBLINGS
If fn() returns this value, then siblings of the current entry will be skipped, and processing continues in the parent.
FTW_SKIP_SUBTREE
If fn() is called with an entry that is a directory (typeflag is FTW_D), this return value will prevent objects within that directory from being passed as arguments to fn(). nftw() continues processing with the next sibling of the directory.
FTW_STOP
Causes nftw() to return immediately with the return value FTW_STOP.

Other return values could be associated with new actions in the future; fn() should not return values other than those listed above.

The feature test macro _GNU_SOURCE must be defined in order to obtain the definition of FTW_ACTIONRETVAL from <ftw.h>.

FTW_CHDIR
If set, do a chdir(2) to each directory before handling its contents. This is useful if the program needs to perform some action in the directory in which fpath resides.
FTW_DEPTH
If set, do a post-order traversal, that is, call fn() for the directory itself after handling the contents of the directory and its subdirectories. (By default, each directory is handled before its contents.)
FTW_MOUNT
If set, stay within the same file system (i.e., do not cross mount points).
FTW_PHYS
If set, do not follow symbolic links. (This is what you want.) If not set, symbolic links are followed, but no file is reported twice.

If FTW_PHYS is not set, but FTW_DEPTH is set, then the function fn() is never called for a directory that would be a descendant of itself.

For each entry in the directory tree, nftw() calls fn() with four arguments. fpath and sb are as for ftw(). typeflag may receive any of the same values as with ftw(), or any of the following values:

FTW_DP
fpath is a directory, and FTW_DEPTH was specified in flags. All of the files and subdirectories within fpath have been processed.
FTW_SL
fpath is a symbolic link, and FTW_PHYS was set in flags.
FTW_SLN
fpath is a symbolic link pointing to a nonexistent file. (This occurs only if FTW_PHYS is not set.)

The fourth argument that nftw() supplies when calling fn() is a structure of type FTW:

struct FTW {
    int base;
    int level;
};
base is the offset of the filename (i.e., basename component) in the pathname given in fpath. level is the depth of fpath in the directory tree, relative to the root of the tree (dirpath, which has depth 0).

RETURN VALUE

These functions return 0 on success, and -1 if an error occurs.

If fn() returns non-zero, then the tree walk is terminated and the value returned by fn() is returned as the result of ftw() or nftw().

If nftw() is called with the FTW_ACTIONRETVAL flag, then the only non-zero value that should be used by fn() to terminate the tree walk is FTW_STOP, and that value is returned as the result of nftw().

CONFORMING TO

POSIX.1-2001, SVr4, SUSv1.

NOTES

The function nftw() and the use of FTW_SL with ftw() were introduced in SUSv1.

On some systems ftw() will never use FTW_SL, on other systems FTW_SL occurs only for symbolic links that do not point to an existing file, and again on other systems ftw() will use FTW_SL for each symbolic link. For predictable control, use nftw().

Under Linux, libc4 and libc5 and glibc 2.0.6 will use FTW_F for all objects (files, symbolic links, fifos, etc) that can be stat'ed but are not a directory.

The function nftw() is available since glibc 2.1.

FTW_ACTIONRETVAL is glibc specific.

EXAMPLE

The following program traverses the directory tree under the path named in its first command-line argument, or under the current directory if no argument is supplied. It displays various information about each file. The second-command line argument can be used to specify characters that control the value assigned to the flags argument when calling nftw().

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int
display_info(const char *fpath, const struct stat *sb,
             int tflag, struct FTW *ftwbuf)
{
    printf("%-3s %2d %7lld   %-40s %d %s\n",
        (tflag == FTW_D) ?   "d"   : (tflag == FTW_DNR) ? "dnr" :
        (tflag == FTW_DP) ?  "dp"  : (tflag == FTW_F) ?   "f" :
        (tflag == FTW_DP) ?  "dp"  : (tflag == FTW_SL) ?  "sl" :
        (tflag == FTW_SLN) ? "sln" : "???",
        ftwbuf->level, (long long) sb->st_size,
        fpath, ftwbuf->base, fpath + ftwbuf->base);
    return 0;           /* To tell nftw() to continue */
}

int
main(int argc, char *argv[])
{
    int flags = 0;

    if (argc > 2 && strchr(argv[2], 'd') != NULL)
        flags |= FTW_DEPTH;
    if (argc > 2 && strchr(argv[2], 'p') != NULL)
        flags |= FTW_PHYS;

    nftw((argc < 2) ? "." : argv[1], display_info, 20, flags);
    exit(EXIT_SUCCESS);
}

SEE ALSO

stat(2), fts(3), readdir(3), feature_test_macros(7)


get_current_dir_name (3)

 Continue to this page.


getgrent(3)

GETGRENT

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

getgrent, setgrent, endgrent - get group file entry

SYNOPSIS

#include <sys/types.h>
#include <grp.h>

struct group *getgrent(void);

void setgrent(void);

void endgrent(void);

DESCRIPTION

The getgrent() function returns a pointer to a structure containing the broken-out fields of a record in the group database (e.g., the local group file /etc/group, NIS, and LDAP). The first time it is called it returns the first entry; thereafter, it returns successive entries.

The setgrent() function rewinds to the beginning of the group database, to allow repeated scans.

The endgrent() function is used to close the group database after all processing has been performed.

The group structure is defined in <grp.h> as follows:

struct group {
    char   *gr_name;       /* group name */
    char   *gr_passwd;     /* group password */
    gid_t   gr_gid;        /* group ID */
    char  **gr_mem;        /* group members */
};

RETURN VALUE

The getgrent() function returns a pointer to a group structure, or NULL if there are no more entries or an error occurs.

Upon error, errno may be set. If one wants to check errno after the call, it should be set to zero before the call.

ERRORS

EINTR
A signal was caught.
EIO
I/O error.
EMFILE
The calling process already has too many open files.
ENFILE
Too many open files in the system.
ENOMEM
Insufficient memory to allocate group information structure.
ERANGE
Insufficient buffer space supplied.

FILES

/etc/group
local group database file

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

SEE ALSO

fgetgrent(3), getgrent_r(3), getgrgid(3), getgrnam(3), putgrent(3)


getnetbyaddr (3)

 Continue to this page.


getpwent(3)

GETPWENT

Section: Linux Programmer's Manual (3)
Updated: 1996-05-27 Return to Main Contents

NAME

getpwent, setpwent, endpwent - get password file entry

SYNOPSIS

#include <sys/types.h>
#include <pwd.h>

struct passwd *getpwent(void);

void setpwent(void);

void endpwent(void);

DESCRIPTION

The getpwent() function returns a pointer to a structure containing the broken-out fields of a record from the password database (e.g., the local password file /etc/passwd, NIS, and LDAP). The first time it is called it returns the first entry; thereafter, it returns successive entries.

The setpwent() function rewinds to the beginning of the password database.

The endpwent() function is used to close the password database after all processing has been performed.

The passwd structure is defined in <pwd.h> as follows:

struct passwd {
    char   *pw_name;       /* user name */
    char   *pw_passwd;     /* user password */
    uid_t   pw_uid;        /* user ID */
    gid_t   pw_gid;        /* group ID */
    char   *pw_gecos;      /* real name */
    char   *pw_dir;        /* home directory */
    char   *pw_shell;      /* shell program */
};

RETURN VALUE

The getpwent() function returns a pointer to a passwd structure, or NULL if there are no more entries or an error occurs. If an error occurs, errno is set appropriately. If one wants to check errno after the call, it should be set to zero before the call.

ERRORS

EINTR
A signal was caught.
EIO
I/O error.
EMFILE
The maximum number (OPEN_MAX) of files was open already in the calling process.
ENFILE
The maximum number of files was open already in the system.
ENOMEM
Insufficient memory to allocate passwd structure.
ERANGE
Insufficient buffer space supplied.

FILES

/etc/passwd
local password database file

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

SEE ALSO

fgetpwent(3), getpw(3), getpwent_r(3), getpwnam(3), getpwuid(3), putpwent(3), passwd(5)


getpwnam(3)

GETPWNAM

Section: Linux Programmer's Manual (3)
Updated: 1996-05-27 Return to Main Contents

NAME

getpwnam, getpwnam_r, getpwuid, getpwuid_r - get password file entry

SYNOPSIS

#include <sys/types.h>
#include <pwd.h>

struct passwd *getpwnam(const char *name);

struct passwd *getpwuid(uid_t uid);

int getpwnam_r(const char *name, struct passwd *pwbuf,

        char *buf, size_t buflen, struct passwd **pwbufp);

int getpwuid_r(uid_t uid, struct passwd *pwbuf,

        char *buf, size_t buflen, struct passwd **pwbufp);

DESCRIPTION

The getpwnam() function returns a pointer to a structure containing the broken-out fields of the record in the password database (e.g., the local password file /etc/passwd, NIS, and LDAP) that matches the user name name.

The getpwuid() function returns a pointer to a structure containing the broken-out fields of the record in the password database that matches the user ID uid.

The getpwnam_r() and getpwuid_r() functions obtain the same information, but store the retrieved passwd structure in the space pointed to by pwbuf. This passwd structure contains pointers to strings, and these strings are stored in the buffer buf of size buflen. A pointer to the result (in case of success) or NULL (in case no entry was found or an error occurred) is stored in *pwbufp.

The passwd structure is defined in <pwd.h> as follows:

struct passwd {
    char   *pw_name;       /* user name */
    char   *pw_passwd;     /* user password */
    uid_t   pw_uid;        /* user ID */
    gid_t   pw_gid;        /* group ID */
    char   *pw_gecos;      /* real name */
    char   *pw_dir;        /* home directory */
    char   *pw_shell;      /* shell program */
};

The maximum needed size for buf can be found using sysconf(3) with the _SC_GETPW_R_SIZE_MAX parameter.

RETURN VALUE

The getpwnam() and getpwuid() functions return a pointer to a passwd structure, or NULL if the matching entry is not found or an error occurs. If an error occurs, errno is set appropriately. If one wants to check errno after the call, it should be set to zero before the call.

The return value may point to static area, and may be overwritten by subsequent calls to getpwent(3), getpwnam(), or getpwuid().

The getpwnam_r() and getpwuid_r() functions return zero on success. In case of error, an error number is returned.

ERRORS

0 or ENOENT or ESRCH or EBADF or EPERM or ...
The given name or uid was not found.
EINTR
A signal was caught.
EIO
I/O error.
EMFILE
The maximum number (OPEN_MAX) of files was open already in the calling process.
ENFILE
The maximum number of files was open already in the system.
ENOMEM
Insufficient memory to allocate passwd structure.
ERANGE
Insufficient buffer space supplied.

FILES

/etc/passwd
local password database file

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001

NOTES

The formulation given above under "RETURN VALUE" is from POSIX.1-2001. It does not call "not found" an error, and hence does not specify what value errno might have in this situation. But that makes it impossible to recognize errors. One might argue that according to POSIX errno should be left unchanged if an entry is not found. Experiments on various Unix-like systems show that lots of different values occur in this situation: 0, ENOENT, EBADF, ESRCH, EWOULDBLOCK, EPERM and probably others.

The pw_dir field contains the name of the initial working directory of the user. Login programs use the value of this field to initialize the HOME environment variable for the login shell. An application that wants to determine its user's home directory should inspect the value of HOME (rather than the value getpwuid(getuid())->pw_dir) since this allows the user to modify their notion of "the home directory" during a login session. To determine the (initial) home directory of another user, it is necessary to use getpwnam(username)->pw_dir or similar.

SEE ALSO

endpwent(3), fgetpwent(3), getgrnam(3), getpw(3), getpwent(3), putpwent(3), setpwent(3), passwd(5)


getusershell(3)

GETUSERSHELL

Section: Linux Programmer's Manual (3)
Updated: 1993-07-04 Return to Main Contents

NAME

getusershell, setusershell, endusershell - get legal user shells

SYNOPSIS

#include <unistd.h>

char *getusershell(void);

void setusershell(void);

void endusershell(void);

DESCRIPTION

The getusershell() function returns the next line from the file /etc/shells, opening the file if necessary. The line should contain the pathname of a valid user shell. If /etc/shells does not exist or is unreadable, getusershell() behaves as if /bin/sh and /bin/csh were listed in the file.

The setusershell() function rewinds /etc/shells.

The endusershell() function closes /etc/shells.

RETURN VALUE

The getusershell() function returns a NULL pointer on end-of-file.

FILES

/etc/shells

CONFORMING TO

4.3BSD

SEE ALSO

shells(5)


glob(3)

GLOB

Section: Linux Programmer's Manual (3)
Updated: 1999-09-12 Return to Main Contents

NAME

glob, globfree - find pathnames matching a pattern, free memory from glob()

SYNOPSIS

#include <glob.h>

int glob(const char *pattern, int flags,

         int (*errfunc) (const char *epath, int eerrno),

         glob_t *pglob);

void globfree(glob_t *pglob);

DESCRIPTION

The glob() function searches for all the pathnames matching pattern according to the rules used by the shell (see glob(7)). No tilde expansion or parameter substitution is done; if you want these, use wordexp(3).

The globfree() function frees the dynamically allocated storage from an earlier call to glob().

The results of a glob() call are stored in the structure pointed to by pglob, which is a glob_t which is declared in <glob.h> and includes the following elements defined by POSIX.2 (more may be present as an extension):

typedef struct {
    size_t   gl_pathc;    /* Count of paths matched so far  */
    char   **gl_pathv;    /* List of matched pathnames.  */
    size_t   gl_offs;     /* Slots to reserve in `gl_pathv'.  */
} glob_t;

Results are stored in dynamically allocated storage.

The parameter flags is made up of bitwise OR of zero or more the following symbolic constants, which modify the of behavior of glob():

GLOB_ERR
which means to return upon read error (because a directory does not have read permission, for example),
GLOB_MARK
which means to append a slash to each path which corresponds to a directory,
GLOB_NOSORT
which means don't sort the returned pathnames (they are by default),
GLOB_DOOFFS
which means that pglob->gl_offs slots will be reserved at the beginning of the list of strings in pglob->pathv,
GLOB_NOCHECK
which means that, if no pattern matches, to return the original pattern,
GLOB_APPEND
which means to append to the results of a previous call. Do not set this flag on the first invocation of glob().
GLOB_NOESCAPE
which means that meta characters cannot be quoted by backslashes.

The flags may also include some of the following, which are GNU extensions and not defined by POSIX.2:

GLOB_PERIOD
which means that a leading period can be matched by meta characters,
GLOB_ALTDIRFUNC
which means that alternative functions
pglob->gl_closedir,

pglob->gl_readdir,

pglob->gl_opendir,

pglob->gl_lstat, and

pglob->gl_stat

are used for file system access instead of the normal library
functions,
GLOB_BRACE
which means that csh(1) style brace expressions {a,b} are expanded,
GLOB_NOMAGIC
which means that the pattern is returned if it contains no metacharacters,
GLOB_TILDE
which means that tilde expansion is carried out, and
GLOB_ONLYDIR
which means that only directories are matched.

If errfunc is not NULL, it will be called in case of an error with the arguments epath, a pointer to the path which failed, and eerrno, the value of errno as returned from one of the calls to opendir(3), readdir(3), or stat(2). If errfunc returns non-zero, or if GLOB_ERR is set, glob() will terminate after the call to errfunc.

Upon successful return, pglob->gl_pathc contains the number of matched pathnames and pglob->gl_pathv a pointer to the list of matched pathnames. The first pointer after the last pathname is NULL.

It is possible to call glob() several times. In that case, the GLOB_APPEND flag has to be set in flags on the second and later invocations.

As a GNU extension, pglob->gl_flags is set to the flags specified, ored with GLOB_MAGCHAR if any metacharacters were found.

RETURN VALUE

On successful completion, glob() returns zero. Other possible returns are:
GLOB_NOSPACE
for running out of memory,
GLOB_ABORTED
for a read error, and
GLOB_NOMATCH
for no found matches.

CONFORMING TO

POSIX.2, POSIX.1-2001.

NOTES

The structure elements gl_pathc and gl_offs are declared as size_t in glibc 2.1, as they should according to POSIX.2, but are declared as int in libc4, libc5 and glibc 2.0.

BUGS

The glob() function may fail due to failure of underlying function calls, such as malloc(3) or opendir(3). These will store their error code in errno.

EXAMPLE

One example of use is the following code, which simulates typing

ls -l *.c ../*.c

in the shell:

glob_t globbuf;

globbuf.gl_offs = 2;
glob("*.c", GLOB_DOOFFS, NULL, &globbuf);
glob("../*.c", GLOB_DOOFFS | GLOB_APPEND, NULL, &globbuf);
globbuf.gl_pathv[0] = "ls";
globbuf.gl_pathv[1] = "-l";
execvp("ls", &globbuf.gl_pathv[0]);

SEE ALSO

ls(1), sh(1), stat(2), exec(3), fnmatch(3), malloc(3), opendir(3), readdir(3), wordexp(3), glob(7)


gmtime (3)

 Continue to this page.


clock(3)

CLOCK

Section: Linux Programmer's Manual (3)
Updated: 2002-06-14 Return to Main Contents

NAME

clock - Determine processor time

SYNOPSIS

#include <time.h>

clock_t clock(void);

DESCRIPTION

The clock() function returns an approximation of processor time used by the program.

RETURN VALUE

The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be represented, the function returns the value (clock_t)-1.

CONFORMING TO

C89, C99, POSIX.1-2001. POSIX requires that CLOCKS_PER_SEC equals 1000000 independent of the actual resolution.

NOTES

The C standard allows for arbitrary values at the start of the program; subtract the value returned from a call to clock() at the start of the program to get maximum portability.

Note that the time can wrap around. On a 32bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.

On several other implementations, the value returned by clock() also includes the times of any children whose status has been collected via wait(2) (or another wait-type call). Linux does not include the times of waited-for children in the value returned by clock(). The times(2) function, which explicitly returns (separate) information about the caller and its children, may be preferable.

SEE ALSO

getrusage(2), times(2)


div(3)

DIV

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

div, ldiv, lldiv, imaxdiv - compute quotient and remainder of an integer division

SYNOPSIS

#include <stdlib.h>

div_t div(int numerator, int denominator);

ldiv_t ldiv(long numerator, long denominator);

lldiv_t lldiv(long long numerator, long long denominator);

#include <inttypes.h>

imaxdiv_t imaxdiv(intmax_t numerator, intmax_t denominator);

DESCRIPTION

The div() function computes the value numerator/denominator and returns the quotient and remainder in a structure named div_t that contains two integer members (in unspecified order) named quot and rem. The quotient is rounded towards zero. The result satisfies quot*denominator+rem = numerator.

The ldiv()and lldiv() and imaxdiv() functions do the same, dividing numbers of the indicated type and returning the result in a structure of the indicated name, in all cases with fields quot and rem of the same type as the function arguments.

RETURN VALUE

The div_t (etc.) structure.

CONFORMING TO

SVr4, 4.3BSD, C89. The functions lldiv() and imaxdiv() were added in C99.

EXAMPLE

After
        div_t q = div(-5, 3);
the values q.quot and q.rem are -1 and -2, respectively.

SEE ALSO

abs(3), remainder(3)


raise(3)

RAISE

Section: Linux Programmer's Manual (3)
Updated: 1995-08-31 Return to Main Contents

NAME

raise - send a signal to the current process

SYNOPSIS

#include <signal.h>

int raise(int sig);

DESCRIPTION

The raise() function sends a signal to the current process. It is equivalent to

kill(getpid(), sig);

RETURN VALUE

0 on success, non-zero for failure.

CONFORMING TO

C89, C99.

SEE ALSO

getpid(2), kill(2), signal(2)


getservbyport (3)

 Continue to this page.


htonl (3)

 Continue to this page.


stdout (3)

 Continue to this page.


asctime (3)

 Continue to this page.


strcat(3)

STRCAT

Section: Linux Programmer's Manual (3)
Updated: 2007-06-15 Return to Main Contents

NAME

strcat, strncat - concatenate two strings

SYNOPSIS

#include <string.h>

char *strcat(char *dest, const char *src);

char *strncat(char *dest, const char *src, size_t n);

DESCRIPTION

The strcat() function appends the src string to the dest string, overwriting the null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result.

The strncat() function is similar, except that

*
it will use at most n characters from src; and
*
src does not need to be null terminated if it contains n or more characters.

As with strcat(), the resulting string in dest is always null terminated.

If src contains n or more characters, strcat() writes n+1 characters to dest (n from src plus the terminating null byte). Therefore, the size of dest must be at least strlen(dest)+n+1.

A simple implementation of strncat() might be:

char*
strncat(char *dest, const char *src, size_t n)
{
    size_t dest_len = strlen(dest);
    int i;

    for(i = 0 ; i < n && src[i] != '\0' ; i++)
        dest[dest_len + i] = src[i];
    dest[dest_len + i] = '\0';

    return dest;
}

RETURN VALUE

The strcat() and strncat() functions return a pointer to the resulting string dest.

CONFORMING TO

SVr4, 4.3BSD, C89, C99.

SEE ALSO

bcopy(3), memccpy(3), memcpy(3), strcpy(3), strncpy(3), wcscat(3), wcsncat(3)


isblank (3)

 Continue to this page.


toupper(3)

TOUPPER

Section: Linux Programmer's Manual (3)
Updated: 1993-04-04 Return to Main Contents

NAME

toupper, tolower - convert letter to upper or lower case

SYNOPSIS

#include <ctype.h>

int toupper(int c);

int tolower(int c);

DESCRIPTION

toupper() converts the letter c to upper case, if possible.

tolower() converts the letter c to lower case, if possible.

If c is not an unsigned char value, or EOF, the behavior of these functions is undefined.

RETURN VALUE

The value returned is that of the converted letter, or c if the conversion was not possible.

CONFORMING TO

C89, C99, 4.3BSD

BUGS

The details of what constitutes an uppercase or lowercase letter depend on the current locale. For example, the default C locale does not know about umlauts, so no conversion is done for them.

In some non-English locales, there are lowercase letters with no corresponding uppercase equivalent; the German sharp s is one example.

SEE ALSO

isalpha(3), setlocale(3), towlower(3), towupper(3), locale(7)


isdigit (3)

 Continue to this page.


cfmakeraw (3)

 Continue to this page.


cfsetispeed (3)

 Continue to this page.


clearerr (3)

 Continue to this page.


copysign(3)

COPYSIGN

Section: Linux Programmer's Manual (3)
Updated: 2007-03-31 Return to Main Contents

NAME

copysign, copysignf, copysignl - copy sign of a number

SYNOPSIS

#include <math.h>

double copysign(double x, double y);

float copysignf(float x, float y);

long double copysignl(long double x, long double y);

Link with -lm.

DESCRIPTION

The copysign() functions return a value whose absolute value matches that of x, but whose sign matches that of y. If x is a NaN, then a NaN with the sign of y is returned.

CONFORMING TO

C99, 4.3BSD. This function is defined in IEC 559 (and the appendix with recommended functions in IEEE 754/IEEE 854).

NOTES

On architectures where the floating-point formats are not IEEE 754 compliant, the copysign() functions may treat a negative zero as positive.

SEE ALSO

signbit(3)


tcsetattr (3)

 Continue to this page.


tcsetpgrp (3)

 Continue to this page.


tdelete (3)

 Continue to this page.


telldir(3)

TELLDIR

Section: Linux Programmer's Manual (3)
Updated: 1993-03-31 Return to Main Contents

NAME

telldir - return current location in directory stream

SYNOPSIS

#include <dirent.h>

off_t telldir(DIR *dir);

DESCRIPTION

The telldir() function returns the current location associated with the directory stream dir.

RETURN VALUE

On success, the telldir() function returns the current location in the directory stream. On error, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
Invalid directory stream descriptor dir.

CONFORMING TO

4.3BSD, POSIX.1-2001.

SEE ALSO

closedir(3), opendir(3), readdir(3), rewinddir(3), scandir(3), seekdir(3)


tempnam(3)

TEMPNAM

Section: Linux Programmer's Manual (3)
Updated: 1999-06-14 Return to Main Contents

NAME

tempnam - create a name for a temporary file

SYNOPSIS

#include <stdio.h>

char *tempnam(const char *dir, const char *pfx);

DESCRIPTION

The tempnam() function returns a pointer to a string that is a valid filename, and such that a file with this name did not exist when tempnam() checked. The filename suffix of the pathname generated will start with pfx in case pfx is a non-NULL string of at most five bytes. The directory prefix part of the pathname generated is required to be `appropriate' (often that at least implies writable).

Attempts to find an appropriate directory go through the following steps:

a)
In case the environment variable TMPDIR exists and contains the name of an appropriate directory, that is used.
b)
Otherwise, if the dir argument is non-NULL and appropriate, it is used.
c)
Otherwise, P_tmpdir (as defined in <stdio.h>) is used when appropriate.
d)
Finally an implementation-defined directory may be used.

The string returned by tempnam() is allocated using malloc(3) and hence should be freed by free(3).

RETURN VALUE

The tempnam() function returns a pointer to a unique temporary filename, or NULL if a unique name cannot be generated.

ERRORS

ENOMEM
Allocation of storage failed.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001

NOTES

Although tempnam(3) generates names that are difficult to guess, it is nevertheless possible that between the time that tempnam(3) returns a pathname, and the time that the program opens it, another program might create that pathname using open(2), or create it as a symbolic link. This can lead to security holes. To avoid such possibilities, use the open(2) O_EXCL flag to open the pathname. Or better yet, use mkstemp(3) or tmpfile(3).

SUSv2 does not mention the use of TMPDIR; glibc will use it only when the program is not set-user-ID. On SVr4, the directory used under d) is /tmp (and this is what glibc does).

Because it dynamically allocates memory used to return the pathname, tempnam() is reentrant, and thus thread safe, unlike tmpnam(3).

The tempnam() function generates a different string each time it is called, up to TMP_MAX (defined in <stdio.h>) times. If it is called more than TMP_MAX times, the behavior is implementation defined.

tempnam() uses at most the first five bytes from pfx.

The glibc implementation of tempnam() will fail with the error EEXIST upon failure to find a unique name.

BUGS

The precise meaning of `appropriate' is undefined; it is unspecified how accessibility of a directory is determined.

Never use this function. Use mkstemp(3) or tmpfile(3) instead.

SEE ALSO

mkstemp(3), mktemp(3), tmpfile(3), tmpnam(3)


tmpfile(3)

TMPFILE

Section: Linux Programmer's Manual (3)
Updated: 2001-11-17 Return to Main Contents

NAME

tmpfile - create a temporary file

SYNOPSIS

#include <stdio.h>

FILE *tmpfile(void);

DESCRIPTION

The tmpfile() function opens a unique temporary file in binary read/write (w+b) mode. The file will be automatically deleted when it is closed or the program terminates.

RETURN VALUE

The tmpfile() function returns a stream descriptor, or NULL if a unique filename cannot be generated or the unique file cannot be opened. In the latter case, errno is set to indicate the error.

ERRORS

EACCES
Search permission denied for directory in file's path prefix.
EEXIST
Unable to generate a unique filename.
EINTR
The call was interrupted by a signal.
EMFILE
Too many file descriptors in use by the process.
ENFILE
Too many files open in the system.
ENOSPC
There was no room in the directory to add the new filename.
EROFS
Read-only filesystem.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, SUSv2, POSIX.1-2001.

NOTES

An error message may be written to stdout if the stream cannot be opened.

The standard does not specify the directory that tmpfile() will use. Glibc will try the path prefix P_tmpdir defined in <stdio.h>, and if that fails the directory /tmp.

SEE ALSO

exit(3), mkstemp(3), mktemp(3), tempnam(3), tmpnam(3)


tmpnam(3)

TMPNAM

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

tmpnam, tmpnam_r - create a name for a temporary file

SYNOPSIS

#include <stdio.h>

char *tmpnam(char *s);

DESCRIPTION

The tmpnam() function returns a pointer to a string that is a valid filename, and such that a file with this name did not exist at some point in time, so that naive programmers may think it a suitable name for a temporary file. If the argument s is NULL this name is generated in an internal static buffer and may be overwritten by the next call to tmpnam(). If s is not NULL, the name is copied to the character array (of length at least L_tmpnam) pointed to by s and the value s is returned in case of success.

The pathname that is created, has a directory prefix P_tmpdir. (Both L_tmpnam and P_tmpdir are defined in <stdio.h>, just like the TMP_MAX mentioned below.)

RETURN VALUE

The tmpnam() function returns a pointer to a unique temporary filename, or NULL if a unique name cannot be generated.

ERRORS

No errors are defined.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001.

NOTES

The tmpnam() function generates a different string each time it is called, up to TMP_MAX times. If it is called more than TMP_MAX times, the behavior is implementation defined.

Although tmpnam(3) generates names that are difficult to guess, it is nevertheless possible that between the time that tmpnam(3) returns a pathname, and the time that the program opens it, another program might create that pathname using open(2), or create it as a symbolic link. This can lead to security holes. To avoid such possibilities, use the open(2) O_EXCL flag to open the pathname. Or better yet, use mkstemp(3) or tmpfile(3).

Portable applications that use threads cannot call tmpnam() with NULL parameter if either _POSIX_THREADS or _POSIX_THREAD_SAFE_FUNCTIONS is defined.

A POSIX draft proposed to use a function tmpnam_r() defined by

char *
tmpnam_r(char *s)
{
    return s ? tmpnam(s) : NULL;
}

apparently as a warning not to use NULL. A few systems implement it. To get a glibc prototype for this function, define _SVID_SOURCE or _BSD_SOURCE before including <stdio.h>.

BUGS

Never use this function. Use mkstemp(3) or tmpfile(3) instead.

SEE ALSO

mkstemp(3), mktemp(3), tempnam(3), tmpfile(3)


tolower (3)

 Continue to this page.


twalk (3)

 Continue to this page.


ulimit(3)

ULIMIT

Section: Linux Programmer's Manual (3)
Updated: 1998-06-12 Return to Main Contents

NAME

ulimit - get and set user limits

SYNOPSIS

#include <ulimit.h>

long ulimit(int cmd, long newlimit);

DESCRIPTION

Warning: This routine is obsolete. The include file is no longer provided by glibc. Use getrlimit(2), setrlimit(2) and sysconf(3) instead. For the shell command ulimit(), see bash(1).

The ulimit() call will get or set some limit for the current process. The cmd argument can have one of the following values.

UL_GETFSIZE
Return the limit on the size of a file, in units of 512 bytes.
UL_SETFSIZE
Set the limit on the size of a file.
3
(Not implemented for Linux.) Return the maximum possible address of the data segment.
4
(Implemented but no symbolic constant provided.) Return the maximum number of files that the calling process can open.

RETURN VALUE

On success, ulimit() returns a non-negative value. On error, -1 is returned, and errno is set appropriately.

ERRORS

EPERM
A non-root process tried to increase a limit.

CONFORMING TO

SVr4, POSIX.1-2001.

SEE ALSO

bash(1), getrlimit(2), setrlimit(2), sysconf(3)


cos(3)

COS

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

cos, cosf, cosl - cosine function

SYNOPSIS

#include <math.h>

double cos(double x);

float cosf(float x);

long double cosl(long double x);

Link with -lm.

DESCRIPTION

The cos() function returns the cosine of x, where x is given in radians.

RETURN VALUE

The cos() function returns a value between -1 and 1.

CONFORMING TO

SVr4, 4.3BSD, C99. The float and long double variants are C99 requirements.

SEE ALSO

acos(3), asin(3), atan(3), atan2(3), ccos(3), sin(3), tan(3)


unsetenv (3)

 Continue to this page.


va_arg (3)

 Continue to this page.


ungetc (3)

 Continue to this page.


va_end (3)

 Continue to this page.


ctime(3)

CTIME

Section: Linux Programmer's Manual (3)
Updated: 2004-11-16 Return to Main Contents

NAME

asctime, ctime, gmtime, localtime, mktime, asctime_r, ctime_r, gmtime_r, localtime_r - transform date and time to broken-down time or ASCII

SYNOPSIS

#include <time.h>

char *asctime(const struct tm *tm);

char *asctime_r(const struct tm *tm, char *buf);

char *ctime(const time_t *timep);

char *ctime_r(const time_t *timep, char *buf);

struct tm *gmtime(const time_t *timep);

struct tm *gmtime_r(const time_t *timep, struct tm *result);

struct tm *localtime(const time_t *timep);

struct tm *localtime_r(const time_t *timep, struct tm *result);

time_t mktime(struct tm *tm);

DESCRIPTION

The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC).

The asctime() and mktime() functions both take an argument representing broken-down time which is a representation separated into year, month, day, etc.

Broken-down time is stored in the structure tm which is defined in <time.h> as follows:

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};

The members of the tm structure are:

tm_sec
The number of seconds after the minute, normally in the range 0 to 59, but can be up to 60 to allow for leap seconds.
tm_min
The number of minutes after the hour, in the range 0 to 59.
tm_hour
The number of hours past midnight, in the range 0 to 23.
tm_mday
The day of the month, in the range 1 to 31.
tm_mon
The number of months since January, in the range 0 to 11.
tm_year
The number of years since 1900.
tm_wday
The number of days since Sunday, in the range 0 to 6.
tm_yday
The number of days since January 1, in the range 0 to 365.
tm_isdst
A flag that indicates whether daylight saving time is in effect at the time described. The value is positive if daylight saving time is in effect, zero if it is not, and negative if the information is not available.

The call ctime(t) is equivalent to asctime(localtime(t)). It converts the calendar time t into a string of the form

"Wed Jun 30 21:49:08 1993\n"

The abbreviations for the days of the week are `Sun', `Mon', `Tue', `Wed', `Thu', `Fri', and `Sat'. The abbreviations for the months are `Jan', `Feb', `Mar', `Apr', `May', `Jun', `Jul', `Aug', `Sep', `Oct', `Nov', and `Dec'. The return value points to a statically allocated string which might be overwritten by subsequent calls to any of the date and time functions. The function also sets the external variable tzname (see tzset(3)) with information about the current time zone. The re-entrant version ctime_r() does the same, but stores the string in a user-supplied buffer of length at least 26. It need not set tzname.

The gmtime() function converts the calendar time timep to broken-down time representation, expressed in Coordinated Universal Time (UTC). It may return NULL when the year does not fit into an integer. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions. The gmtime_r() function does the same, but stores the data in a user-supplied struct.

The localtime() function converts the calendar time timep to broken-time representation, expressed relative to the user's specified time zone. The function acts as if it called tzset(3) and sets the external variables tzname with information about the current time zone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a non-zero value if daylight savings time rules apply during some part of the year. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions. The localtime_r() function does the same, but stores the data in a user-supplied struct. It need not set tzname.

The asctime() function converts the broken-down time value tm into a string with the same format as ctime(). The return value points to a statically allocated string which might be overwritten by subsequent calls to any of the date and time functions. The asctime_r() function does the same, but stores the string in a user-supplied buffer of length at least 26.

The mktime() function converts a broken-down time structure, expressed as local time, to calendar time representation. The function ignores the specified contents of the structure members tm_wday and tm_yday and recomputes them from the other information in the broken-down time structure. If structure members are outside their legal interval, they will be normalized (so that, for example, 40 October is changed into 9 November). Calling mktime() also sets the external variable tzname with information about the current time zone. If the specified broken-down time cannot be represented as calendar time (seconds since the epoch), mktime() returns a value of (time_t)(-1) and does not alter the tm_wday and tm_yday members of the broken-down time structure.

RETURN VALUE

Each of these functions returns the value described, or NULL (-1 in case of mktime()) in case an error was detected.

CONFORMING TO

POSIX.1-2001. C89 and C99 specify asctime(), ctime(), gmtime(), localtime(), and mktime()

NOTES

The four functions asctime(), ctime(), gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Thread-safe versions asctime_r(), ctime_r(), gmtime_r() and localtime_r() are specified by SUSv2, and available since libc 5.2.5.

In many implementations, including glibc, a 0 in tm_mday is interpreted as meaning the last day of the preceding month.

The glibc version of struct tm has additional fields

long tm_gmtoff;           /* Seconds east of UTC */
const char *tm_zone;      /* Timezone abbreviation */

defined when _BSD_SOURCE was set before including <time.h>. This is a BSD extension, present in 4.3BSD-Reno.

SEE ALSO

date(1), gettimeofday(2), time(2), utime(2), clock(3), difftime(3), strftime(3), strptime(3), tzset(3), time(7)


isalpha(3)

ISALPHA

Section: Linux Programmer's Manual (3)
Updated: 1995-09-02 Return to Main Contents

NAME

isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit - character classification routines

SYNOPSIS

#include <ctype.h>

int isalnum(int c);

int isalpha(int c);

int isascii(int c);

int isblank(int c);

int iscntrl(int c);

int isdigit(int c);

int isgraph(int c);

int islower(int c);

int isprint(int c);

int ispunct(int c);

int isspace(int c);

int isupper(int c);

int isxdigit(int c);

DESCRIPTION

These functions check whether c, which must have the value of an unsigned char or EOF, falls into a certain character class according to the current locale.
isalnum()
checks for an alphanumeric character; it is equivalent to (isalpha(c) || isdigit(c)).
isalpha()
checks for an alphabetic character; in the standard "C" locale, it is equivalent to (isupper(c) || islower(c)). In some locales, there may be additional characters for which isalpha() is true---letters which are neither upper case nor lower case.
isascii()
checks whether c is a 7-bit unsigned char value that fits into the ASCII character set.
isblank()
checks for a blank character; that is, a space or a tab.
iscntrl()
checks for a control character.
isdigit()
checks for a digit (0 through 9).
isgraph()
checks for any printable character except space.
islower()
checks for a lower-case character.
isprint()
checks for any printable character including space.
ispunct()
checks for any printable character which is not a space or an alphanumeric character.
isspace()
checks for white-space characters. In the C and POSIX locales, these are: space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v').
isupper()
checks for an uppercase letter.
isxdigit()
checks for a hexadecimal digits, that is, one of
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F.

RETURN VALUE

The values returned are non-zero if the character c falls into the tested class, and a zero value if not.

CONFORMING TO

C99, 4.3BSD. C89 specifies all of these functions except isascii() and isblank(). isascii() is a BSD extension and is also an SVr4 extension. isblank() conforms to POSIX.1-2001 and C99 7.4.1.3.

NOTES

The details of what characters belong into which class depend on the current locale. For example, isupper() will not recognize an A-umlaut (:A) as an uppercase letter in the default C locale.

SEE ALSO

iswalnum(3), iswalpha(3), iswblank(3), iswcntrl(3), iswdigit(3), iswgraph(3), iswlower(3), iswprint(3), iswpunct(3), iswspace(3), iswupper(3), iswxdigit(3), setlocale(3), tolower(3), toupper(3), ascii(7), locale(7)


catclose (3)

 Continue to this page.


res_mkquery (3)

 Continue to this page.


scanf(3)

SCANF

Section: Linux Programmer's Manual (3)
Updated: 1995-11-01 Return to Main Contents

NAME

scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf - input format conversion

SYNOPSIS

#include <stdio.h>
int scanf(const char *format, ...);

int fscanf(FILE *stream, const char *format, ...);

int sscanf(const char *str, const char *format, ...);

#include <stdarg.h>
int vscanf(const char *format, va_list ap);

int vsscanf(const char *str, const char *format, va_list ap);

int vfscanf(FILE *stream, const char *format, va_list ap);

DESCRIPTION

The scanf() family of functions scans input according to format as described below. This format may contain conversion specifications; the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format. Each pointer argument must be of a type that is appropriate for the value returned by the corresponding conversion specification.

If the number of conversion specifications in format exceeds the number of pointer arguments, the results are undefined. If the number of pointer arguments exceeds the number of conversion specifications, then the excess pointer arguments are evaluated, but are otherwise ignored.

The scanf() function reads input from the standard input stream stdin, fscanf() reads input from the stream pointer stream, and sscanf() reads its input from the character string pointed to by str.

The vfscanf() function is analogous to vfprintf(3) and reads input from the stream pointer stream using a variable argument list of pointers (see stdarg(3). The vscanf() function scans a variable argument list from the standard input and the vsscanf() function scans it from a string; these are analogous to the vprintf(3) and vsprintf(3) functions respectively.

The format string consists of a sequence of directives which describe how to process the sequence of input characters. If processing of a directive fails, no further input is read, and scanf() returns. A "failure" can be either of the following: input failure, meaning that input characters were unavailable, or matching failure, meaning that the input was inappropriate (see below).

A directive is one of the following:

*
A sequence of white-space characters (space, tab, newline, etc; see isspace(3)). This directive matches any amount of white space, including none, in the input.
*
An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input.
*
A conversion specification, which commences with a '%' (percent) character. A sequence of characters from the input is converted according to this specification, and the result is placed in the corresponding pointer argument. If the next item of input does not match the the conversion specification, the conversion fails --- this is a matching failure.

Each conversion specification in format begins with either the character '%' or the character sequence "%n$" (see below for the distinction) followed by:

*
An optional '*' assignment-suppression character: scanf() reads input as directed by the conversion specification, but discards the input. No corresponding pointer argument is required, and this specification is not included in the count of successful assignments returned by scanf().
*
An optional 'a' character. This is used with string conversions, and relieves the caller of the need to allocate a corresponding buffer to hold the input: instead, scanf() allocates a buffer of sufficient size, and assigns the address of this buffer to the corresponding pointer argument, which should be a pointer to a char * variable (this variable does not need to be initialized before the call). The caller should subsequently free(3) this buffer when it is no longer required. This is a GNU extension; C99 employs the 'a' character as a conversion specifier (and it can also be used as such in the GNU implementation).
*
An optional decimal integer which specifies the maximum field width. Reading of characters stops either when this maximum is reached or when a non-matching character is found, whichever happens first. Most conversions discard initial whitespace characters (the exceptions are noted below), and these discarded characters don't count towards the maximum field width. String input conversions store a null terminator ('\0') to mark the end of the input; the maximum field width does not include this terminator.
*
An optional type modifier character. For example, the l type modifier is used with integer conversions such as %d to specify that the corresponding pointer argument refers to a long int rather than a pointer to an int.
*
A conversion specifier that specifies the type of input conversion to be performed.

The conversion specifications in format are of two forms, either beginning with '%' or beginning with "%n$". The two forms should not be mixed in the same format string, except that a string containing "%n$" specifications can include %% and %*. If format contains '%' specifications then these correspond in order with successive pointer arguments. In the "%n$" form (which is specified in POSIX.1-2001, but not C99), n is a decimal integer that specifies that the converted input should be placed in the location referred to by the n-th pointer argument following format.

Conversions

The following type modifier characters can appear in a conversion specification:
h
Indicates that the conversion will be one of diouxX or n and the next pointer is a pointer to a short int or unsigned short int (rather than int).
hh
As for h, but the next pointer is a pointer to a signed char or unsigned char.
j
As for h, but the next pointer is a pointer to a intmax_t or uintmax_t. This modifier was introduced in C99.
l
Indicates either that the conversion will be one of diouxX or n and the next pointer is a pointer to a long int or unsigned long int (rather than int), or that the conversion will be one of efg and the next pointer is a pointer to double (rather than float). Specifying two l characters is equivalent to L. If used with %c or %s the corresponding parameter is considered as a pointer to a wide character or wide-character string respectively.
L
Indicates that the conversion will be either efg and the next pointer is a pointer to long double or the conversion will be dioux and the next pointer is a pointer to long long.
q
equivalent to L. This specifier does not exist in ANSI C.
t
As for h, but the next pointer is a pointer to a ptrdiff_t. This modifier was introduced in C99.
z
As for h, but the next pointer is a pointer to a size_t. This modifier was introduced in C99.

The following conversion specifiers are available:

%
Matches a literal '%'. That is, %% in the format string matches a single input '%' character. No conversion is done, and assignment does not occur.
d
Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
D
Equivalent to ld; this exists only for backwards compatibility. (Note: thus only in libc4. In libc5 and glibc the %D is silently ignored, causing old programs to fail mysteriously.)
i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.
o
Matches an unsigned octal integer; the next pointer must be a pointer to unsigned int.
u
Matches an unsigned decimal integer; the next pointer must be a pointer to unsigned int.
x
Matches an unsigned hexadecimal integer; the next pointer must be a pointer to unsigned int.
X
Equivalent to x.
f
Matches an optionally signed floating-point number; the next pointer must be a pointer to float.
e
Equivalent to f.
g
Equivalent to f.
E
Equivalent to f.
a
(C99) Equivalent to f.
s
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
c
Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.
[
Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer to char, and there must be enough room for all the characters in the string, plus a terminating null byte. The usual skip of leading white space is suppressed. The string is to be made up of characters in (or not in) a particular set; the set is defined by the characters between the open bracket [ character and a close bracket ] character. The set excludes those characters if the first character after the open bracket is a circumflex (^). To include a close bracket in the set, make it the first character after the open bracket or the circumflex; any other position will end the set. The hyphen character - is also special; when placed between two other characters, it adds all intervening characters to the set. To include a hyphen, make it the last character before the final close bracket. For instance, [^]0-9-] means the set "everything except close bracket, zero through nine, and hyphen". The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the field width runs out.
p
Matches a pointer value (as printed by %p in printf(3); the next pointer must be a pointer to a pointer to void.
n
Nothing is expected; instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer to int. This is not a conversion, although it can be suppressed with the * assignment-suppression character. The C standard says: "Execution of a %n directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of %n conversions on the return value.

RETURN VALUE

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

CONFORMING TO

The functions fscanf(), scanf(), and sscanf() conform to C89 and C99.

The q specifier is the 4.4BSD notation for long long, while ll or the usage of L in integer conversions is the GNU notation.

The Linux version of these functions is based on the GNU libio library. Take a look at the info documentation of GNU libc (glibc-1.08) for a more concise description.

BUGS

All functions are fully C89 conformant, but provide the additional specifiers q and a as well as an additional behavior of the L and l specifiers. The latter may be considered to be a bug, as it changes the behavior of specifiers defined in C89.

Some combinations of the type modifiers and conversion specifiers defined by ANSI C do not make sense (e.g. %Ld). While they may have a well-defined behavior on Linux, this need not to be so on other architectures. Therefore it usually is better to use modifiers that are not defined by ANSI C at all, that is, use q instead of L in combination with diouxX conversions or ll.

The usage of q is not the same as on 4.4BSD, as it may be used in float conversions equivalently to L.

SEE ALSO

getc(3), printf(3), setlocale(3), strtod(3), strtol(3), strtoul(3)


opendir(3)

OPENDIR

Section: Linux Programmer's Manual (3)
Updated: 1995-06-11 Return to Main Contents

NAME

opendir - open a directory

SYNOPSIS

#include <sys/types.h>

#include <dirent.h>

DIR *opendir(const char *name);

DESCRIPTION

The opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the directory stream. The stream is positioned at the first entry in the directory.

RETURN VALUE

The opendir() function returns a pointer to the directory stream. On error, NULL is returned, and errno is set appropriately.

ERRORS

EACCES
Permission denied.
EMFILE
Too many file descriptors in use by process.
ENFILE
Too many files are currently open in the system.
ENOENT
Directory does not exist, or name is an empty string.
ENOMEM
Insufficient memory to complete the operation.
ENOTDIR
name is not a directory.

CONFORMING TO

SVr4, 4.3BSD, POSIX.1-2001.

NOTES

The underlying file descriptor of the directory stream can be obtained using dirfd(3).

SEE ALSO

open(2), closedir(3), dirfd(3), readdir(3), rewinddir(3), scandir(3), seekdir(3), telldir(3)


exp(3)

EXP

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

exp, expf, expl - base-e exponential function

SYNOPSIS

#include <math.h>

double exp(double x);

float expf(float x);

long double expl(long double x);

Link with -lm.

DESCRIPTION

The exp() function returns the value of e (the base of natural logarithms) raised to the power of x.

CONFORMING TO

SVr4, 4.3BSD, C89, C99, POSIX.1-2001. The float and long double variants are C99 requirements.

SEE ALSO

cbrt(3), cexp(3), exp10(3), exp2(3), sqrt(3)


hcreate (3)

 Continue to this page.


hypot(3)

HYPOT

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

hypot, hypotf, hypotl - Euclidean distance function

SYNOPSIS

#include <math.h>

double hypot(double x, double y);

float hypotf(float x, float y);

long double hypotl(long double x, long double y);

Link with -lm.

DESCRIPTION

The hypot() function returns sqrt(x*x+y*y). This is the length of the hypotenuse of a right-angle triangle with sides of length x and y, or the distance of the point (x,y) from the origin.

CONFORMING TO

SVr4, 4.3BSD, C99. The float and long double variants are C99 requirements.

SEE ALSO

cabs(3), sqrt(3)


re_comp(3)

RE_COMP

Section: Linux Programmer's Manual (3)
Updated: 1995-07-14 Return to Main Contents

NAME

re_comp, re_exec - BSD regex functions

SYNOPSIS

#define _REGEX_RE_COMP
#include <sys/types.h>
#include <regex.h>

char *re_comp(char *regex);
int re_exec(char *string);

DESCRIPTION

re_comp() is used to compile the null-terminated regular expression pointed to by regex. The compiled pattern occupies a static area, the pattern buffer, which is overwritten by subsequent use of re_comp(). If regex is NULL, no operation is performed and the pattern buffer's contents are not altered.

re_exec() is used to assess whether the null-terminated string pointed to by string matches the previously compiled regex.

RETURN VALUE

re_comp() returns NULL on successful compilation of regex otherwise it returns a pointer to an appropriate error message.

re_exec() returns 1 for a successful match, zero for failure.

CONFORMING TO

4.3BSD

NOTES

These functions are obsolete; the functions documented in regcomp(3) should be used instead.

SEE ALSO

regcomp(3), regex(7), GNU regex manual


strcasecmp(3)

STRCASECMP

Section: Linux Programmer's Manual (3)
Updated: 1993-04-11 Return to Main Contents

NAME

strcasecmp, strncasecmp - compare two strings ignoring case

SYNOPSIS

#include <strings.h>

int strcasecmp(const char *s1, const char *s2);

int strncasecmp(const char *s1, const char *s2, size_t n);

DESCRIPTION

The strcasecmp() function compares the two strings s1 and s2, ignoring the case of the characters. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

The strncasecmp() function is similar, except it only compares the first n characters of s1.

RETURN VALUE

The strcasecmp() and strncasecmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

CONFORMING TO

4.4BSD, POSIX.1-2001

SEE ALSO

bcmp(3), memcmp(3), strcmp(3), strcoll(3), strncmp(3), wcscasecmp(3), wcsncasecmp(3)


vfprintf (3)

 Continue to this page.


iscntrl (3)

 Continue to this page.


feof (3)

 Continue to this page.


sprintf (3)

 Continue to this page.


fgets (3)

 Continue to this page.


seekdir(3)

SEEKDIR

Section: Linux Programmer's Manual (3)
Updated: 1993-03-31 Return to Main Contents

NAME

seekdir - set the position of the next readdir() call in the directory stream.

SYNOPSIS

#include <dirent.h>

void seekdir(DIR *dir, off_t offset);

DESCRIPTION

The seekdir() function sets the location in the directory stream from which the next readdir(2) call will start. seekdir() should be used with an offset returned by telldir(3).

RETURN VALUE

The seekdir() function returns no value.

CONFORMING TO

4.3BSD, POSIX.1-2001.

SEE ALSO

lseek(2), closedir(3), opendir(3), readdir(3), rewinddir(3), scandir(3), telldir(3)


setbuf(3)

SETBUF

Section: Linux Programmer's Manual (3)
Updated: 2001-06-09 Return to Main Contents

NAME

setbuf, setbuffer, setlinebuf, setvbuf - stream buffering operations

SYNOPSIS

#include <stdio.h>

void setbuf(FILE *stream, char *buf);
void setbuffer(FILE *stream, char *buf, size_t size);
void setlinebuf(FILE *stream);
int setvbuf(FILE *stream, char *buf, int mode

, size_t size);

DESCRIPTION

The three types of buffering available are unbuffered, block buffered, and line buffered. When an output stream is unbuffered, information appears on the destination file or terminal as soon as written; when it is block buffered many characters are saved up and written as a block; when it is line buffered characters are saved up until a newline is output or input is read from any stream attached to a terminal device (typically stdin). The function fflush(3) may be used to force the block out early. (See fclose(3).) Normally all files are block buffered. When the first I/O operation occurs on a file, malloc(3) is called, and a buffer is obtained. If a stream refers to a terminal (as stdout normally does) it is line buffered. The standard error stream stderr is always unbuffered by default.

The setvbuf() function may be used on any open stream to change its buffer. The mode parameter must be one of the following three macros:

_IONBF
unbuffered
_IOLBF
line buffered
_IOFBF
fully buffered

Except for unbuffered files, the buf argument should point to a buffer at least size bytes long; this buffer will be used instead of the current buffer. If the argument buf is NULL, only the mode is affected; a new buffer will be allocated on the next read or write operation. The setvbuf() function may only be used after opening a stream and before any other operations have been performed on it.

The other three calls are, in effect, simply aliases for calls to setvbuf(). The setbuf() function is exactly equivalent to the call

setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);

The setbuffer() function is the same, except that the size of the buffer is up to the caller, rather than being determined by the default BUFSIZ. The setlinebuf() function is exactly equivalent to the call:

setvbuf(stream, (char *) NULL, _IOLBF, 0);

RETURN VALUE

The function setvbuf() returns 0 on success. It can return any value on failure, but returns non-zero when mode is invalid or the request cannot be honored. It may set errno on failure. The other functions are void.

CONFORMING TO

The setbuf() and setvbuf() functions conform to C89 and C99.

BUGS

The setbuffer() and setlinebuf() functions are not portable to versions of BSD before 4.2BSD, and are available under Linux since libc 4.5.21. On 4.2BSD and 4.3BSD systems, setbuf() always uses a suboptimal buffer size and should be avoided. You must make sure that both buf and the space it points to still exist by the time stream is closed, which also happens at program termination. For example, the following is illegal:

#include <stdio.h>

int
main(void)
{
    char buf[BUFSIZ];
    setbuf(stdin, buf);
    printf("Hello, world!\n");
    return 0;
}

SEE ALSO

fclose(3), fflush(3), fopen(3), fread(3), malloc(3), printf(3), puts(3)


logwtmp (3)

 Continue to this page.


strdup(3)

STRDUP

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strdup, strndup, strdupa, strndupa - duplicate a string

SYNOPSIS

#include <string.h>

char *strdup(const char *s);

#define _GNU_SOURCE

#include <string.h>

char *strndup(const char *s, size_t n);

char *strdupa(const char *s);

char *strndupa(const char *s, size_t n);

DESCRIPTION

The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).

The strndup() function is similar, but only copies at most n characters. If s is longer than n, only n characters are copied, and a terminating null byte ('\0') is added.

strdupa() and strndupa() are similar, but use alloca(3) to allocate the buffer. They are only available when using the GNU GCC suite, and suffer from the same limitations described in alloca(3).

RETURN VALUE

The strdup() function returns a pointer to the duplicated string, or NULL if insufficient memory was available.

ERRORS

ENOMEM
Insufficient memory available to allocate duplicate string.

CONFORMING TO

strdup() conforms to SVr4, 4.3BSD, POSIX.1-2001. strndup(), strdupa(), and strndupa() are GNU extensions.

SEE ALSO

alloca(3), calloc(3), free(3), malloc(3), realloc(3), wcsdup(3), feature_test_macros(7)


catgets(3)

CATGETS

Section: Linux Programmer's Manual (3)
Updated: 1998-08-09 Return to Main Contents

NAME

catgets - get message from a message catalog

SYNOPSIS

#include <nl_types.h>

char *catgets(nl_catd catalog, int set_number, int message_number,
              const char *message);

DESCRIPTION

catgets() reads the message message_number, in set set_number, from the message catalog identified by catalog, where catalog is a catalog descriptor returned from an earlier call to catopen(3). The fourth argument message points to a default message string which will be returned by catgets() if the identified message catalog is not currently available. The message-text is contained in an internal buffer area and should be copied by the application if it is to be saved or modified. The return string is always terminated with a null byte.

RETURN VALUE

On success, catgets() returns a pointer to an internal buffer area containing the null-terminated message string. On failure, catgets() returns the value message.

CONFORMING TO

POSIX.1-2001.

NOTES

These functions are only available in libc.so.4.4.4c and above. The Jan 1987 X/Open Portability Guide specifies a more subtle error return: message is returned if the message catalog specified by catalog is not available, while an empty string is returned when the message catalog is available but does not contain the specified message. These two possible error returns seem to be discarded in SUSv2 in favor of always returning message.

SEE ALSO

catopen(3), setlocale(3)


lrand48 (3)

 Continue to this page.


drand48(3)

DRAND48

Section: Linux Programmer's Manual (3)
Updated: 1993-07-02 Return to Main Contents

NAME

drand48, erand48, lrand48, nrand48, mrand48, jrand48, srand48, seed48, lcong48 - generate uniformly distributed pseudo-random numbers

SYNOPSIS

#include <stdlib.h>

double drand48(void);

double erand48(unsigned short xsubi[3]);

long int lrand48(void);

long int nrand48(unsigned short xsubi[3]);

long int mrand48(void);

long int jrand48(unsigned short xsubi[3]);

void srand48(long int seedval);

unsigned short *seed48(unsigned short seed16v[3]);

void lcong48(unsigned short param[7]);

DESCRIPTION

These functions generate pseudo-random numbers using the linear congruential algorithm and 48-bit integer arithmetic.

The drand48() and erand48() functions return non-negative double-precision floating-point values uniformly distributed between [0.0, 1.0).

The lrand48() and nrand48() functions return non-negative long integers uniformly distributed between 0 and 2^31.

The mrand48() and jrand48() functions return signed long integers uniformly distributed between -2^31 and 2^31.

The srand48(), seed48() and lcong48() functions are initialization functions, one of which should be called before using drand48(), lrand48() or mrand48(). The functions erand48(), nrand48() and jrand48() do not require an initialization function to be called first.

All the functions work by generating a sequence of 48-bit integers, Xi, according to the linear congruential formula:

Xn+1 = (aXn + c) mod m,   where n >= 0

The parameter m = 2^48, hence 48-bit integer arithmetic is performed. Unless lcong48() is called, a and c are given by:

a = 0x5DEECE66D
c = 0xB

The value returned by any of the functions drand48(), erand48(), lrand48(), nrand48(), mrand48() or jrand48() is computed by first generating the next 48-bit Xi in the sequence. Then the appropriate number of bits, according to the type of data item to be returned, is copied from the high-order bits of Xi and transformed into the returned value.

The functions drand48(), lrand48() and mrand48() store the last 48-bit Xi generated in an internal buffer. The functions erand48(), nrand48() and jrand48() require the calling program to provide storage for the successive Xi values in the array argument xsubi. The functions are initialized by placing the initial value of Xi into the array before calling the function for the first time.

The initializer function srand48() sets the high order 32-bits of Xi to the argument seedval. The low order 16-bits are set to the arbitrary value 0x330E.

The initializer function seed48() sets the value of Xi to the 48-bit value specified in the array argument seed16v. The previous value of Xi is copied into an internal buffer and a pointer to this buffer is returned by seed48().

The initialization function lcong48() allows the user to specify initial values for Xi, a and c. Array argument elements param[0-2] specify Xi, param[3-5] specify a, and param[6] specifies c. After lcong48() has been called, a subsequent call to either srand48() or seed48() will restore the standard values of a and c.

CONFORMING TO

SVr4, POSIX.1-2001.

NOTES

These functions are declared obsolete by SVID 3, which states that rand(3) should be used instead.

SEE ALSO

rand(3), random(3)


strfry(3)

STRFRY

Section: Linux Programmer's Manual (3)
Updated: 1993-04-12 Return to Main Contents

NAME

strfry - randomize a string

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

char *strfry(char *string);

DESCRIPTION

The strfry() function randomizes the contents of string by using rand(3) to randomly swap characters in the string. The result is an anagram of string.

RETURN VALUE

The strfry() functions returns a pointer to the randomized string.

CONFORMING TO

The strfry() function is unique to the GNU C Library.

SEE ALSO

memfrob(3), feature_test_macros(7)


strncasecmp (3)

 Continue to this page.


fread(3)

FREAD

Section: Linux Programmer's Manual (3)
Updated: 1996-05-17 Return to Main Contents

NAME

fread, fwrite - binary stream input/output

SYNOPSIS

#include <stdio.h>

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

size_t fwrite(const void *ptr, size_t size, size_t nmemb,
              FILE *stream);

DESCRIPTION

The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

The function fwrite() writes nmemb elements of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.

For non-locking counterparts, see unlocked_stdio(3).

RETURN VALUE

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.

CONFORMING TO

C89, POSIX.1-2001.

SEE ALSO

read(2), write(2), feof(3), ferror(3), unlocked_stdio(3)


res_init (3)

 Continue to this page.


regex(3)

REGEX

Section: Linux Programmer's Manual (3)
Updated: 1998-05-08 Return to Main Contents

NAME

regcomp, regexec, regerror, regfree - POSIX regex functions

SYNOPSIS

#include <sys/types.h>
#include <regex.h>

u int regcomp(regex_t *preg, const char *regex, int cflags);
u int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
u size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);
void regfree(regex_t *preg);

DESCRIPTION

POSIX Regex Compiling

regcomp() is used to compile a regular expression into a form that is suitable for subsequent regexec() searches.

regcomp() is supplied with preg, a pointer to a pattern buffer storage area; regex, a pointer to the null-terminated string and cflags, flags used to determine the type of compilation.

All regular expression searching must be done via a compiled pattern buffer, thus regexec() must always be supplied with the address of a regcomp() initialized pattern buffer.

cflags may be the bitwise-or of one or more of the following:

REG_EXTENDED
Use POSIX Extended Regular Expression syntax when interpreting regex. If not set, POSIX Basic Regular Expression syntax is used.
REG_ICASE
Do not differentiate case. Subsequent regexec() searches using this pattern buffer will be case insensitive.
REG_NOSUB
Support for substring addressing of matches is not required. The nmatch and pmatch parameters to regexec() are ignored if the pattern buffer supplied was compiled with this flag set.
REG_NEWLINE
Match-any-character operators don't match a newline.

A non-matching list ([^...]) not containing a newline does not match a newline.

Match-beginning-of-line operator (^) matches the empty string immediately after a newline, regardless of whether eflags, the execution flags of regexec(), contains REG_NOTBOL.

Match-end-of-line operator ($) matches the empty string immediately before a newline, regardless of whether eflags contains REG_NOTEOL.

POSIX Regex Matching

regexec() is used to match a null-terminated string against the precompiled pattern buffer, preg. nmatch and pmatch are used to provide information regarding the location of any matches. eflags may be the bitwise-or of one or both of REG_NOTBOL and REG_NOTEOL which cause changes in matching behavior described below.
REG_NOTBOL
The match-beginning-of-line operator always fails to match (but see the compilation flag REG_NEWLINE above) This flag may be used when different portions of a string are passed to regexec() and the beginning of the string should not be interpreted as the beginning of the line.
REG_NOTEOL
The match-end-of-line operator always fails to match (but see the compilation flag REG_NEWLINE above)

BYTE OFFSETS

Unless REG_NOSUB was set for the compilation of the pattern buffer, it is possible to obtain substring match addressing information. pmatch must be dimensioned to have at least nmatch elements. These are filled in by regexec() with substring match addresses. Any unused structure elements will contain the value -1.

The regmatch_t structure which is the type of pmatch is defined in regex.h.

typedef struct
{
regoff_t rm_so;
regoff_t rm_eo;
}

regmatch_t;

Each rm_so element that is not -1 indicates the start offset of the next largest substring match within the string. The relative rm_eo element indicates the end offset of the match.

Posix Error Reporting

regerror() is used to turn the error codes that can be returned by both regcomp() and regexec() into error message strings.

regerror() is passed the error code, errcode, the pattern buffer, preg, a pointer to a character string buffer, errbuf, and the size of the string buffer, errbuf_size. It returns the size of the errbuf required to contain the null-terminated error message string. If both errbuf and errbuf_size are non-zero, errbuf is filled in with the first errbuf_size - 1 characters of the error message and a terminating null.

POSIX Pattern Buffer Freeing

Supplying regfree() with a precompiled pattern buffer, preg will free the memory allocated to the pattern buffer by the compiling process, regcomp().

RETURN VALUE

regcomp() returns zero for a successful compilation or an error code for failure.

regexec() returns zero for a successful match or REG_NOMATCH for failure.

ERRORS

The following errors can be returned by regcomp():
REG_BADBR
Invalid use of back reference operator.
REG_BADPAT
Invalid use of pattern operators such as group or list.
REG_BADRPT
Invalid use of repetition operators such as using `*' as the first character.
REG_EBRACE
Un-matched brace interval operators.
REG_EBRACK
Un-matched bracket list operators.
REG_ECOLLATE
Invalid collating element.
REG_ECTYPE
Unknown character class name.
REG_EEND
Non specific error. This is not defined by POSIX.2.
REG_EESCAPE
Trailing backslash.
REG_EPAREN
Un-matched parenthesis group operators.
REG_ERANGE
Invalid use of the range operator, eg. the ending point of the range occurs prior to the starting point.
REG_ESIZE
Compiled regular expression requires a pattern buffer larger than 64Kb. This is not defined by POSIX.2.
REG_ESPACE
The regex routines ran out of memory.
REG_ESUBREG
Invalid back reference to a subexpression.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

grep(1), regex(7), GNU regex manual


setenv(3)

SETENV

Section: Linux Programmer's Manual (3)
Updated: 2004-05-09 Return to Main Contents

NAME

setenv - change or add an environment variable

SYNOPSIS

#include <stdlib.h>

int setenv(const char *name, const char *value, int overwrite);

int unsetenv(const char *name);

DESCRIPTION

The setenv() function adds the variable name to the environment with the value value, if name does not already exist. If name does exist in the environment, then its value is changed to value if overwrite is non-zero; if overwrite is zero, then the value of name is not changed.

The unsetenv() function deletes the variable name from the environment.

RETURN VALUE

The setenv() function returns zero on success, or -1 if there was insufficient space in the environment. The unsetenv() function returns zero on success, or -1 on error, with errno set to indicate the cause of the error.

ERRORS

EINVAL
name contained an '=' character.

CONFORMING TO

4.3BSD, POSIX.1-2001.

NOTES

Prior to glibc 2.2.2, unsetenv() was prototyped as returning void; more recent glibc versions follow the POSIX.1-2001-compliant prototype shown in the SYNOPSIS.

BUGS

POSIX.1-2001 specifies that if name contains an '=' character, then setenv() should fail with the error EINVAL; however, versions of glibc before 2.3.4 allowed an '=' sign in name.

SEE ALSO

clearenv(3), getenv(3), putenv(3), environ(7)


endhostent (3)

 Continue to this page.


free (3)

 Continue to this page.


ruserok (3)

 Continue to this page.


cfgetispeed (3)

 Continue to this page.


cfsetospeed (3)

 Continue to this page.


endnetent (3)

 Continue to this page.


endpwent (3)

 Continue to this page.


endusershell (3)

 Continue to this page.


fnmatch(3)

FNMATCH

Section: Linux Programmer's Manual (3)
Updated: 2000-10-15 Return to Main Contents

NAME

fnmatch - match filename or pathname

SYNOPSIS

#include <fnmatch.h>

int fnmatch(const char *pattern, const char *string, int flags);

DESCRIPTION

The fnmatch() function checks whether the string argument matches the pattern argument, which is a shell wildcard pattern.

The flags argument modifies the behavior; it is the bitwise OR of zero or more of the following flags:

FNM_NOESCAPE
If this flag is set, treat backslash as an ordinary character, instead of an escape character.
FNM_PATHNAME
If this flag is set, match a slash in string only with a slash in pattern and not by an asterisk (*) or a question mark (?) metacharacter, nor by a bracket expression ([]) containing a slash.
FNM_PERIOD
If this flag is set, a leading period in string has to be matched exactly by a period in pattern. A period is considered to be leading if it is the first character in string, or if both FNM_PATHNAME is set and the period immediately follows a slash.
FNM_FILE_NAME
This is a GNU synonym for FNM_PATHNAME.
FNM_LEADING_DIR
If this flag (a GNU extension) is set, the pattern is considered to be matched if it matches an initial segment of string which is followed by a slash. This flag is mainly for the internal use of glibc and is only implemented in certain cases.
FNM_CASEFOLD
If this flag (a GNU extension) is set, the pattern is matched case-insensitively.

RETURN VALUE

Zero if string matches pattern, FNM_NOMATCH if there is no match or another non-zero value if there is an error.

CONFORMING TO

POSIX.2. The FNM_FILE_NAME, FNM_LEADING_DIR, and FNM_CASEFOLD flags are GNU extensions.

SEE ALSO

sh(1), glob(3), scandir(3), wordexp(3), glob(7)


frexp(3)

FREXP

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

frexp, frexpf, frexpl - convert floating-point number to fractional and integral components

SYNOPSIS

#include <math.h>

double frexp(double x, int *exp);

float frexpf(float x, int *exp);

long double frexpl(long double x, int *exp);

Link with -lm.

DESCRIPTION

The frexp() function is used to split the number x into a normalized fraction and an exponent which is stored in exp.

RETURN VALUE

The frexp() function returns the normalized fraction. If the argument x is not zero, the normalized fraction is x times a power of two, and its absolute value is always in the range 1/2 (inclusive) to 1 (exclusive). If x is zero, then the normalized fraction is zero and zero is stored in exp.

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

EXAMPLE

#include <math.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    double x, r;
    int exp;

    x = strtod(argv[1], NULL);
    r = frexp(x, &exp);

    printf("frexp(%g, &e) = %g: %g * %d^%d = %g\n",
           x, r, r, FLT_RADIX, exp, x);
    exit(EXIT_SUCCESS);
} /* main */

This program produces results such as the following:

$ ./a.out 2560 frexp(2560, &e) = 0.625: 0.625 * 2^12 = 2560 $ ./a.out -4 frexp(-4, &e) = -0.5: -0.5 * 2^3 = -4

SEE ALSO

ldexp(3), modf(3)


fseek(3)

FSEEK

Section: Linux Programmer's Manual (3)
Updated: 1993-11-29 Return to Main Contents

NAME

fgetpos, fseek, fsetpos, ftell, rewind - reposition a stream

SYNOPSIS

#include <stdio.h>

int fseek(FILE *stream, long offset, int whence);
long ftell(FILE *stream);
void rewind(FILE *stream);
int fgetpos(FILE *stream, fpos_t *pos);
int fsetpos(FILE *stream, fpos_t *pos);

DESCRIPTION

The fseek() function sets the file position indicator for the stream pointed to by stream. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the current position indicator, or end-of-file, respectively. A successful call to the fseek() function clears the end-of-file indicator for the stream and undoes any effects of the ungetc(3) function on the same stream.

The ftell() function obtains the current value of the file position indicator for the stream pointed to by stream.

The rewind() function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to:

(void) fseek(stream, 0L, SEEK_SET)

except that the error indicator for the stream is also cleared (see clearerr(3)).

The fgetpos() and fsetpos() functions are alternate interfaces equivalent to ftell() and fseek() (with whence set to SEEK_SET), setting and storing the current value of the file offset into or from the object referenced by pos. On some non-UNIX systems an fpos_t object may be a complex object and these routines may be the only way to portably reposition a text stream.

RETURN VALUE

The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() return 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error.

ERRORS

EBADF
The stream specified is not a seekable stream.
EINVAL
The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR.

The functions fgetpos(), fseek(), fsetpos(), and ftell() may also fail and set errno for any of the errors specified for the routines fflush(3), fstat(2), lseek(2), and malloc(3).

CONFORMING TO

C89, C99.

SEE ALSO

lseek(2), fseeko(3)


getc (3)

 Continue to this page.


getdirentries(3)

GETDIRENTRIES

Section: Linux Programmer's Manual (3)
Updated: 1993-07-22 Return to Main Contents

NAME

getdirentries - get directory entries in a filesystem independent format

SYNOPSIS

#define _BSD_SOURCE or #define _SVID_SOURCE
#include <dirent.h>

ssize_t getdirentries(int fd, char *buf, size_t nbytes , off_t *basep);

DESCRIPTION

Read directory entries from the directory specified by fd into buf. At most nbytes are read. Reading starts at offset *basep, and *basep is updated with the new position after reading.

RETURN VALUE

getdirentries() returns the number of bytes read or zero when at the end of the directory. If an error occurs, -1 is returned, and errno is set appropriately.

ERRORS

See the Linux library source code for details.

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs, and a few other systems. Use opendir(3) and readdir(3) instead.

SEE ALSO

lseek(2), open(2), feature_test_macros(7)


getnetbyname (3)

 Continue to this page.


longjmp(3)

LONGJMP

Section: Linux Programmer's Manual (3)
Updated: 1997-03-02 Return to Main Contents

NAME

longjmp, siglongjmp - non-local jump to a saved stack context

SYNOPSIS

#include <setjmp.h>

void longjmp(jmp_buf env, int val);
void siglongjmp(sigjmp_buf env, int val);

DESCRIPTION

longjmp() and setjmp(3) are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. longjmp() restores the environment saved by the last call of setjmp(3) with the corresponding env argument. After longjmp() is completed, program execution continues as if the corresponding call of setjmp(3) had just returned the value val. longjmp() cannot cause 0 to be returned. If longjmp() is invoked with a second argument of 0, 1 will be returned instead. siglongjmp() is similar to longjmp() except for the type of its env argument. If the sigsetjmp(3) call that set this env used a non-zero savesigs flag, siglongjmp() also restores the set of blocked signals.

RETURN VALUE

These functions never return.

CONFORMING TO

C89, C99, and POSIX.1-2001 specify longjmp(). POSIX.1-2001 specifies siglongjmp().

NOTES

POSIX does not specify whether longjmp() will restore the signal context. If you want to save and restore signal masks, use siglongjmp(). longjmp() and siglongjmp() make programs hard to understand and maintain. If possible an alternative should be used.

SEE ALSO

setjmp(3), sigsetjmp(3)


setprotoent (3)

 Continue to this page.


sigismember (3)

 Continue to this page.


sigsetops(3)

SIGSETOPS

Section: Linux Programmer's Manual (3)
Updated: 2005-11-17 Return to Main Contents

NAME

sigemptyset, sigfillset, sigaddset, sigdelset, sigismember - POSIX signal set operations.

SYNOPSIS

#include <signal.h>

int sigemptyset(sigset_t *set);

int sigfillset(sigset_t *set);

int sigaddset(sigset_t *set, int signum);

int sigdelset(sigset_t *set, int signum);

int sigismember(const sigset_t *set, int signum);

DESCRIPTION

The sigsetops(3) functions allow the manipulation of POSIX signal sets.

sigemptyset() initializes the signal set given by set to empty, with all signals excluded from the set.

sigfillset() initializes set to full, including all signals.

sigaddset() and sigdelset() add and delete respectively signal signum from set.

sigismember() tests whether signum is a member of set.

RETURN VALUE

sigemptyset(), sigfillset(), sigaddset(), and sigdelset() return 0 on success and -1 on error.

sigismember() returns 1 if signum is a member of set, 0 if signum is not a member, and -1 on error.

ERRORS

EINVAL
sig is not a valid signal.

CONFORMING TO

POSIX.1-2001.

NOTES

Glibc Notes

If the _GNU_SOURCE feature test macro is defined, then <signal.h> exposes three other functions for manipulating signal sets.
int sigisemptyset(sigset_t *set);
returns 1 if set contains no signals, and 0 otherwise.
int sigorset(sigset_t *dest, sigset_t *left, sigset_t *right);
places the union of the sets left and right in dest.
int sigandset(sigset_t *dest, sigset_t *left, sigset_t *right);
places the intersection of the sets left and right in dest.

sigorset() and sigandset() return 0 on success, and -1 on failure.

These functions are non-standard (a few other systems provide similar functions) and their use should be avoided in portable applications.

SEE ALSO

sigaction(2), sigpending(2), sigprocmask(2), sigsuspend(2)


vfscanf (3)

 Continue to this page.


vsscanf (3)

 Continue to this page.


xdr(3)

XDR

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

xdr - library routines for external data representation

SYNOPSIS AND DESCRIPTION

These routines allow C programmers to describe arbitrary data structures in a machine-independent fashion. Data for remote procedure calls are transmitted using these routines.

xdr_array(xdrs, arrp, sizep, maxsize, elsize, elproc)
XDR *xdrs;
char **arrp;
u_int *sizep, maxsize, elsize;
xdrproc_t elproc;
A filter primitive that translates between variable-length arrays and their corresponding external representations. The parameter arrp is the address of the pointer to the array, while sizep is the address of the element count of the array; this element count cannot exceed maxsize. The parameter elsize is the sizeof each of the array's elements, and elproc is an XDR filter that translates between the array elements' C form, and their external representation. This routine returns one if it succeeds, zero otherwise.

xdr_bool(xdrs, bp)
XDR *xdrs;
bool_t *bp;
A filter primitive that translates between booleans (C integers) and their external representations. When encoding data, this filter produces values of either one or zero. This routine returns one if it succeeds, zero otherwise.

xdr_bytes(xdrs, sp, sizep, maxsize)
XDR *xdrs;
char **sp;
u_int *sizep, maxsize;
A filter primitive that translates between counted byte strings and their external representations. The parameter sp is the address of the string pointer. The length of the string is located at address sizep; strings cannot be longer than maxsize. This routine returns one if it succeeds, zero otherwise.

xdr_char(xdrs, cp)
XDR *xdrs;
char *cp;
A filter primitive that translates between C characters and their external representations. This routine returns one if it succeeds, zero otherwise. Note: encoded characters are not packed, and occupy 4 bytes each. For arrays of characters, it is worthwhile to consider xdr_bytes(), xdr_opaque() or xdr_string().

void
xdr_destroy(xdrs)
XDR *xdrs;
A macro that invokes the destroy routine associated with the XDR stream, xdrs. Destruction usually involves freeing private data structures associated with the stream. Using xdrs after invoking xdr_destroy() is undefined.

xdr_double(xdrs, dp)
XDR *xdrs;
double *dp;
A filter primitive that translates between C double precision numbers and their external representations. This routine returns one if it succeeds, zero otherwise.

xdr_enum(xdrs, ep)
XDR *xdrs;
enum_t *ep;
A filter primitive that translates between C enums (actually integers) and their external representations. This routine returns one if it succeeds, zero otherwise.

xdr_float(xdrs, fp)
XDR *xdrs;
float *fp;
A filter primitive that translates between C floats and their external representations. This routine returns one if it succeeds, zero otherwise.

void
xdr_free(proc, objp)
xdrproc_t proc;
char *objp;
Generic freeing routine. The first argument is the XDR routine for the object being freed. The second argument is a pointer to the object itself. Note: the pointer passed to this routine is not freed, but what it points to is freed (recursively).

u_int
xdr_getpos(xdrs)
XDR *xdrs;
A macro that invokes the get-position routine associated with the XDR stream, xdrs. The routine returns an unsigned integer, which indicates the position of the XDR byte stream. A desirable feature of XDR streams is that simple arithmetic works with this number, although the XDR stream instances need not guarantee this.

long *
xdr_inline(xdrs, len)
XDR *xdrs;
int len;
A macro that invokes the in-line routine associated with the XDR stream, xdrs. The routine returns a pointer to a contiguous piece of the stream's buffer; len is the byte length of the desired buffer. Note: pointer is cast to long *.
Warning: xdr_inline() may return NULL (0) if it cannot allocate a contiguous piece of a buffer. Therefore the behavior may vary among stream instances; it exists for the sake of efficiency.

xdr_int(xdrs, ip)
XDR *xdrs;
int *ip;
A filter primitive that translates between C integers and their external representations. This routine returns one if it succeeds, zero otherwise.

xdr_long(xdrs, lp)
XDR *xdrs;
long *lp;
A filter primitive that translates between C long integers and their external representations. This routine returns one if it succeeds, zero otherwise.

void
xdrmem_create(xdrs, addr, size, op)
XDR *xdrs;
char *addr;
u_int size;
enum xdr_op op;
This routine initializes the XDR stream object pointed to by xdrs. The stream's data is written to, or read from, a chunk of memory at location addr whose length is no more than size bytes long. The op determines the direction of the XDR stream (either XDR_ENCODE, XDR_DECODE, or XDR_FREE).

xdr_opaque(xdrs, cp, cnt)
XDR *xdrs;
char *cp;
u_int cnt;
A filter primitive that translates between fixed size opaque data and its external representation. The parameter cp is the address of the opaque object, and cnt is its size in bytes. This routine returns one if it succeeds, zero otherwise.

xdr_pointer(xdrs, objpp, objsize, xdrobj)
XDR *xdrs;
char **objpp;
u_int objsize;
xdrproc_t xdrobj;
Like xdr_reference() except that it serializes NULL pointers, whereas xdr_reference() does not. Thus, xdr_pointer() can represent recursive data structures, such as binary trees or linked lists.

void
xdrrec_create(xdrs, sendsize, recvsize, handle, readit, writeit)
XDR *xdrs;
u_int sendsize, recvsize;
char *handle;
int (*readit) (), (*writeit) ();
This routine initializes the XDR stream object pointed to by xdrs. The stream's data is written to a buffer of size sendsize; a value of zero indicates the system should use a suitable default. The stream's data is read from a buffer of size recvsize; it too can be set to a suitable default by passing a zero value. When a stream's output buffer is full, writeit is called. Similarly, when a stream's input buffer is empty, readit is called. The behavior of these two routines is similar to the system calls read(2) and write(2), except that handle is passed to the former routines as the first parameter. Note: the XDR stream's op field must be set by the caller.
Warning: this XDR stream implements an intermediate record stream. Therefore there are additional bytes in the stream to provide record boundary information.

xdrrec_endofrecord(xdrs, sendnow)
XDR *xdrs;
int sendnow;
This routine can be invoked only on streams created by xdrrec_create(). The data in the output buffer is marked as a completed record, and the output buffer is optionally written out if sendnow is non-zero. This routine returns one if it succeeds, zero otherwise.

xdrrec_eof(xdrs)
XDR *xdrs;
int empty;
This routine can be invoked only on streams created by xdrrec_create(). After consuming the rest of the current record in the stream, this routine returns one if the stream has no more input, zero otherwise.

xdrrec_skiprecord(xdrs)
XDR *xdrs;
This routine can be invoked only on streams created by xdrrec_create(). It tells the XDR implementation that the rest of the current record in the stream's input buffer should be discarded. This routine returns one if it succeeds, zero otherwise.

xdr_reference(xdrs, pp, size, proc)
XDR *xdrs;
char **pp;
u_int size;
xdrproc_t proc;
A primitive that provides pointer chasing within structures. The parameter pp is the address of the pointer; size is the sizeof the structure that *pp points to; and proc is an XDR procedure that filters the structure between its C form and its external representation. This routine returns one if it succeeds, zero otherwise.
Warning: this routine does not understand NULL pointers. Use xdr_pointer() instead.

xdr_setpos(xdrs, pos)
XDR *xdrs;
u_int pos;
A macro that invokes the set position routine associated with the XDR stream xdrs. The parameter pos is a position value obtained from xdr_getpos(). This routine returns one if the XDR stream could be repositioned, and zero otherwise.
Warning: it is difficult to reposition some types of XDR streams, so this routine may fail with one type of stream and succeed with another.

xdr_short(xdrs, sp)
XDR *xdrs;
short *sp;
A filter primitive that translates between C short integers and their external representations. This routine returns one if it succeeds, zero otherwise.

void
xdrstdio_create(xdrs, file, op)
XDR *xdrs;
FILE *file;
enum xdr_op op;
This routine initializes the XDR stream object pointed to by xdrs. The XDR stream data is written to, or read from, the Standard I/O stream file. The parameter op determines the direction of the XDR stream (either XDR_ENCODE, XDR_DECODE, or XDR_FREE).
Warning: the destroy routine associated with such XDR streams calls fflush(3) on the file stream, but never fclose(3).

xdr_string(xdrs, sp, maxsize)
XDR
*xdrs;
char **sp;
u_int maxsize;
A filter primitive that translates between C strings and their corresponding external representations. Strings cannot be longer than maxsize. Note: sp is the address of the string's pointer. This routine returns one if it succeeds, zero otherwise.

xdr_u_char(xdrs, ucp)
XDR *xdrs;
unsigned char *ucp;
A filter primitive that translates between unsigned C characters and their external representations. This routine returns one if it succeeds, zero otherwise.

xdr_u_int(xdrs, up)
XDR *xdrs;
unsigned *up;
A filter primitive that translates between C unsigned integers and their external representations. This routine returns one if it succeeds, zero otherwise.

xdr_u_long(xdrs, ulp)
XDR *xdrs;
unsigned long *ulp;
A filter primitive that translates between C unsigned long integers and their external representations. This routine returns one if it succeeds, zero otherwise.

xdr_u_short(xdrs, usp)
XDR *xdrs;
unsigned short *usp;
A filter primitive that translates between C unsigned short integers and their external representations. This routine returns one if it succeeds, zero otherwise.

xdr_union(xdrs, dscmp, unp, choices, dfault)
XDR *xdrs;
int *dscmp;
char *unp;
struct xdr_discrim *choices;
bool_t (*defaultarm) ();  /* may equal NULL */
A filter primitive that translates between a discriminated C union and its corresponding external representation. It first translates the discriminant of the union located at dscmp. This discriminant is always an enum_t. Next the union located at unp is translated. The parameter choices is a pointer to an array of xdr_discrim() structures. Each structure contains an ordered pair of [value,proc]. If the union's discriminant is equal to the associated value, then the proc is called to translate the union. The end of the xdr_discrim() structure array is denoted by a routine of value NULL. If the discriminant is not found in the choices array, then the defaultarm procedure is called (if it is not NULL). Returns one if it succeeds, zero otherwise.

xdr_vector(xdrs, arrp, size, elsize, elproc)
XDR *xdrs;
char *arrp;
u_int size, elsize;
xdrproc_t elproc;
A filter primitive that translates between fixed-length arrays and their corresponding external representations. The parameter arrp is the address of the pointer to the array, while size is is the element count of the array. The parameter elsize is the sizeof each of the array's elements, and elproc is an XDR filter that translates between the array elements' C form, and their external representation. This routine returns one if it succeeds, zero otherwise.

xdr_void()
This routine always returns one. It may be passed to RPC routines that require a function parameter, where nothing is to be done.

xdr_wrapstring(xdrs, sp)
XDR *xdrs;
char **sp;
A primitive that calls xdr_string(xdrs, sp,MAXUN.UNSIGNED ); where MAXUN.UNSIGNED is the maximum value of an unsigned integer. xdr_wrapstring() is handy because the RPC package passes a maximum of two XDR routines as parameters, and xdr_string(), one of the most frequently used primitives, requires three. Returns one if it succeeds, zero otherwise.

SEE ALSO

rpc(3)

The following manuals:

eXternal Data Representation Standard: Protocol Specification
eXternal Data Representation: Sun Technical Notes
XDR: External Data Representation Standard, RFC 1014, Sun Microsystems, Inc., USC-ISI.


getrpcport(3)

GETRPCPORT

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

getrpcport - get RPC port number

SYNOPSIS

int getrpcport(host, prognum, versnum, proto)
        char *host;
        int prognum, versnum, proto;

DESCRIPTION

getrpcport() returns the port number for version versnum of the RPC program prognum running on host and using protocol proto. It returns 0 if it cannot contact the portmapper, or if prognum is not registered. If prognum is registered but not with version versnum, it will still return a port number (for some version of the program) indicating that the program is indeed registered. The version mismatch will be detected upon the first call to the service.

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs, Solaris, and many other systems.


getrpcent(3)

GETRPCENT

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

getrpcent, getrpcbyname, getrpcbynumber - get RPC entry

SYNOPSIS

#include <netdb.h>

struct rpcent *getrpcent()

struct rpcent *getrpcbyname(name)
char *name;

struct rpcent *getrpcbynumber(number)
int number;

setrpcent(stayopen)
int stayopen;

endrpcent()

DESCRIPTION

getrpcent(), getrpcbyname(), and getrpcbynumber() each return a pointer to an object with the following structure containing the broken-out fields of a line in the rpc program number data base, /etc/rpc.

struct  rpcent {
        char    *r_name;        /* name of server for this rpc program */
        char    **r_aliases;    /* alias list */
        long    r_number;       /* rpc program number */
};

The members of this structure are:

r_name
The name of the server for this rpc program.
r_aliases
A zero terminated list of alternate names for the rpc program.
r_number
The rpc program number for this service.

getrpcent() reads the next line of the file, opening the file if necessary.

setrpcent() opens and rewinds the file. If the stayopen flag is non-zero, the net data base will not be closed after each call to getrpcent() (either directly, or indirectly through one of the other ``getrpc'' calls).

endrpcent() closes the file.

getrpcbyname() and getrpcbynumber() sequentially search from the beginning of the file until a matching rpc program name or program number is found, or until end-of-file is encountered.

RETURN VALUE

A NULL pointer is returned on EOF or error.

FILES

/etc/rpc

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs, Solaris, and many other systems.

BUGS

All information is contained in a static area so it must be copied if it is to be saved.

SEE ALSO

rpc(5), rpcinfo(8), ypserv(8)


strnlen(3)

STRNLEN

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

strnlen - determine the length of a fixed-size string

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

size_t strnlen(const char *s, size_t maxlen);

DESCRIPTION

The strnlen() function returns the number of characters in the string pointed to by s, not including the terminating '\0' character, but at most maxlen. In doing this, strnlen() looks only at the first maxlen characters at s and never beyond s+maxlen.

RETURN VALUE

The strnlen() function returns strlen(s), if that is less than maxlen, or maxlen if there is no '\0' character among the first maxlen characters pointed to by s.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

strlen(3), feature_test_macros(7)


stpncpy(3)

STPNCPY

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

stpncpy - copy a fixed-size string, returning a pointer to its end

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

char *stpncpy(char *dest, const char *src, size_t n);

DESCRIPTION

The stpncpy() function copies at most n characters from the string pointed to by src, including the terminating '\0' character, to the array pointed to by dest. Exactly n characters are written at dest. If the length strlen(src) is smaller than n, the remaining characters in the array pointed to by dest are filled with '\0' characters. If the length strlen(src) is greater or equal to n, the string pointed to by dest will not be '\0' terminated.

The strings may not overlap.

The programmer must ensure that there is room for at least n characters at dest.

RETURN VALUE

stpncpy() returns a pointer to the terminating null in dest, or, if dest is not null-terminated, dest + n.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

strncpy(3), wcpncpy(3), feature_test_macros(7)


wcsnrtombs(3)

WCSNRTOMBS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsnrtombs - convert a wide-character string to a multibyte string

SYNOPSIS

#include <wchar.h>

size_t wcsnrtombs(char *dest, const wchar_t **src, size_t nwc,
                  size_t len, mbstate_t *ps);

DESCRIPTION

The wcsnrtombs() function is like the wcsrtombs() function, except that the number of wide characters to be converted, starting at *src, is limited to nwc.

If dest is not a NULL pointer, the wcsnrtombs() function converts at most nwc wide characters from the wide-character string *src to a multibyte string starting at dest. At most len bytes are written to dest. The shift state *ps is updated. The conversion is effectively performed by repeatedly calling wcrtomb(dest,*src,ps), as long as this call succeeds, and then incrementing dest by the number of bytes written and *src by one. The conversion can stop for three reasons:

1. A wide character has been encountered that can not be represented as a multibyte sequence (according to the current locale). In this case *src is left pointing to the invalid wide character, (size_t)(-1) is returned, and errno is set to EILSEQ.

2. nwc wide characters have been converted without encountering a L'\0', or the length limit forces a stop. In this case *src is left pointing to the next wide character to be converted, and the number of bytes written to dest is returned.

3. The wide-character string has been completely converted, including the terminating L'\0' (which has the side effect of bringing back *ps to the initial state). In this case *src is set to NULL, and the number of bytes written to dest, excluding the terminating '\0' byte, is returned.

If dest is NULL, len is ignored, and the conversion proceeds as above, except that the converted bytes are not written out to memory, and that no destination length limit exists.

In both of the above cases, if ps is a NULL pointer, a static anonymous state only known to the wcsnrtombs function is used instead.

The programmer must ensure that there is room for at least len bytes at dest.

RETURN VALUE

The wcsnrtombs() function returns the number of bytes that make up the converted part of multibyte sequence, not including the terminating null byte. If a wide character was encountered which could not be converted, (size_t)(-1) is returned, and errno set to EILSEQ.

CONFORMING TO

This function is a GNU extension.

NOTES

The behavior of wcsnrtombs() depends on the LC_CTYPE category of the current locale.

Passing NULL as ps is not multi-thread safe.

SEE ALSO

iconv(3), wcsrtombs(3)


MB_CUR_MAX(3)

MB_CUR_MAX

Section: Linux Programmer's Manual (3)
Updated: 1999-07-04 Return to Main Contents

NAME

MB_CUR_MAX - maximum length of a multibyte character in the current locale

SYNOPSIS

#include <stdlib.h>

DESCRIPTION

The MB_CUR_MAX macro defines an integer expression giving the maximum number of bytes needed to represent a single wide character in the current locale. It is locale dependent and therefore not a compile-time constant.

RETURN VALUE

An integer >= 1 and <= MB_LEN_MAX. The value 1 denotes traditional 8-bit encoded characters.

CONFORMING TO

C99, POSIX.1-2001.

SEE ALSO

MB_LEN_MAX(3), mblen(3), mbstowcs(3), mbtowc(3), wcstombs(3), wctomb(3)


MB_LEN_MAX(3)

MB_LEN_MAX

Section: Linux Programmer's Manual (3)
Updated: 1999-07-04 Return to Main Contents

NAME

MB_LEN_MAX - maximum multibyte length of a character across all locales

SYNOPSIS

#include <limits.h>

DESCRIPTION

The MB_LEN_MAX macro is the upper bound for the number of bytes needed to represent a single wide character, across all locales.

RETURN VALUE

A constant integer >= 1.

CONFORMING TO

C99, POSIX.1-2001.

NOTES

The entities MB_LEN_MAX and sizeof(wchar_t) are totally unrelated. In the GNU libc, MB_LEN_MAX is typically 6 while sizeof(wchar_t) is 4.

SEE ALSO

MB_CUR_MAX(3)


btowc(3)

BTOWC

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

btowc - convert single byte to wide character

SYNOPSIS

#include <wchar.h>

wint_t btowc(int c);

DESCRIPTION

The btowc() function converts c, interpreted as a multibyte sequence of length 1, starting in the initial shift state, to a wide character and returns it. If c is EOF or not a valid multibyte sequence of length 1, the btowc() function returns WEOF.

RETURN VALUE

The btowc() function returns the wide character converted from the single byte c. If c is EOF or not a valid multibyte sequence of length 1, it returns WEOF.

CONFORMING TO

C99, POSIX.1-2001.

NOTES

The behavior of btowc() depends on the LC_CTYPE category of the current locale.

This function should never be used. It does not work for encodings which have state, and unnecessarily treats single bytes differently from multibyte sequences. Use the function mbtowc() instead.

SEE ALSO

mbtowc(3)


fgetwc(3)

FGETWC

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

fgetwc, getwc - read a wide character from a FILE stream

SYNOPSIS

#include <stdio.h>

#include <wchar.h>

wint_t fgetwc(FILE *stream);
wint_t getwc(FILE *stream);

DESCRIPTION

The fgetwc() function is the wide-character equivalent of the fgetc(3) function. It reads a wide character from stream and returns it. If the end of stream is reached, or if ferror(stream) becomes true, it returns WEOF. If a wide-character conversion error occurs, it sets errno to EILSEQ and returns WEOF.

The getwc() function or macro functions identically to fgetwc(). It may be implemented as a macro, and may evaluate its argument more than once. There is no reason ever to use it.

For non-locking counterparts, see unlocked_stdio(3).

RETURN VALUE

The fgetwc() function returns the next wide-character from the stream, or WEOF.

ERRORS

Apart from the usual ones, there is
EILSEQ
The data obtained from the input stream does not form a valid character.

CONFORMING TO

C99, POSIX.1-2001.

NOTES

The behavior of fgetwc() depends on the LC_CTYPE category of the current locale.

In the absence of additional information passed to the fopen(3) call, it is reasonable to expect that fgetwc() will actually read a multibyte sequence from the stream and then convert it to a wide character.

SEE ALSO

fgetws(3), fputwc(3), ungetwc(3), unlocked_stdio(3)


getwc (3)

 Continue to this page.


fgetws(3)

FGETWS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

fgetws - read a wide-character string from a FILE stream

SYNOPSIS

#include <wchar.h>

wchar_t *fgetws(wchar_t *ws, int n, FILE *stream);

DESCRIPTION

The fgetws() function is the wide-character equivalent of the fgets(3) function. It reads a string of at most n-1 wide characters into the wide-character array pointed to by ws, and adds a terminating L'\0' character. It stops reading wide characters after it has encountered and stored a newline wide character. It also stops when end of stream is reached.

The programmer must ensure that there is room for at least n wide characters at ws.

For a non-locking counterpart, see unlocked_stdio(3).

RETURN VALUE

The fgetws() function, if successful, returns ws. If end of stream was already reached or if an error occurred, it returns NULL.

CONFORMING TO

C99, POSIX.1-2001.

NOTES

The behavior of fgetws() depends on the LC_CTYPE category of the current locale.

In the absence of additional information passed to the fopen(3) call, it is reasonable to expect that fgetws() will actually read a multibyte string from the stream and then convert it to a wide-character string.

This function is unreliable, because it does not permit to deal properly with null wide characters that may be present in the input.

SEE ALSO

fgetwc(3), unlocked_stdio(3)


fputwc(3)

FPUTWC

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

fputwc, putwc - write a wide character to a FILE stream

SYNOPSIS

#include <stdio.h>

#include <wchar.h>

wint_t fputwc(wchar_t wc, FILE *stream);
wint_t putwc(wchar_t wc, FILE *stream);

DESCRIPTION

The fputwc() function is the wide-character equivalent of the fputc(3) function. It writes the wide character wc to stream. If ferror(stream) becomes true, it returns WEOF. If a wide-character conversion error occurs, it sets errno to EILSEQ and returns WEOF. Otherwise it returns wc.

The putwc() function or macro functions identically to fputwc(). It may be implemented as a macro, and may evaluate its argument more than once. There is no reason ever to use it.

For non-locking counterparts, see unlocked_stdio(3).

RETURN VALUE

The fputwc() function returns wc if no error occurred, or WEOF to indicate an error.

ERRORS

Apart from the usual ones, there is
EILSEQ
Conversion of wc to the stream's encoding fails.

CONFORMING TO

C99, POSIX.1-2001.

NOTES

The behavior of fputwc() depends on the LC_CTYPE category of the current locale.

In the absence of additional information passed to the fopen(3) call, it is reasonable to expect that fputwc() will actually write the multibyte sequence corresponding to the wide character wc.

SEE ALSO

fgetwc(3), fputws(3), unlocked_stdio(3)


putwc (3)

 Continue to this page.


fputws(3)

FPUTWS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

fputws - write a wide-character string to a FILE stream

SYNOPSIS

#include <wchar.h>

int fputws(const wchar_t *ws, FILE *stream);

DESCRIPTION

The fputws() function is the wide-character equivalent of the fputs(3) function. It writes the wide-character string starting at ws, up to but not including the terminating L'\0' character, to stream.

For a non-locking counterpart, see unlocked_stdio(3).

RETURN VALUE

The fputws() function returns a non-negative integer if the operation was successful, or -1 to indicate an error.

CONFORMING TO

C99, POSIX.1-2001.

NOTES

The behavior of fputws() depends on the LC_CTYPE category of the current locale.

In the absence of additional information passed to the fopen(3) call, it is reasonable to expect that fputws() will actually write the multibyte string corresponding to the wide-character string ws.

SEE ALSO

fputwc(3), unlocked_stdio(3)


iswalnum(3)

ISWALNUM

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswalnum - test for alphanumeric wide character

SYNOPSIS

#include <wctype.h>

int iswalnum(wint_t wc);

DESCRIPTION

The iswalnum() function is the wide-character equivalent of the isalnum(3) function. It tests whether wc is a wide character belonging to the wide-character class "alnum".

The wide-character class "alnum" is a subclass of the wide-character class "graph", and therefore also a subclass of the wide-character class "print".

Being a subclass of the wide-character class "print", the wide-character class "alnum" is disjoint from the wide-character class "cntrl".

Being a subclass of the wide-character class "graph", the wide-character class "alnum" is disjoint from the wide-character class "space" and its subclass "blank".

The wide-character class "alnum" is disjoint from the wide-character class "punct".

The wide-character class "alnum" is the union of the wide-character classes "alpha" and "digit". As such, it also contains the wide-character class "xdigit".

The wide-character class "alnum" always contains at least the letters 'A' to 'Z', 'a' to 'z' and the digits '0' to '9'.

RETURN VALUE

The iswalnum() function returns non-zero if wc is a wide character belonging to the wide-character class "alnum". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswalnum() depends on the LC_CTYPE category of the current locale.

SEE ALSO

isalnum(3), iswctype(3)


iswalpha(3)

ISWALPHA

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswalpha - test for alphabetic wide character

SYNOPSIS

#include <wctype.h>

int iswalpha(wint_t wc);

DESCRIPTION

The iswalpha() function is the wide-character equivalent of the isalpha(3) function. It tests whether wc is a wide character belonging to the wide-character class "alpha".

The wide-character class "alpha" is a subclass of the wide-character class "alnum", and therefore also a subclass of the wide-character class "graph" and of the wide-character class "print".

Being a subclass of the wide-character class "print", the wide-character class "alpha" is disjoint from the wide-character class "cntrl".

Being a subclass of the wide-character class "graph", the wide-character class "alpha" is disjoint from the wide-character class "space" and its subclass "blank".

Being a subclass of the wide-character class "alnum", the wide-character class "alpha" is disjoint from the wide-character class "punct".

The wide-character class "alpha" is disjoint from the wide-character class "digit".

The wide-character class "alpha" contains the wide-character classes "upper" and "lower".

The wide-character class "alpha" always contains at least the letters 'A' to 'Z' and 'a' to 'z'.

RETURN VALUE

The iswalpha() function returns non-zero if wc is a wide character belonging to the wide-character class "alpha". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswalpha() depends on the LC_CTYPE category of the current locale.

SEE ALSO

isalpha(3), iswctype(3)


iswblank(3)

ISWBLANK

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswblank - test for whitespace wide character

SYNOPSIS

#include <wctype.h>

int iswblank(wint_t wc);

DESCRIPTION

The iswblank() function is the wide-character equivalent of the isblank(3) function. It tests whether wc is a wide character belonging to the wide-character class "blank".

The wide-character class "blank" is a subclass of the wide-character class "space".

Being a subclass of the wide-character class "space", the wide-character class "blank" is disjoint from the wide-character class "graph" and therefore also disjoint from its subclasses "alnum", "alpha", "upper", "lower", "digit", "xdigit", "punct".

The wide-character class "blank" always contains at least the space character and the control character '\t'.

RETURN VALUE

The iswblank() function returns non-zero if wc is a wide character belonging to the wide-character class "blank". Otherwise it returns zero.

CONFORMING TO

POSIX.1-2001.

NOTES

The behavior of iswblank() depends on the LC_CTYPE category of the current locale.

SEE ALSO

isblank(3), iswctype(3)


iswcntrl(3)

ISWCNTRL

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswcntrl - test for control wide character

SYNOPSIS

#include <wctype.h>

int iswcntrl(wint_t wc);

DESCRIPTION

The iswcntrl() function is the wide-character equivalent of the iscntrl(3) function. It tests whether wc is a wide character belonging to the wide-character class "cntrl".

The wide-character class "cntrl" is disjoint from the wide-character class "print" and therefore also disjoint from its subclasses "graph", "alpha", "upper", "lower", "digit", "xdigit", "punct".

For an unsigned char c, iscntrl(c) implies iswcntrl(btowc(c)), but not vice versa.

RETURN VALUE

The iswcntrl() function returns non-zero if wc is a wide character belonging to the wide-character class "cntrl". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswcntrl() depends on the LC_CTYPE category of the current locale.

SEE ALSO

iscntrl(3), iswctype(3)


iswctype(3)

ISWCTYPE

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswctype - wide-character classification

SYNOPSIS

#include <wctype.h>

int iswctype(wint_t wc, wctype_t desc);

DESCRIPTION

If wc is a wide character having the character property designated by desc (or in other words: belongs to the character class designated by desc), the iswctype() function returns non-zero. Otherwise it returns zero. If wc is WEOF, zero is returned.

desc must be a character property descriptor returned by the wctype function.

RETURN VALUE

The iswctype() function returns non-zero if the wc has the designated property. Otherwise it returns 0.

CONFORMING TO

C99.

NOTES

The behavior of iswctype() depends on the LC_CTYPE category of the current locale.

SEE ALSO

iswalnum(3), iswalpha(3), iswblank(3), iswcntrl(3), iswdigit(3), iswgraph(3), iswlower(3), iswprint(3), iswpunct(3), iswspace(3), iswupper(3), iswxdigit(3), wctype(3)


iswdigit(3)

ISWDIGIT

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswdigit - test for decimal digit wide character

SYNOPSIS

#include <wctype.h>

int iswdigit(wint_t wc);

DESCRIPTION

The iswdigit() function is the wide-character equivalent of the isdigit(3) function. It tests whether wc is a wide character belonging to the wide-character class "digit".

The wide-character class "digit" is a subclass of the wide-character class "xdigit", and therefore also a subclass of the wide-character class "alnum", of the wide-character class "graph" and of the wide-character class "print".

Being a subclass of the wide character class "print", the wide-character class "digit" is disjoint from the wide-character class "cntrl".

Being a subclass of the wide-character class "graph", the wide-character class "digit" is disjoint from the wide-character class "space" and its subclass "blank".

Being a subclass of the wide-character class "alnum", the wide-character class "digit" is disjoint from the wide-character class "punct".

The wide-character class "digit" is disjoint from the wide-character class "alpha" and therefore also disjoint from its subclasses "lower", "upper".

The wide-character class "digit" always contains exactly the digits '0' to '9'.

RETURN VALUE

The iswdigit() function returns non-zero if wc is a wide character belonging to the wide-character class "digit". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswdigit() depends on the LC_CTYPE category of the current locale.

SEE ALSO

isdigit(3), iswctype(3)


iswgraph(3)

ISWGRAPH

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswgraph - test for graphic wide character

SYNOPSIS

#include <wctype.h>

int iswgraph(wint_t wc);

DESCRIPTION

The iswgraph() function is the wide-character equivalent of the isgraph(3) function. It tests whether wc is a wide character belonging to the wide-character class "graph".

The wide-character class "graph" is a subclass of the wide-character class "print".

Being a subclass of the wide-character class "print", the wide-character class "graph" is disjoint from the wide-character class "cntrl".

The wide-character class "graph" is disjoint from the wide-character class "space" and therefore also disjoint from its subclass "blank".

The wide-character class "graph" contains all the wide characters from the wide-character class "print" except the space character. It therefore contains the wide-character classes "alnum" and "punct".

RETURN VALUE

The iswgraph() function returns non-zero if wc is a wide character belonging to the wide-character class "graph". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswgraph() depends on the LC_CTYPE category of the current locale.

SEE ALSO

isgraph(3), iswctype(3)


iswlower(3)

ISWLOWER

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswlower - test for lowercase wide character

SYNOPSIS

#include <wctype.h>

int iswlower(wint_t wc);

DESCRIPTION

The iswlower() function is the wide-character equivalent of the islower(3) function. It tests whether wc is a wide character belonging to the wide-character class "lower".

The wide-character class "lower" is a subclass of the wide-character class "alpha", and therefore also a subclass of the wide-character class "alnum", of the wide-character class "graph" and of the wide-character class "print".

Being a subclass of the wide-character class "print", the wide-character class "lower" is disjoint from the wide-character class "cntrl".

Being a subclass of the wide-character class "graph", the wide-character class "lower" is disjoint from the wide-character class "space" and its subclass "blank".

Being a subclass of the wide-character class "alnum", the wide-character class "lower" is disjoint from the wide-character class "punct".

Being a subclass of the wide-character class "alpha", the wide-character class "lower" is disjoint from the wide-character class "digit".

The wide-character class "lower" contains at least those characters wc which are equal to towlower(wc) and different from towupper(wc).

The wide-character class "lower" always contains at least the letters 'a' to 'z'.

RETURN VALUE

The iswlower() function returns non-zero if wc is a wide character belonging to the wide-character class "lower". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswlower() depends on the LC_CTYPE category of the current locale.

This function is not very appropriate for dealing with Unicode characters, because Unicode knows about three cases: upper, lower and title case.

SEE ALSO

islower(3), iswctype(3), towlower(3)


mbrlen(3)

MBRLEN

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

mbrlen - determine number of bytes in next multibyte character

SYNOPSIS

#include <wchar.h>

size_t mbrlen(const char *s, size_t n, mbstate_t *ps);

DESCRIPTION

The mbrlen() function inspects at most n bytes of the multibyte string starting at s and extracts the next complete multibyte character. It updates the shift state *ps. If the multibyte character is not the null wide character, it returns the number of bytes that were consumed from s. If the multibyte character is the null wide character, it resets the shift state *ps to the initial state and returns 0.

If the n bytes starting at s do not contain a complete multibyte character, mbrlen() returns (size_t)(-2). This can happen even if n >= MB_CUR_MAX, if the multibyte string contains redundant shift sequences.

If the multibyte string starting at s contains an invalid multibyte sequence before the next complete character, mbrlen() returns (size_t)(-1) and sets errno to EILSEQ. In this case, the effects on *ps are undefined.

If ps is a NULL pointer, a static anonymous state only known to the mbrlen function is used instead.

RETURN VALUE

The mbrlen() function returns the number of bytes parsed from the multibyte sequence starting at s, if a non-null wide character was recognized. It returns 0, if a null wide character was recognized. It returns (size_t)(-1) and sets errno to EILSEQ, if an invalid multibyte sequence was encountered. It returns (size_t)(-2) if it couldn't parse a complete multibyte character, meaning that n should be increased.

CONFORMING TO

C99

NOTES

The behavior of mbrlen() depends on the LC_CTYPE category of the current locale.

SEE ALSO

mbrtowc(3)


iswprint(3)

ISWPRINT

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswprint - test for printing wide character

SYNOPSIS

#include <wctype.h>

int iswprint(wint_t wc);

DESCRIPTION

The iswprint() function is the wide-character equivalent of the isprint(3) function. It tests whether wc is a wide character belonging to the wide-character class "print".

The wide-character class "print" is disjoint from the wide-character class "cntrl".

The wide-character class "print" contains the wide-character class "graph".

RETURN VALUE

The iswprint() function returns non-zero if wc is a wide character belonging to the wide-character class "print". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswprint() depends on the LC_CTYPE category of the current locale.

SEE ALSO

isprint(3), iswctype(3)


iswpunct(3)

ISWPUNCT

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswpunct - test for punctuation or symbolic wide character

SYNOPSIS

#include <wctype.h>

int iswpunct(wint_t wc);

DESCRIPTION

The iswpunct() function is the wide-character equivalent of the ispunct(3) function. It tests whether wc is a wide character belonging to the wide-character class "punct".

The wide-character class "punct" is a subclass of the wide-character class "graph", and therefore also a subclass of the wide-character class "print".

The wide-character class "punct" is disjoint from the wide-character class "alnum" and therefore also disjoint from its subclasses "alpha", "upper", "lower", "digit", "xdigit".

Being a subclass of the wide-character class "print", the wide-character class "punct" is disjoint from the wide-character class "cntrl".

Being a subclass of the wide-character class "graph", the wide-character class "punct" is disjoint from the wide-character class "space" and its subclass "blank".

RETURN VALUE

The iswpunct() function returns non-zero if wc is a wide-character belonging to the wide-character class "punct". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswpunct() depends on the LC_CTYPE category of the current locale.

This function's name is a misnomer when dealing with Unicode characters, because the wide-character class "punct" contains both punctuation characters and symbol (math, currency, etc.) characters.

SEE ALSO

ispunct(3), iswctype(3)


iswspace(3)

ISWSPACE

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswspace - test for whitespace wide character

SYNOPSIS

#include <wctype.h>

int iswspace(wint_t wc);

DESCRIPTION

The iswspace() function is the wide-character equivalent of the isspace(3) function. It tests whether wc is a wide character belonging to the wide-character class "space".

The wide-character class "space" is disjoint from the wide-character class "graph" and therefore also disjoint from its subclasses "alnum", "alpha", "upper", "lower", "digit", "xdigit", "punct".

The wide-character class "space" contains the wide-character class "blank".

The wide-character class "space" always contains at least the space character and the control characters '\f', '\n', '\r', '\t', '\v'.

RETURN VALUE

The iswspace() function returns non-zero if wc is a wide character belonging to the wide-character class "space". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswspace() depends on the LC_CTYPE category of the current locale.

SEE ALSO

isspace(3), iswctype(3)


iswupper(3)

ISWUPPER

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswupper - test for uppercase wide character

SYNOPSIS

#include <wctype.h>

int iswupper(wint_t wc);

DESCRIPTION

The iswupper() function is the wide-character equivalent of the isupper(3) function. It tests whether wc is a wide character belonging to the wide-character class "upper".

The wide-character class "upper" is a subclass of the wide-character class "alpha", and therefore also a subclass of the wide-character class "alnum", of the wide-character class "graph" and of the wide-character class "print".

Being a subclass of the wide-character class "print", the wide-character class "upper" is disjoint from the wide-character class "cntrl".

Being a subclass of the wide-character class "graph", the wide-character class "upper" is disjoint from the wide-character class "space" and its subclass "blank".

Being a subclass of the wide-character class "alnum", the wide-character class "upper" is disjoint from the wide-character class "punct".

Being a subclass of the wide-character class "alpha", the wide-character class "upper" is disjoint from the wide-character class "digit".

The wide-character class "upper" contains at least those characters wc which are equal to towupper(wc) and different from towlower(wc).

The wide-character class "upper" always contains at least the letters 'A' to 'Z'.

RETURN VALUE

The iswupper() function returns non-zero if wc is a wide character belonging to the wide-character class "upper". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswupper() depends on the LC_CTYPE category of the current locale.

This function is not very appropriate for dealing with Unicode characters, because Unicode knows about three cases: upper, lower and title case.

SEE ALSO

isupper(3), iswctype(3), towupper(3)


iswxdigit(3)

ISWXDIGIT

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

iswxdigit - test for hexadecimal digit wide character

SYNOPSIS

#include <wctype.h>

int iswxdigit(wint_t wc);

DESCRIPTION

The iswxdigit() function is the wide-character equivalent of the isxdigit(3) function. It tests whether wc is a wide character belonging to the wide-character class "xdigit".

The wide-character class "xdigit" is a subclass of the wide-character class "alnum", and therefore also a subclass of the wide-character class "graph" and of the wide-character class "print".

Being a subclass of the wide-character class "print", the wide-character class "xdigit" is disjoint from the wide-character class "cntrl".

Being a subclass of the wide-character class "graph", the wide-character class "xdigit" is disjoint from the wide-character class "space" and its subclass "blank".

Being a subclass of the wide-character class "alnum", the wide-character class "xdigit" is disjoint from the wide-character class "punct".

The wide-character class "xdigit" always contains at least the letters 'A' to 'F', 'a' to 'f' and the digits '0' to '9'.

RETURN VALUE

The iswxdigit() function returns non-zero if wc is a wide character belonging to the wide-character class "xdigit". Otherwise it returns zero.

CONFORMING TO

C99.

NOTES

The behavior of iswxdigit() depends on the LC_CTYPE category of the current locale.

SEE ALSO

iswctype(3), isxdigit(3)


mbrtowc(3)

MBRTOWC

Section: Linux Programmer's Manual (3)
Updated: 2001-11-22 Return to Main Contents

NAME

mbrtowc - convert a multibyte sequence to a wide character

SYNOPSIS

#include <wchar.h>

size_t mbrtowc(wchar_t *pwc, const char *s, size_t n, mbstate_t *ps);

DESCRIPTION

The main case for this function is when s is not NULL and pwc is not NULL. In this case, the mbrtowc() function inspects at most n bytes of the multibyte string starting at s, extracts the next complete multibyte character, converts it to a wide character and stores it at *pwc. It updates the shift state *ps. If the converted wide character is not L'\0', it returns the number of bytes that were consumed from s. If the converted wide character is L'\0', it resets the shift state *ps to the initial state and returns 0.

If the n bytes starting at s do not contain a complete multibyte character, mbrtowc() returns (size_t)(-2). This can happen even if n >= MB_CUR_MAX, if the multibyte string contains redundant shift sequences.

If the multibyte string starting at s contains an invalid multibyte sequence before the next complete character, mbrtowc() returns (size_t)(-1) and sets errno to EILSEQ. In this case, the effects on *ps are undefined.

A different case is when s is not NULL but pwc is NULL. In this case the mbrtowc() function behaves as above, excepts that it does not store the converted wide character in memory.

A third case is when s is NULL. In this case, pwc and n are ignored. If the conversion state represented by *ps denotes an incomplete multibyte character conversion, the mbrtowc() function returns (size_t)(-1), sets errno to EILSEQ, and leaves *ps in an undefined state. Otherwise, the mbrtowc() function puts *ps in the initial state and returns 0.

In all of the above cases, if ps is a NULL pointer, a static anonymous state only known to the mbrtowc function is used instead. Otherwise, *ps must be a valid mbstate_t object. An mbstate_t object a can be initialized to the initial state by zeroing it, for example using

memset(&a, 0, sizeof(a));

RETURN VALUE

The mbrtowc() function returns the number of bytes parsed from the multibyte sequence starting at s, if a non-L'\0' wide character was recognized. It returns 0, if a L'\0' wide character was recognized. It returns (size_t)(-1) and sets errno to EILSEQ, if an invalid multibyte sequence was encountered. It returns (size_t)(-2) if it couldn't parse a complete multibyte character, meaning that n should be increased.

CONFORMING TO

C99

NOTES

The behavior of mbrtowc() depends on the LC_CTYPE category of the current locale.

SEE ALSO

mbsrtowcs(3)


mbsinit(3)

MBSINIT

Section: Linux Programmer's Manual (3)
Updated: 2000-11-20 Return to Main Contents

NAME

mbsinit - test for initial shift state

SYNOPSIS

#include <wchar.h>

int mbsinit(const mbstate_t *ps);

DESCRIPTION

Character conversion between the multibyte representation and the wide character representation uses conversion state, of type mbstate_t. Conversion of a string uses a finite-state machine; when it is interrupted after the complete conversion of a number of characters, it may need to save a state for processing the remaining characters. Such a conversion state is needed for the sake of encodings such as ISO-2022 and UTF-7.

The initial state is the state at the beginning of conversion of a string. There are two kinds of state: The one used by multibyte to wide character conversion functions, such as mbsrtowcs(3), and the one used by wide character to multibyte conversion functions, such as wcsrtombs(3), but they both fit in a mbstate_t, and they both have the same representation for an initial state.

For 8-bit encodings, all states are equivalent to the initial state. For multibyte encodings like UTF-8, EUC-*, BIG5 or SJIS, the wide character to multibyte conversion functions never produce non-initial states, but the multibyte to wide-character conversion functions like mbrtowc(3) do produce non-initial states when interrupted in the middle of a character.

One possible way to create an mbstate_t in initial state is to set it to zero:

  mbstate_t state;
  memset(&state,0,sizeof(mbstate_t));
On Linux, the following works as well, but might generate compiler warnings:
  mbstate_t state = { 0 };

The function mbsinit() tests whether *ps corresponds to an initial state.

RETURN VALUE

mbsinit() returns non-zero if *ps is an initial state, or if ps is a null pointer. Otherwise it returns 0.

CONFORMING TO

C99

NOTES

The behavior of mbsinit() depends on the LC_CTYPE category of the current locale.

SEE ALSO

mbsrtowcs(3), wcsrtombs(3)


mbsnrtowcs(3)

MBSNRTOWCS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

mbsnrtowcs - convert a multibyte string to a wide-character string

SYNOPSIS

#include <wchar.h>

size_t mbsnrtowcs(wchar_t *dest, const char **src,
                  size_t nms, size_t len, mbstate_t *ps);

DESCRIPTION

The mbsnrtowcs() function is like the mbsrtowcs(3) function, except that the number of bytes to be converted, starting at *src, is limited to nms.

If dest is not a NULL pointer, the mbsnrtowcs() function converts at most nms bytes from the multibyte string *src to a wide-character string starting at dest. At most len wide characters are written to dest. The shift state *ps is updated. The conversion is effectively performed by repeatedly calling mbrtowc(dest,*src,n,ps) where n is some positive number, as long as this call succeeds, and then incrementing dest by one and *src by the number of bytes consumed. The conversion can stop for three reasons:

1. An invalid multibyte sequence has been encountered. In this case *src is left pointing to the invalid multibyte sequence, (size_t)(-1) is returned, and errno is set to EILSEQ.

2. The nms limit forces a stop, or len non-L'\0' wide characters have been stored at dest. In this case *src is left pointing to the next multibyte sequence to be converted, and the number of wide characters written to dest is returned.

3. The multibyte string has been completely converted, including the terminating '\0' (which has the side effect of bringing back *ps to the initial state). In this case *src is set to NULL, and the number of wide characters written to dest, excluding the terminating L'\0' character, is returned.

If dest is NULL, len is ignored, and the conversion proceeds as above, except that the converted wide characters are not written out to memory, and that no destination length limit exists.

In both of the above cases, if ps is a NULL pointer, a static anonymous state only known to the mbsnrtowcs function is used instead.

The programmer must ensure that there is room for at least len wide characters at dest.

RETURN VALUE

The mbsnrtowcs() function returns the number of wide characters that make up the converted part of the wide-character string, not including the terminating null wide character. If an invalid multibyte sequence was encountered, (size_t)(-1) is returned, and errno set to EILSEQ.

CONFORMING TO

This function is a GNU extension.

NOTES

The behavior of mbsnrtowcs() depends on the LC_CTYPE category of the current locale.

Passing NULL as ps is not multi-thread safe.

SEE ALSO

iconv(3), mbsrtowcs(3)


mbsrtowcs(3)

MBSRTOWCS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

mbsrtowcs - convert a multibyte string to a wide-character string

SYNOPSIS

#include <wchar.h>

size_t mbsrtowcs(wchar_t *dest, const char **src,
                  size_t len, mbstate_t *ps);

DESCRIPTION

If dest is not a NULL pointer, the mbsrtowcs() function converts the multibyte string *src to a wide-character string starting at dest. At most len wide characters are written to dest. The shift state *ps is updated. The conversion is effectively performed by repeatedly calling mbrtowc(dest,*src,n,ps) where n is some positive number, as long as this call succeeds, and then incrementing dest by one and *src by the number of bytes consumed. The conversion can stop for three reasons:

1. An invalid multibyte sequence has been encountered. In this case *src is left pointing to the invalid multibyte sequence, (size_t)(-1) is returned, and errno is set to EILSEQ.

2. len non-L'\0' wide characters have been stored at dest. In this case *src is left pointing to the next multibyte sequence to be converted, and the number of wide characters written to dest is returned.

3. The multibyte string has been completely converted, including the terminating '\0' (which has the side effect of bringing back *ps to the initial state). In this case *src is set to NULL, and the number of wide characters written to dest, excluding the terminating L'\0' character, is returned.

If dest is NULL, len is ignored, and the conversion proceeds as above, except that the converted wide characters are not written out to memory, and that no length limit exists.

In both of the above cases, if ps is a NULL pointer, a static anonymous state only known to the mbsrtowcs function is used instead.

The programmer must ensure that there is room for at least len wide characters at dest.

RETURN VALUE

The mbsrtowcs() function returns the number of wide characters that make up the converted part of the wide-character string, not including the terminating null wide character. If an invalid multibyte sequence was encountered, (size_t)(-1) is returned, and errno set to EILSEQ.

CONFORMING TO

C99

NOTES

The behavior of mbsrtowcs() depends on the LC_CTYPE category of the current locale.

Passing NULL as ps is not multi-thread safe.

SEE ALSO

iconv(3), mbsnrtowcs(3), mbstowcs(3)


getwchar(3)

GETWCHAR

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

getwchar - read a wide character from standard input

SYNOPSIS

#include <wchar.h>

wint_t getwchar(void);

DESCRIPTION

The getwchar() function is the wide-character equivalent of the getchar(3) function. It reads a wide character from stdin and returns it. If the end of stream is reached, or if ferror(stdin) becomes true, it returns WEOF. If a wide-character conversion error occurs, it sets errno to EILSEQ and returns WEOF.

For a non-locking counterpart, see unlocked_stdio(3).

RETURN VALUE

The getwchar() function returns the next wide-character from standard input, or WEOF.

CONFORMING TO

C99

NOTES

The behavior of getwchar() depends on the LC_CTYPE category of the current locale.

It is reasonable to expect that getwchar() will actually read a multibyte sequence from standard input and then convert it to a wide character.

SEE ALSO

fgetwc(3), unlocked_stdio(3)


putwchar(3)

PUTWCHAR

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

putwchar - write a wide character to standard output

SYNOPSIS

#include <wchar.h>

wint_t putwchar(wchar_t wc);

DESCRIPTION

The putwchar() function is the wide-character equivalent of the putchar(3) function. It writes the wide character wc to stdout. If ferror(stdout) becomes true, it returns WEOF. If a wide character conversion error occurs, it sets errno to EILSEQ and returns WEOF. Otherwise it returns wc.

For a non-locking counterpart, see unlocked_stdio(3).

RETURN VALUE

The putwchar() function returns wc if no error occurred, or WEOF to indicate an error.

CONFORMING TO

C99.

NOTES

The behavior of putwchar() depends on the LC_CTYPE category of the current locale.

It is reasonable to expect that putwchar() will actually write the multibyte sequence corresponding to the wide character wc.

SEE ALSO

fputwc(3), unlocked_stdio(3)


towctrans(3)

TOWCTRANS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

towctrans - wide-character transliteration

SYNOPSIS

#include <wctype.h>

wint_t towctrans(wint_t wc, wctrans_t desc);

DESCRIPTION

If wc is a wide character, the towctrans() function translates it according to the transliteration descriptor desc. If wc is WEOF, WEOF is returned.

desc must be a transliteration descriptor returned by the wctrans(3) function.

RETURN VALUE

The towctrans() function returns the translated wide character, or WEOF if wc is WEOF.

CONFORMING TO

C99.

NOTES

The behavior of towctrans() depends on the LC_CTYPE category of the current locale.

SEE ALSO

towlower(3), towupper(3), wctrans(3)


towlower(3)

TOWLOWER

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

towlower - convert a wide character to lowercase

SYNOPSIS

#include <wctype.h>

wint_t towlower(wint_t wc);

DESCRIPTION

The towlower() function is the wide-character equivalent of the tolower(3) function. If wc is a wide character, it is converted to lowercase. Characters which do not have case are returned unchanged. If wc is WEOF, WEOF is returned.

RETURN VALUE

The towlower() function returns the lowercase equivalent of wc, or WEOF if wc is WEOF.

CONFORMING TO

C99.

NOTES

The behavior of towlower() depends on the LC_CTYPE category of the current locale.

This function is not very appropriate for dealing with Unicode characters, because Unicode knows about three cases: upper, lower and title case.

SEE ALSO

iswlower(3), towctrans(3), towupper(3)


towupper(3)

TOWUPPER

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

towupper - convert a wide character to uppercase

SYNOPSIS

#include <wctype.h>

wint_t towupper(wint_t wc);

DESCRIPTION

The towupper() function is the wide-character equivalent of the toupper(3) function. If wc is a wide character, it is converted to uppercase. Characters which do not have case are returned unchanged. If wc is WEOF, WEOF is returned.

RETURN VALUE

The towupper() function returns the uppercase equivalent of wc, or WEOF if wc is WEOF.

CONFORMING TO

C99.

NOTES

The behavior of towupper() depends on the LC_CTYPE category of the current locale.

This function is not very appropriate for dealing with Unicode characters, because Unicode knows about three cases: upper, lower and title case.

SEE ALSO

iswupper(3), towctrans(3), towlower(3)


wcpcpy(3)

WCPCPY

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcpcpy - copy a wide-character string, returning a pointer to its end

SYNOPSIS

#define _GNU_SOURCE

#include <wchar.h>

wchar_t *wcpcpy(wchar_t *dest, const wchar_t *src);

DESCRIPTION

The wcpcpy() function is the wide-character equivalent of the stpcpy(3) function. It copies the wide-character string pointed to by src, including the terminating L'\0' character, to the array pointed to by dest.

The strings may not overlap.

The programmer must ensure that there is room for at least wcslen(src)+1 wide characters at dest.

RETURN VALUE

wcpcpy() returns a pointer to the end of the wide-character string dest, that is, a pointer to the terminating L'\0' character.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

strcpy(3), wcscpy(3), feature_test_macros(7)


wcpncpy(3)

WCPNCPY

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

wcpncpy - copy a fixed-size string of wide characters, returning a pointer to its end

SYNOPSIS

#define _GNU_SOURCE

#include <wchar.h>

wchar_t *wcpncpy(wchar_t *dest, const wchar_t *src, size_t n);

DESCRIPTION

The wcpncpy() function is the wide-character equivalent of the stpncpy(3) function. It copies at most n wide characters from the wide-character string pointed to by src, including the terminating L'\0' character, to the array pointed to by dest. Exactly n wide characters are written at dest. If the length wcslen(src) is smaller than n, the remaining wide characters in the array pointed to by dest are filled with L'\0' characters. If the length wcslen(src) is greater or equal to n, the string pointed to by dest will not be L'\0' terminated.

The strings may not overlap.

The programmer must ensure that there is room for at least n wide characters at dest.

RETURN VALUE

wcpncpy() returns a pointer to the last wide character written, that is, dest + n - 1.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

stpncpy(3), wcsncpy(3), feature_test_macros(7)


wcrtomb(3)

WCRTOMB

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcrtomb - convert a wide character to a multibyte sequence

SYNOPSIS

#include <wchar.h>

size_t wcrtomb(char *s, wchar_t wc, mbstate_t *ps);

DESCRIPTION

The main case for this function is when s is not NULL and wc is not L'\0'. In this case, the wcrtomb() function converts the wide character wc to its multibyte representation and stores it at the beginning of the character array pointed to by s. It updates the shift state *ps, and returns the length of said multibyte representation, that is, the number of bytes written at s.

A different case is when s is not NULL but wc is L'\0'. In this case the wcrtomb() function stores at the character array pointed to by s the shift sequence needed to bring *ps back to the initial state, followed by a '\0' byte. It updates the shift state *ps (i.e., brings it into the initial state), and returns the length of the shift sequence plus one, that is, the number of bytes written at s.

A third case is when s is NULL. In this case wc is ignored, and the function effectively returns wcrtomb(buf,L'\0',ps) where buf is an internal anonymous buffer.

In all of the above cases, if ps is a NULL pointer, a static anonymous state only known to the wcrtomb() function is used instead.

RETURN VALUE

The wcrtomb() function returns the number of bytes that have been or would have been written to the byte array at s. If wc can not be represented as a multibyte sequence (according to the current locale), (size_t)(-1) is returned, and errno set to EILSEQ.

CONFORMING TO

C99.

NOTES

The behavior of wcrtomb() depends on the LC_CTYPE category of the current locale.

Passing NULL as ps is not multi-thread safe.

SEE ALSO

wcsrtombs(3)


wcscasecmp(3)

WCSCASECMP

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcscasecmp - compare two wide-character strings, ignoring case

SYNOPSIS

#include <wchar.h>

int wcscasecmp(const wchar_t *s1, const wchar_t *s2);

DESCRIPTION

The wcscasecmp() function is the wide-character equivalent of the strcasecmp(3) function. It compares the wide-character string pointed to by s1 and the wide-character string pointed to by s2, ignoring case differences (towupper(3), towlower(3)).

RETURN VALUE

The wcscasecmp() function returns zero if the wide-character strings at s1 and s2 are equal except for case distinctions. It returns a positive integer if s1 is greater than s2, ignoring case. It returns a negative integer if s1 is smaller than s2, ignoring case.

CONFORMING TO

This function is a GNU extension.

NOTES

The behavior of wcscasecmp() depends on the LC_CTYPE category of the current locale.

SEE ALSO

strcasecmp(3), wcscmp(3)


wcscat(3)

WCSCAT

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcscat - concatenate two wide-character strings

SYNOPSIS

#include <wchar.h>

wchar_t *wcscat(wchar_t *dest, const wchar_t *src);

DESCRIPTION

The wcscat() function is the wide-character equivalent of the strcat(3) function. It copies the wide-character string pointed to by src, including the terminating L'\0' character, to the end of the wide-character string pointed to by dest.

The strings may not overlap.

The programmer must ensure that there is room for at least wcslen(dest)+wcslen(src)+1 wide characters at dest.

RETURN VALUE

wcscat() returns dest.

CONFORMING TO

C99.

SEE ALSO

strcat(3), wcpcpy(3), wcscpy(3), wcsncat(3)


wcschr(3)

WCSCHR

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcschr - search a wide character in a wide-character string

SYNOPSIS

#include <wchar.h>

wchar_t *wcschr(const wchar_t *wcs, wchar_t wc);

DESCRIPTION

The wcschr() function is the wide-character equivalent of the strchr(3) function. It searches the first occurrence of wc in the wide-character string pointed to by wcs.

RETURN VALUE

The wcschr() function returns a pointer to the first occurrence of wc in the wide-character string pointed to by wcs, or NULL if wc does not occur in the string.

CONFORMING TO

C99.

SEE ALSO

strchr(3), wcspbrk(3), wcsrchr(3), wcsstr(3), wmemchr(3)


wcscmp(3)

WCSCMP

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcscmp - compare two wide-character strings

SYNOPSIS

#include <wchar.h>

int wcscmp(const wchar_t *s1, const wchar_t *s2);

DESCRIPTION

The wcscmp() function is the wide-character equivalent of the strcmp(3) function. It compares the wide-character string pointed to by s1 and the wide-character string pointed to by s2.

RETURN VALUE

The wcscmp() function returns zero if the wide-character strings at s1 and s2 are equal. It returns an integer greater than zero if at the first differing position i, the corresponding wide-character s1[i] is greater than s2[i]. It returns an integer less than zero if at the first differing position i, the corresponding wide-character s1[i] is less than s2[i].

CONFORMING TO

C99.

SEE ALSO

strcmp(3), wcscasecmp(3), wmemcmp(3)


wcscpy(3)

WCSCPY

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcscpy - copy a wide-character string

SYNOPSIS

#include <wchar.h>

wchar_t *wcscpy(wchar_t *dest, const wchar_t *src);

DESCRIPTION

The wcscpy() function is the wide-character equivalent of the strcpy(3) function. It copies the wide-character string pointed to by src, including the terminating L'\0' character, to the array pointed to by dest.

The strings may not overlap.

The programmer must ensure that there is room for at least wcslen(src)+1 wide characters at dest.

RETURN VALUE

wcscpy() returns dest.

CONFORMING TO

C99.

SEE ALSO

strcpy(3), wcpcpy(3), wcscat(3), wcsdup(3), wmemcpy(3)


wcscspn(3)

WCSCSPN

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcscspn - search a wide-character string for any of a set of wide characters

SYNOPSIS

#include <wchar.h>

size_t wcscspn(const wchar_t *wcs, const wchar_t *reject);

DESCRIPTION

The wcscspn() function is the wide-character equivalent of the strcspn(3) function. It determines the length of the longest initial segment of wcs which consists entirely of wide-characters not listed in reject. In other words, it searches for the first occurrence in the wide-character string wcs of any of the characters in the wide-character string reject.

RETURN VALUE

The wcscspn() function returns the number of wide characters in the longest initial segment of wcs which consists entirely of wide-characters not listed in reject. In other words, it returns the position of the first occurrence in the wide-character string wcs of any of the characters in the wide-character string reject, or wcslen(wcs) if there is none.

CONFORMING TO

C99.

SEE ALSO

strcspn(3), wcspbrk(3), wcsspn(3)


wcsdup(3)

WCSDUP

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

wcsdup - duplicate a wide-character string

SYNOPSIS

#define _GNU_SOURCE

#include <wchar.h>

wchar_t *wcsdup(const wchar_t *s);

DESCRIPTION

The wcsdup() function is the wide-character equivalent of the strdup(3) function. It allocates and returns a new wide-character string whose initial contents is a duplicate of the wide-character string pointed to by s.

Memory for the new wide-character string is obtained with malloc(3), and can be freed with free(3).

RETURN VALUE

The wcsdup() function returns a pointer to the new wide-character string, or NULL if sufficient memory was not available.

ERRORS

ENOMEM
Insufficient memory available to allocate duplicate string.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

strdup(3), wcscpy(3), feature_test_macros(7)


wcslen(3)

WCSLEN

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcslen - determine the length of a wide-character string

SYNOPSIS

#include <wchar.h>

size_t wcslen(const wchar_t *s);

DESCRIPTION

The wcslen() function is the wide-character equivalent of the strlen(3) function. It determines the length of the wide-character string pointed to by s, not including the terminating L'\0' character.

RETURN VALUE

The wcslen() function returns the number of wide characters in s.

CONFORMING TO

C99.

SEE ALSO

strlen(3)


wcsncasecmp(3)

WCSNCASECMP

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsncasecmp - compare two fixed-size wide-character strings, ignoring case

SYNOPSIS

#include <wchar.h>

int wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n);

DESCRIPTION

The wcsncasecmp() function is the wide-character equivalent of the strncasecmp(3) function. It compares the wide-character string pointed to by s1 and the wide-character string pointed to by s2, but at most n wide characters from each string, ignoring case differences (towupper(3), towlower(3)).

RETURN VALUE

The wcsncasecmp() function returns zero if the wide-character strings at s1 and s2, truncated to at most length n, are equal except for case distinctions. It returns a positive integer if truncated s1 is greater than truncated s2, ignoring case. It returns a negative integer if truncated s1 is smaller than truncated s2, ignoring case.

CONFORMING TO

This function is a GNU extension.

NOTES

The behavior of wcsncasecmp() depends on the LC_CTYPE category of the current locale.

SEE ALSO

strncasecmp(3), wcsncmp(3)


wcsncat(3)

WCSNCAT

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsncat - concatenate two wide-character strings

SYNOPSIS

#include <wchar.h>

wchar_t *wcsncat(wchar_t *dest, const wchar_t *src, size_t n);

DESCRIPTION

The wcsncat() function is the wide-character equivalent of the strncat(3) function. It copies at most n wide characters from the wide-character string pointed to by src to the end of the wide-character string pointed to by dest, and adds a terminating L'\0' character.

The strings may not overlap.

The programmer must ensure that there is room for at least wcslen(dest)+n+1 wide characters at dest.

RETURN VALUE

wcsncat() returns dest.

CONFORMING TO

C99.

SEE ALSO

strncat(3), wcscat(3)


wcsncmp(3)

WCSNCMP

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsncmp - compare two fixed-size wide-character strings

SYNOPSIS

#include <wchar.h>

int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n);

DESCRIPTION

The wcsncmp() function is the wide-character equivalent of the strncmp(3) function. It compares the wide-character string pointed to by s1 and the wide-character string pointed to by s2, but at most n wide characters from each string. In each string, the comparison extends only up to the first occurrence of a L'\0' character, if any.

RETURN VALUE

The wcsncmp() function returns zero if the wide-character strings at s1 and s2, truncated to at most length n, are equal. It returns an integer greater than zero if at the first differing position i (i < n), the corresponding wide-character s1[i] is greater than s2[i]. It returns an integer less than zero if at the first differing position i (i < n), the corresponding wide-character s1[i] is less than s2[i].

CONFORMING TO

C99.

SEE ALSO

strncmp(3), wcsncasecmp(3)


wcsncpy(3)

WCSNCPY

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsncpy - copy a fixed-size string of wide characters

SYNOPSIS

#include <wchar.h>

wchar_t *wcsncpy(wchar_t *dest, const wchar_t *src, size_t n);

DESCRIPTION

The wcsncpy() function is the wide-character equivalent of the strncpy(3) function. It copies at most n wide characters from the wide-character string pointed to by src, including the terminating L'\0' character, to the array pointed to by dest. Exactly n wide characters are written at dest. If the length wcslen(src) is smaller than n, the remaining wide characters in the array pointed to by dest are filled with L'\0' characters. If the length wcslen(src) is greater or equal to n, the string pointed to by dest will not be L'\0' terminated.

The strings may not overlap.

The programmer must ensure that there is room for at least n wide characters at dest.

RETURN VALUE

wcsncpy() returns dest.

CONFORMING TO

C99.

SEE ALSO

strncpy(3)


wcsnlen(3)

WCSNLEN

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsnlen - determine the length of a fixed-size wide-character string

SYNOPSIS

#include <wchar.h>

size_t wcsnlen(const wchar_t *s, size_t maxlen);

DESCRIPTION

The wcsnlen() function is the wide-character equivalent of the strnlen(3) function. It returns the number of wide-characters in the string pointed to by s, not including the terminating L'\0' character, but at most maxlen. In doing this, wcsnlen() looks only at the first maxlen wide-characters at s and never beyond s+maxlen.

RETURN VALUE

The wcsnlen() function returns wcslen(s), if that is less than maxlen, or maxlen if there is no L'\0' character among the first maxlen wide characters pointed to by s.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

strnlen(3), wcslen(3)


wcspbrk(3)

WCSPBRK

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcspbrk - search a wide-character string for any of a set of wide characters

SYNOPSIS

#include <wchar.h>

wchar_t *wcspbrk(const wchar_t *wcs, const wchar_t *accept);

DESCRIPTION

The wcspbrk() function is the wide-character equivalent of the strpbrk(3) function. It searches for the first occurrence in the wide-character string pointed to by wcs of any of the characters in the wide-character string pointed to by accept.

RETURN VALUE

The wcspbrk() function returns a pointer to the first occurrence in wcs of any of the characters listed in accept. If wcs contains none of these characters, NULL is returned.

CONFORMING TO

C99.

SEE ALSO

strpbrk(3), wcschr(3), wcscspn(3)


wcsrchr(3)

WCSRCHR

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsrchr - search a wide character in a wide-character string

SYNOPSIS

#include <wchar.h>

wchar_t *wcsrchr(const wchar_t *wcs, wchar_t wc);

DESCRIPTION

The wcsrchr() function is the wide-character equivalent of the strrchr(3) function. It searches the last occurrence of wc in the wide-character string pointed to by wcs.

RETURN VALUE

The wcsrchr() function returns a pointer to the last occurrence of wc in the wide-character string pointed to by wcs, or NULL if wc does not occur in the string.

CONFORMING TO

C99.

SEE ALSO

strrchr(3), wcschr(3)


wcsrtombs(3)

WCSRTOMBS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsrtombs - convert a wide-character string to a multibyte string

SYNOPSIS

#include <wchar.h>

size_t wcsrtombs(char *dest, const wchar_t **src,
                 size_t len, mbstate_t *ps);

DESCRIPTION

If dest is not a NULL pointer, the wcsrtombs() function converts the wide-character string *src to a multibyte string starting at dest. At most len bytes are written to dest. The shift state *ps is updated. The conversion is effectively performed by repeatedly calling wcrtomb(dest,*src,ps), as long as this call succeeds, and then incrementing dest by the number of bytes written and *src by one. The conversion can stop for three reasons:

1. A wide character has been encountered that can not be represented as a multibyte sequence (according to the current locale). In this case *src is left pointing to the invalid wide character, (size_t)(-1) is returned, and errno is set to EILSEQ.

2. The length limit forces a stop. In this case *src is left pointing to the next wide character to be converted, and the number of bytes written to dest is returned.

3. The wide-character string has been completely converted, including the terminating L'\0' (which has the side effect of bringing back *ps to the initial state). In this case *src is set to NULL, and the number of bytes written to dest, excluding the terminating '\0' byte, is returned.

If dest is NULL, len is ignored, and the conversion proceeds as above, except that the converted bytes are not written out to memory, and that no length limit exists.

In both of the above cases, if ps is a NULL pointer, a static anonymous state only known to the wcsrtombs function is used instead.

The programmer must ensure that there is room for at least len bytes at dest.

RETURN VALUE

The wcsrtombs() function returns the number of bytes that make up the converted part of multibyte sequence, not including the terminating null byte. If a wide character was encountered which could not be converted, (size_t)(-1) is returned, and errno set to EILSEQ.

CONFORMING TO

C99.

NOTES

The behavior of wcsrtombs() depends on the LC_CTYPE category of the current locale.

Passing NULL as ps is not multi-thread safe.

SEE ALSO

iconv(3), wcsnrtombs(3), wcstombs(3)


wcsspn(3)

WCSSPN

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsspn - advance in a wide-character string, skipping any of a set of wide characters

SYNOPSIS

#include <wchar.h>

wcsspn(const wchar_t *wcs, const wchar_t *accept);

DESCRIPTION

The wcsspn() function is the wide-character equivalent of the strspn(3) function. It determines the length of the longest initial segment of wcs which consists entirely of wide-characters listed in accept. In other words, it searches for the first occurrence in the wide-character string wcs of a wide-character not contained in the wide-character string accept.

RETURN VALUE

The wcsspn() function returns the number of wide characters in the longest initial segment of wcs which consists entirely of wide-characters listed in accept. In other words, it returns the position of the first occurrence in the wide-character string wcs of a wide-character not contained in the wide-character string accept, or wcslen(wcs) if there is none.

CONFORMING TO

C99.

SEE ALSO

strspn(3), wcscspn(3)


wcsstr(3)

WCSSTR

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcsstr - locate a substring in a wide-character string

SYNOPSIS

#include <wchar.h>

wchar_t *wcsstr(const wchar_t *haystack, const wchar_t *needle);

DESCRIPTION

The wcsstr() function is the wide-character equivalent of the strstr(3) function. It searches for the first occurrence of the wide-character string needle (without its terminating L'\0' character) as a substring in the wide-character string haystack.

RETURN VALUE

The wcsstr() function returns a pointer to the first occurrence of needle in haystack. It returns NULL if needle does not occur as a substring in haystack.

Note the special case: If needle is the empty wide-character string, the return value is always haystack itself.

CONFORMING TO

C99.

SEE ALSO

strstr(3), wcschr(3)


wcstok(3)

WCSTOK

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcstok - split wide-character string into tokens

SYNOPSIS

#include <wchar.h>

wchar_t *wcstok(wchar_t *wcs, const wchar_t *delim, wchar_t **ptr);

DESCRIPTION

The wcstok() function is the wide-character equivalent of the strtok(3) function, with an added argument to make it multithread-safe. It can be used to split a wide-character string wcs into tokens, where a token is defined as a substring not containing any wide-characters from delim.

The search starts at wcs, if wcs is not NULL, or at *ptr, if wcs is NULL. First, any delimiter wide-characters are skipped, that is, the pointer is advanced beyond any wide-characters which occur in delim. If the end of the wide-character string is now reached, wcstok() returns NULL, to indicate that no tokens were found, and stores an appropriate value in *ptr, so that subsequent calls to wcstok() will continue to return NULL. Otherwise, the wcstok() function recognizes the beginning of a token and returns a pointer to it, but before doing that, it zero-terminates the token by replacing the next wide-character which occurs in delim with a L'\0' character, and it updates *ptr so that subsequent calls will continue searching after the end of recognized token.

RETURN VALUE

The wcstok() function returns a pointer to the next token, or NULL if no further token was found.

CONFORMING TO

C99.

NOTES

The original wcs wide-character string is destructively modified during the operation.

EXAMPLE

The following code loops over the tokens contained in a wide-character string.

wchar_t *wcs = ...;
wchar_t *token;
wchar_t *state;
for (token = wcstok(wcs, " \t\n", &state);
    token != NULL;
    token = wcstok(NULL, " \t\n", &state)) {
    ...
}

SEE ALSO

strtok(3), wcschr(3)


wcswidth(3)

WCSWIDTH

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcswidth - determine columns needed for a fixed-size wide-character string

SYNOPSIS

#include <wchar.h>

int wcswidth(const wchar_t *s, size_t n);

DESCRIPTION

The wcswidth() function returns the number of columns needed to represent the wide-character string pointed to by s, but at most n wide characters. If a non-printable wide character occurs among these characters, -1 is returned.

RETURN VALUE

The wcswidth() function returns the number of column positions for the wide-character string s, truncated to at most length n.

CONFORMING TO

POSIX.1-2001.

NOTES

The behavior of wcswidth() depends on the LC_CTYPE category of the current locale.

SEE ALSO

iswprint(3), wcwidth(3)


wctob(3)

WCTOB

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wctob - try to represent a wide character as a single byte

SYNOPSIS

#include <wchar.h>

int wctob(wint_t c);

DESCRIPTION

The wctob() function tests whether the multi-byte representation of the wide character c, starting in the initial state, consists of a single byte. If so, it is returned as an unsigned char.

Never use this function. It cannot help you in writing internationalized programs. Internationalized programs must never distinguish single-byte and multi-byte characters.

RETURN VALUE

The wctob() function returns the single-byte representation of c, if it exists, of EOF otherwise.

CONFORMING TO

C99.

NOTES

The behavior of wctob() depends on the LC_CTYPE category of the current locale.

This function should never be used. Internationalized programs must never distinguish single-byte and multi-byte characters. Use the function wctomb(3) instead.

SEE ALSO

wctomb(3)


wctrans(3)

WCTRANS

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wctrans - wide-character translation mapping

SYNOPSIS

#include <wctype.h>

wctrans_t wctrans(const char *name);

DESCRIPTION

The wctrans_t type represents a mapping which can map a wide character to another wide character. Its nature is implementation dependent, but the special value (wctrans_t) 0 denotes an invalid mapping. Nonzero wctrans_t values can be passed to the towctrans() function to actually perform the wide-character mapping.

The wctrans() function returns a mapping, given by its name. The set of valid names depends on the LC_CTYPE category of the current locale, but the following names are valid in all locales.

  "tolower" - realizes the tolower(3) mapping
  "toupper" - realizes the toupper(3) mapping

RETURN VALUE

The wctrans() function returns a mapping descriptor if the name is valid. Otherwise it returns (wctrans_t) 0.

CONFORMING TO

C99.

NOTES

The behavior of wctrans() depends on the LC_CTYPE category of the current locale.

SEE ALSO

towctrans(3)


wctype(3)

WCTYPE

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wctype - wide-character classification

SYNOPSIS

#include <wctype.h>

wctype_t wctype(const char *name);

DESCRIPTION

The wctype_t type represents a property which a wide character may or may not have. In other words, it represents a class of wide characters. This type's nature is implementation dependent, but the special value (wctype_t) 0 denotes an invalid property. Nonzero wctype_t values can be passed to the iswctype(3) function to actually test whether a given wide character has the property.

The wctype() function returns a property, given by its name. The set of valid names depends on the LC_CTYPE category of the current locale, but the following names are valid in all locales.

  "alnum" - realizes the isalnum(3) classification function
  "alpha" - realizes the isalpha(3) classification function
  "blank" - realizes the isblank(3) classification function
  "cntrl" - realizes the iscntrl(3) classification function
  "digit" - realizes the isdigit(3) classification function
  "graph" - realizes the isgraph(3) classification function
  "lower" - realizes the islower(3) classification function
  "print" - realizes the isprint(3) classification function
  "punct" - realizes the ispunct(3) classification function
  "space" - realizes the isspace(3) classification function
  "upper" - realizes the isupper(3) classification function
  "xdigit" - realizes the isxdigit(3) classification function

RETURN VALUE

The wctype() function returns a property descriptor if the name is valid. Otherwise it returns (wctype_t) 0.

CONFORMING TO

C99.

NOTES

The behavior of wctype() depends on the LC_CTYPE category of the current locale.

SEE ALSO

iswctype(3)


wcwidth(3)

WCWIDTH

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wcwidth - determine columns needed for a wide character

SYNOPSIS

#define _XOPEN_SOURCE
#include <wchar.h>

int wcwidth(wchar_t c);

DESCRIPTION

The wcwidth() function returns the number of columns needed to represent the wide character c. If c is a printable wide character, the value is at least 0. If c is L'\0', the value is 0. Otherwise -1 is returned.

RETURN VALUE

The wcwidth() function returns the number of column positions for c.

CONFORMING TO

POSIX.1-2001.

Note that glibc before 2.2.5 used the prototype

int wcwidth(wint_t c);

NOTES

The behavior of wcwidth() depends on the LC_CTYPE category of the current locale.

SEE ALSO

iswprint(3), wcswidth(3), feature_test_macros(7)


wmemchr(3)

WMEMCHR

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wmemchr - search a wide character in a wide-character array

SYNOPSIS

#include <wchar.h>

wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n);

DESCRIPTION

The wmemchr() function is the wide-character equivalent of the memchr(3) function. It searches the n wide characters starting at s for the first occurrence of the wide character c.

RETURN VALUE

The wmemchr() function returns a pointer to the first occurrence of c among the n wide characters starting at s, or NULL if c does not occur among these.

CONFORMING TO

C99.

SEE ALSO

memchr(3), wcschr(3)


wmemcmp(3)

WMEMCMP

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wmemcmp - compare two arrays of wide-characters

SYNOPSIS

#include <wchar.h>

int wmemcmp(const wchar_t *s1, const wchar_t *s2, size_t n);

DESCRIPTION

The wmemcmp() function is the wide-character equivalent of the memcmp(3) function. It compares the n wide-characters starting at s1 and the n wide-characters starting at s2.

RETURN VALUE

The wmemcmp() function returns zero if the wide-character arrays of size n at s1 and s2 are equal. It returns an integer greater than zero if at the first differing position i (i < n), the corresponding wide-character s1[i] is greater than s2[i]. It returns an integer less than zero if at the first differing position i (i < n), the corresponding wide-character s1[i] is less than s2[i].

CONFORMING TO

C99.

SEE ALSO

memcmp(3), wcscmp(3)


wmemcpy(3)

WMEMCPY

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wmemcpy - copy an array of wide-characters

SYNOPSIS

#include <wchar.h>

wchar_t *wmemcpy(wchar_t *dest, const wchar_t *src, size_t n);

DESCRIPTION

The wmemcpy() function is the wide-character equivalent of the memcpy(3) function. It copies n wide characters from the array starting at src to the array starting at dest.

The arrays may not overlap; use wmemmove(3) to copy between overlapping arrays.

The programmer must ensure that there is room for at least n wide characters at dest.

RETURN VALUE

wmemcpy() returns dest.

CONFORMING TO

C99.

SEE ALSO

memcpy(3), wcscpy(3), wmemmove(3), wmempcpy(3)


wmemmove(3)

WMEMMOVE

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wmemmove - copy an array of wide-characters

SYNOPSIS

#include <wchar.h>

wchar_t *wmemmove(wchar_t *dest, const wchar_t *src, size_t n);

DESCRIPTION

The wmemmove() function is the wide-character equivalent of the memmove(3) function. It copies n wide characters from the array starting at src to the array starting at dest. The arrays may overlap.

The programmer must ensure that there is room for at least n wide characters at dest.

RETURN VALUE

wmemmove() returns dest.

CONFORMING TO

C99.

SEE ALSO

memmove(3), wmemcpy(3)


wmemset(3)

WMEMSET

Section: Linux Programmer's Manual (3)
Updated: 1999-07-25 Return to Main Contents

NAME

wmemset - fill an array of wide-characters with a constant wide character

SYNOPSIS

#include <wchar.h>

wchar_t *wmemset(wchar_t *wcs, wchar_t wc, size_t n);

DESCRIPTION

The wmemset() function is the wide-character equivalent of the memset(3) function. It fills the array of n wide-characters starting at wcs with n copies of the wide character wc.

RETURN VALUE

wmemset() returns wcs.

CONFORMING TO

C99.

SEE ALSO

memset(3)


snprintf (3)

 Continue to this page.


iconv(3)

ICONV

Section: Linux Programmer's Manual (3)
Updated: 2001-11-15 Return to Main Contents

NAME

iconv - perform character set conversion

SYNOPSIS

#include <iconv.h>

size_t iconv(iconv_t cd,
             char **inbuf, size_t *inbytesleft,
             char **outbuf, size_t *outbytesleft);

DESCRIPTION

The argument cd must be a conversion descriptor created using the function iconv_open(3).

The main case is when inbuf is not NULL and *inbuf is not NULL. In this case, the iconv() function converts the multibyte sequence starting at *inbuf to a multibyte sequence starting at *outbuf. At most *inbytesleft bytes, starting at *inbuf, will be read. At most *outbytesleft bytes, starting at *outbuf, will be written.

The iconv() function converts one multibyte character at a time, and for each character conversion it increments *inbuf and decrements *inbytesleft by the number of converted input bytes, it increments *outbuf and decrements *outbytesleft by the number of converted output bytes, and it updates the conversion state contained in cd. The conversion can stop for four reasons:

1. An invalid multibyte sequence is encountered in the input. In this case it sets errno to EILSEQ and returns (size_t)(-1). *inbuf is left pointing to the beginning of the invalid multibyte sequence.

2. The input byte sequence has been entirely converted, that is, *inbytesleft has gone down to 0. In this case iconv() returns the number of non-reversible conversions performed during this call.

3. An incomplete multibyte sequence is encountered in the input, and the input byte sequence terminates after it. In this case it sets errno to EINVAL and returns (size_t)(-1). *inbuf is left pointing to the beginning of the incomplete multibyte sequence.

4. The output buffer has no more room for the next converted character. In this case it sets errno to E2BIG and returns (size_t)(-1).

A different case is when inbuf is NULL or *inbuf is NULL, but outbuf is not NULL and *outbuf is not NULL. In this case, the iconv() function attempts to set cd's conversion state to the initial state and store a corresponding shift sequence at *outbuf. At most *outbytesleft bytes, starting at *outbuf, will be written. If the output buffer has no more room for this reset sequence, it sets errno to E2BIG and returns (size_t)(-1). Otherwise it increments *outbuf and decrements *outbytesleft by the number of bytes written.

A third case is when inbuf is NULL or *inbuf is NULL, and outbuf is NULL or *outbuf is NULL. In this case, the iconv() function sets cd's conversion state to the initial state.

RETURN VALUE

The iconv() function returns the number of characters converted in a non-reversible way during this call; reversible conversions are not counted. In case of error, it sets errno and returns (size_t)(-1).

ERRORS

The following errors can occur, among others:
E2BIG
There is not sufficient room at *outbuf.
EILSEQ
An invalid multibyte sequence has been encountered in the input.
EINVAL
An incomplete multibyte sequence has been encountered in the input.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

iconv_close(3), iconv_open(3)


iconv_open(3)

ICONV_OPEN

Section: Linux Programmer's Manual (3)
Updated: 2007-03-31 Return to Main Contents

NAME

iconv_open - allocate descriptor for character set conversion

SYNOPSIS

#include <iconv.h>

iconv_t iconv_open(const char *tocode, const char *fromcode);

DESCRIPTION

The iconv_open() function allocates a conversion descriptor suitable for converting byte sequences from character encoding fromcode to character encoding tocode.

The values permitted for fromcode and tocode and the supported combinations are system dependent. For the GNU C library, the permitted values are listed by the iconv --list command, and all combinations of the listed values are supported. Furthermore the GNU C library and the GNU libiconv library support the following two suffixes:

//TRANSLIT
When the string "//TRANSLIT" is appended to tocode, transliteration is activated. This means that when a character cannot be represented in the target character set, it can be approximated through one or several similarly looking characters.
//IGNORE
When the string "//IGNORE" is appended to tocode, characters that cannot be represented in the target character set will be silently discarded.

The resulting conversion descriptor can be used with iconv(3) any number of times. It remains valid until deallocated using iconv_close(3).

A conversion descriptor contains a conversion state. After creation using iconv_open(), the state is in the initial state. Using iconv(3) modifies the descriptor's conversion state. (This implies that a conversion descriptor can not be used in multiple threads simultaneously.) To bring the state back to the initial state, use iconv(3) with NULL as inbuf argument.

RETURN VALUE

The iconv_open() function returns a freshly allocated conversion descriptor. In case of error, it sets errno and returns (iconv_t)(-1).

ERRORS

The following error can occur, among others:
EINVAL
The conversion from fromcode to tocode is not supported by the implementation.

CONFORMING TO

UNIX98, POSIX.1-2001.

SEE ALSO

iconv(1), iconv(3), iconv_close(3)


ungetwc(3)

UNGETWC

Section: Linux Programmer's Manual (3)
Updated: 1999-09-19 Return to Main Contents

NAME

ungetwc - push back a wide character onto a FILE stream

SYNOPSIS

#include <wchar.h>

wint_t ungetwc(wint_t wc, FILE *stream);

DESCRIPTION

The ungetwc() function is the wide-character equivalent of the ungetc() function. It pushes back a wide character onto stream and returns it.

If wc is WEOF, it returns WEOF. If wc is an invalid wide character, it sets errno to EILSEQ and returns WEOF.

If wc is a valid wide character, it is pushed back onto the stream and thus becomes available for future wide-character read operations. The file-position indicator is decremented by one or more. The end-of-file indicator is cleared. The backing storage of the file is not affected.

Note: wc need not be the last wide-character read from the stream; it can be any other valid wide character.

If the implementation supports multiple push-back operations in a row, the pushed-back wide characters will be read in reverse order; however, only one level of push-back is guaranteed.

RETURN VALUE

The ungetwc() function returns wc when successful, or WEOF upon failure.

CONFORMING TO

C99.

NOTES

The behavior of ungetwc() depends on the LC_CTYPE category of the current locale.

SEE ALSO

fgetwc(3)


fts(3)

FTS

Section: C Library Functions (3) Return to Main Contents

BSD mandoc

NAME

fts fts_open fts_read fts_children fts_set fts_close - traverse a file hierarchy

SYNOPSIS

Fd #include <sys/types.h> Fd #include <sys/stat.h> Fd #include <fts.h> Ft FTS * Fn fts_open char * const *path_argv int options int (*compar)(const FTSENT **, const FTSENT **) Ft FTSENT * Fn fts_read FTS *ftsp Ft FTSENT * Fn fts_children FTS *ftsp int options Ft int Fn fts_set FTS *ftsp FTSENT *f int options Ft int Fn fts_close FTS *ftsp

DESCRIPTION

The fts functions are provided for traversing UNIX file hierarchies. A simple overview is that the Fn fts_open function returns a ``handle'' on a file hierarchy, which is then supplied to the other fts functions. The function Fn fts_read returns a pointer to a structure describing one of the files in the file hierarchy. The function Fn fts_children returns a pointer to a linked list of structures, each of which describes one of the files contained in a directory in the hierarchy. In general, directories are visited two distinguishable times; in pre-order (before any of their descendants are visited) and in post-order (after all of their descendants have been visited). Files are visited once. It is possible to walk the hierarchy ``logically'' (ignoring symbolic links) or physically (visiting symbolic links), order the walk of the hierarchy or prune and/or re-visit portions of the hierarchy.

Two structures are defined (and typedef'd) in the include file Aq Pa fts.h . The first is Fa FTS , the structure that represents the file hierarchy itself. The second is Fa FTSENT , the structure that represents a file in the file hierarchy. Normally, an Fa FTSENT structure is returned for every file in the file hierarchy. In this manual page, ``file'' and ``Fa FTSENT structure '' are generally interchangeable. The Fa FTSENT structure contains at least the following fields, which are described in greater detail below:

typedef struct _ftsent {
        u_short fts_info;               /* flags for FTSENT structure */
        char *fts_accpath;              /* access path */
        char *fts_path;                 /* root path */
        short fts_pathlen;              /* strlen(fts_path) */
        char *fts_name;                 /* filename */
        short fts_namelen;              /* strlen(fts_name) */
        short fts_level;                /* depth (-1 to N) */
        int fts_errno;                  /* file errno */
        long fts_number;                /* local numeric value */
        void *fts_pointer;              /* local address value */
        struct ftsent *fts_parent;      /* parent directory */
        struct ftsent *fts_link;        /* next file structure */
        struct ftsent *fts_cycle;       /* cycle structure */
        struct stat *fts_statp;         /* stat(2) information */
} FTSENT;

These fields are defined as follows:

Fa fts_info
One of the following flags describing the returned Fa FTSENT structure and the file it represents. With the exception of directories without errors (FTS_D ) all of these entries are terminal, that is, they will not be revisited, nor will any of their descendants be visited.

FTS_D
A directory being visited in pre-order.
FTS_DC
A directory that causes a cycle in the tree. (The Fa fts_cycle field of the Fa FTSENT structure will be filled in as well.)
FTS_DEFAULT
Any Fa FTSENT structure that represents a file type not explicitly described by one of the other Fa fts_info values.
FTS_DNR
A directory which cannot be read. This is an error return, and the Fa fts_errno field will be set to indicate what caused the error.
FTS_DOT
A file named `.' or `..' which was not specified as a filename to Fn fts_open (see FTS_SEEDOT )
FTS_DP
A directory being visited in post-order. The contents of the Fa FTSENT structure will be unchanged from when it was returned in pre-order, that is, with the Fa fts_info field set to FTS_D
FTS_ERR
This is an error return, and the Fa fts_errno field will be set to indicate what caused the error.
FTS_F
A regular file.
FTS_NS
A file for which no stat(2) information was available. The contents of the Fa fts_statp field are undefined. This is an error return, and the Fa fts_errno field will be set to indicate what caused the error.
FTS_NSOK
A file for which no stat(2) information was requested. The contents of the Fa fts_statp field are undefined.
FTS_SL
A symbolic link.
FTS_SLNONE
A symbolic link with a non-existent target. The contents of the Fa fts_statp field reference the file characteristic information for the symbolic link itself.

Fa fts_accpath
A path for accessing the file from the current directory.
Fa fts_path
The path for the file relative to the root of the traversal. This path contains the path specified to Fn fts_open as a prefix.
Fa fts_pathlen
The length of the string referenced by Fa fts_path .
Fa fts_name
The name of the file.
Fa fts_namelen
The length of the string referenced by Fa fts_name .
Fa fts_level
The depth of the traversal, numbered from -1 to N, where this file was found. The Fa FTSENT structure representing the parent of the starting point (or root) of the traversal is numbered -1, and the Fa FTSENT structure for the root itself is numbered 0.
Fa fts_errno
Upon return of a Fa FTSENT structure from the Fn fts_children or Fn fts_read functions, with its Fa fts_info field set to FTS_DNR FTS_ERR or FTS_NS the Fa fts_errno field contains the value of the external variable errno specifying the cause of the error. Otherwise, the contents of the Fa fts_errno field are undefined.
Fa fts_number
This field is provided for the use of the application program and is not modified by the fts functions. It is initialized to 0.
Fa fts_pointer
This field is provided for the use of the application program and is not modified by the fts functions. It is initialized to NULL
Fa fts_parent
A pointer to the Fa FTSENT structure referencing the file in the hierarchy immediately above the current file, that is, the directory of which this file is a member. A parent structure for the initial entry point is provided as well, however, only the Fa fts_level , Fa fts_number and Fa fts_pointer fields are guaranteed to be initialized.
Fa fts_link
Upon return from the Fn fts_children function, the Fa fts_link field points to the next structure in the NULL-terminated linked list of directory members. Otherwise, the contents of the Fa fts_link field are undefined.
Fa fts_cycle
If a directory causes a cycle in the hierarchy (see FTS_DC ) either because of a hard link between two directories, or a symbolic link pointing to a directory, the Fa fts_cycle field of the structure will point to the Fa FTSENT structure in the hierarchy that references the same file as the current Fa FTSENT structure. Otherwise, the contents of the Fa fts_cycle field are undefined.
Fa fts_statp
A pointer to stat(2) information for the file.

A single buffer is used for all of the paths of all of the files in the file hierarchy. Therefore, the Fa fts_path and Fa fts_accpath fields are guaranteed to be NULL -terminated only for the file most recently returned by Fn fts_read . To use these fields to reference any files represented by other Fa FTSENT structures will require that the path buffer be modified using the information contained in that Fa FTSENT structure's Fa fts_pathlen field. Any such modifications should be undone before further calls to Fn fts_read are attempted. The Fa fts_name field is always NULL -terminated.

FTS_OPEN

The Fn fts_open function takes a pointer to an array of character pointers naming one or more paths which make up a logical file hierarchy to be traversed. The array must be terminated by a NULL pointer.

There are a number of options, at least one of which (either FTS_LOGICAL or FTS_PHYSICAL must be specified. The options are selected by or 'ing the following values:

FTS_COMFOLLOW
This option causes any symbolic link specified as a root path to be followed immediately whether or not FTS_LOGICAL is also specified.
FTS_LOGICAL
This option causes the fts routines to return Fa FTSENT structures for the targets of symbolic links instead of the symbolic links themselves. If this option is set, the only symbolic links for which Fa FTSENT structures are returned to the application are those referencing non-existent files. Either FTS_LOGICAL or FTS_PHYSICAL must be provided to the Fn fts_open function.
FTS_NOCHDIR
As a performance optimization, the fts functions change directories as they walk the file hierarchy. This has the side-effect that an application cannot rely on being in any particular directory during the traversal. The FTS_NOCHDIR option turns off this optimization, and the fts functions will not change the current directory. Note that applications should not themselves change their current directory and try to access files unless FTS_NOCHDIR is specified and absolute pathnames were provided as arguments to Fn fts_open .
FTS_NOSTAT
By default, returned Fa FTSENT structures reference file characteristic information (the Fa statp field) for each file visited. This option relaxes that requirement as a performance optimization, allowing the fts functions to set the Fa fts_info field to FTS_NSOK and leave the contents of the Fa statp field undefined.
FTS_PHYSICAL
This option causes the fts routines to return Fa FTSENT structures for symbolic links themselves instead of the target files they point to. If this option is set, Fa FTSENT structures for all symbolic links in the hierarchy are returned to the application. Either FTS_LOGICAL or FTS_PHYSICAL must be provided to the Fn fts_open function.
FTS_SEEDOT
By default, unless they are specified as path arguments to Fn fts_open , any files named `.' or `..' encountered in the file hierarchy are ignored. This option causes the fts routines to return Fa FTSENT structures for them.
FTS_XDEV
This option prevents fts from descending into directories that have a different device number than the file from which the descent began.

The argument Fn compar specifies a user-defined function which may be used to order the traversal of the hierarchy. It takes two pointers to pointers to Fa FTSENT structures as arguments and should return a negative value, zero, or a positive value to indicate if the file referenced by its first argument comes before, in any order with respect to, or after, the file referenced by its second argument. The Fa fts_accpath , Fa fts_path and Fa fts_pathlen fields of the Fa FTSENT structures may never be used in this comparison. If the Fa fts_info field is set to FTS_NS or FTS_NSOK the Fa fts_statp field may not either. If the Fn compar argument is NULL the directory traversal order is in the order listed in Fa path_argv for the root paths, and in the order listed in the directory for everything else.

FTS_READ

The Fn fts_read function returns a pointer to an Fa FTSENT structure describing a file in the hierarchy. Directories (that are readable and do not cause cycles) are visited at least twice, once in pre-order and once in post-order. All other files are visited at least once. (Hard links between directories that do not cause cycles or symbolic links to symbolic links may cause files to be visited more than once, or directories more than twice.)

If all the members of the hierarchy have been returned, Fn fts_read returns NULL and sets the external variable errno to 0. If an error unrelated to a file in the hierarchy occurs, Fn fts_read returns NULL and sets errno appropriately. If an error related to a returned file occurs, a pointer to an Fa FTSENT structure is returned, and errno may or may not have been set (see Fa fts_info ) .

The Fa FTSENT structures returned by Fn fts_read may be overwritten after a call to Fn fts_close on the same file hierarchy stream, or, after a call to Fn fts_read on the same file hierarchy stream unless they represent a file of type directory, in which case they will not be overwritten until after a call to Fn fts_read after the Fa FTSENT structure has been returned by the function Fn fts_read in post-order.

FTS_CHILDREN

The Fn fts_children function returns a pointer to an Fa FTSENT structure describing the first entry in a NULL-terminated linked list of the files in the directory represented by the Fa FTSENT structure most recently returned by Fn fts_read . The list is linked through the Fa fts_link field of the Fa FTSENT structure, and is ordered by the user-specified comparison function, if any. Repeated calls to Fn fts_children will recreate this linked list.

As a special case, if Fn fts_read has not yet been called for a hierarchy, Fn fts_children will return a pointer to the files in the logical directory specified to Fn fts_open , that is, the arguments specified to Fn fts_open . Otherwise, if the Fa FTSENT structure most recently returned by Fn fts_read is not a directory being visited in pre-order, or the directory does not contain any files, Fn fts_children returns NULL and sets errno to zero. If an error occurs, Fn fts_children returns NULL and sets errno appropriately.

The Fa FTSENT structures returned by Fn fts_children may be overwritten after a call to Fn fts_children , Fn fts_close or Fn fts_read on the same file hierarchy stream.

Option may be set to the following value:

FTS_NAMEONLY
Only the names of the files are needed. The contents of all the fields in the returned linked list of structures are undefined with the exception of the Fa fts_name and Fa fts_namelen fields.

FTS_SET

The function Fn fts_set allows the user application to determine further processing for the file Fa f of the stream Fa ftsp . The Fn fts_set function returns 0 on success, and -1 if an error occurs. Option must be set to one of the following values:

FTS_AGAIN
Re-visit the file; any file type may be re-visited. The next call to Fn fts_read will return the referenced file. The Fa fts_stat and Fa fts_info fields of the structure will be reinitialized at that time, but no other fields will have been changed. This option is meaningful only for the most recently returned file from Fn fts_read . Normal use is for post-order directory visits, where it causes the directory to be re-visited (in both pre and post-order) as well as all of its descendants.
FTS_FOLLOW
The referenced file must be a symbolic link. If the referenced file is the one most recently returned by Fn fts_read , the next call to Fn fts_read returns the file with the Fa fts_info and Fa fts_statp fields reinitialized to reflect the target of the symbolic link instead of the symbolic link itself. If the file is one of those most recently returned by Fn fts_children , the Fa fts_info and Fa fts_statp fields of the structure, when returned by Fn fts_read , will reflect the target of the symbolic link instead of the symbolic link itself. In either case, if the target of the symbolic link does not exist the fields of the returned structure will be unchanged and the Fa fts_info field will be set to FTS_SLNONE

If the target of the link is a directory, the pre-order return, followed by the return of all of its descendants, followed by a post-order return, is done.

FTS_SKIP
No descendants of this file are visited. The file may be one of those most recently returned by either Fn fts_children or Fn fts_read .

FTS_CLOSE

The Fn fts_close function closes a file hierarchy stream Fa ftsp and restores the current directory to the directory from which Fn fts_open was called to open Fa ftsp . The Fn fts_close function returns 0 on success, and -1 if an error occurs.

ERRORS

The function Fn fts_open may fail and set errno for any of the errors specified for the library functions open(2) and malloc(3).

The function Fn fts_close may fail and set errno for any of the errors specified for the library functions chdir(2) and close(2).

The functions Fn fts_read and Fn fts_children may fail and set errno for any of the errors specified for the library functions chdir(2), malloc(3), opendir(3), readdir(3) and stat(2).

In addition, Fn fts_children , Fn fts_open and Fn fts_set may fail and set errno as follows:

Bq Er EINVAL
The options were invalid.

VERSIONS

These functions are available in Linux since glibc2.

CONFORMING TO

4.4BSD. The fts utility is expected to be included in a future St -p1003.1-88 revision.

SEE ALSO

find(1), chdir(2), stat(2), ftw(3), qsort(3)


fts_open (3)

 Continue to this page.


getaddrinfo(3)

GETADDRINFO

Section: Linux Programmer's Manual (3)
Updated: 2007-06-08 Return to Main Contents

NAME

getaddrinfo, freeaddrinfo, gai_strerror - network address and service translation

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int getaddrinfo(const char *node, const char *service,
                const struct addrinfo *hints,
                struct addrinfo **res);

void freeaddrinfo(struct addrinfo *res);

const char *gai_strerror(int errcode);

DESCRIPTION

The getaddrinfo(3) function combines the functionality provided by the getipnodebyname(3), getipnodebyaddr(3), getservbyname(3), and getservbyport(3) functions into a single interface. The thread-safe getaddrinfo(3) function creates one or more socket address structures that can be used by the bind(2) and connect(2) system calls to create a client or a server socket.

The getaddrinfo(3) function is not limited to creating IPv4 socket address structures; IPv6 socket address structures can be created if IPv6 support is available. These socket address structures can be used directly by bind(2) or connect(2), to prepare a client or a server socket.

The addrinfo structure used by this function contains the following members:

struct addrinfo {
    int     ai_flags;
    int     ai_family;
    int     ai_socktype;
    int     ai_protocol;
    size_t  ai_addrlen;
    struct sockaddr *ai_addr;
    char   *ai_canonname;
    struct addrinfo *ai_next;
};

getaddrinfo(3) sets res to point to a dynamically-allocated linked list of addrinfo structures, linked by the ai_next member. There are several reasons why the linked list may have more than one addrinfo structure, including: if the network host is multi-homed; or if the same service is available from multiple socket protocols (one SOCK_STREAM address and another SOCK_DGRAM address, for example).

The members ai_family, ai_socktype, and ai_protocol have the same meaning as the corresponding parameters in the socket(2) system call. The getaddrinfo(3) function returns socket addresses in either IPv4 or IPv6 address family, (ai_family will be set to either AF_INET or AF_INET6).

The hints parameter specifies the preferred socket type, or protocol. A NULL hints specifies that any network address or protocol is acceptable. If this parameter is not NULL it points to an addrinfo structure whose ai_family, ai_socktype, and ai_protocol members specify the preferred socket type. AF_UNSPEC in ai_family specifies any protocol family (either IPv4 or IPv6, for example). 0 in ai_socktype or ai_protocol specifies that any socket type or protocol is acceptable as well. The ai_flags member specifies additional options, defined below. Multiple flags are specified by logically OR-ing them together. All the other members in the hints parameter must contain either 0, or a null pointer.

The node or service parameter, but not both, may be NULL. node specifies either a numerical network address (dotted-decimal format for IPv4, hexadecimal format for IPv6) or a network hostname, whose network addresses are looked up and resolved. If hints.ai_flags contains the AI_NUMERICHOST flag then the node parameter must be a numerical network address. The AI_NUMERICHOST flag suppresses any potentially lengthy network host address lookups.

The getaddrinfo(3) function creates a linked list of addrinfo structures, one for each network address subject to any restrictions imposed by the hints parameter. The ai_canonname field of the first of these addrinfo structures is set to point to the official name of the host, if hints.ai_flags includes the AI_CANONNAME flag. ai_family, ai_socktype, and ai_protocol specify the socket creation parameters. A pointer to the socket address is placed in the ai_addr member, and the length of the socket address, in bytes, is placed in the ai_addrlen member.

If node is NULL, the network address in each socket structure is initialized according to the AI_PASSIVE flag, which is set in hints.ai_flags. The network address in each socket structure will be left unspecified if AI_PASSIVE flag is set. This is used by server applications, which intend to accept client connections on any network address. The network address will be set to the loopback interface address if the AI_PASSIVE flag is not set. This is used by client applications, which intend to connect to a server running on the same network host.

If hints.ai_flags includes the AI_ADDRCONFIG flag, then IPv4 addresses are returned in the list pointed to by result only if the local system has at least one IPv4 address configured, and IPv6 addresses are only returned if the local system has at least one IPv6 address configured.

If hint.ai_flags specifies the AI_V4MAPPED flag, and hints.ai_family was specified as AF_INET6, and no matching IPv6 addresses could be found, then return IPv4-mapped IPv6 addresses in the list pointed to by result. If both AI_V4MAPPED and AI_ALL are specified in hints.ai_family, then return both IPv6 and IPv4-mapped IPv6 addresses in the list pointed to by result. AI_ALL is ignored if AI_V4MAPPED is not also specified.

service sets the port number in the network address of each socket structure. If service is NULL the port number will be left uninitialized. If AI_NUMERICSERV is specified in hints.ai_flags and service is not NULL, then service must point to a string containing a numeric port number. This flag is used to inhibit the invocation of a name resolution service in cases where it is known not to be required.

The freeaddrinfo(3) function frees the memory that was allocated for the dynamically allocated linked list res.

Extensions to getaddrinfo() for Internationalized Domain Names

Starting with glibc 2.3.4, getaddrinfo() has been extended to selectively allow the incoming and outgoing host names to be transparently converted to and from the Internationalized Domain Name (IDN) format (see RFC 3490, Internationalizing Domain Names in Applications (IDNA)). Four new flags are defined:

AI_IDN
If this flag is specified, then the node name given in node is converted to IDN format if necessary. The source encoding is that of the current locale.

If the input name contains non-ASCII characters, then the IDN encoding is used. Those parts of the node name (delimited by dots) that contain non-ASCII characters are encoded using ASCII Compatible Encoding (ACE) before being passed to the name resolution functions.

AI_CANONIDN
After a successful name lookup, and if the AI_CANONNAME flag was specified, getaddrinfo() will return the canonical name of the node corresponding to the addrinfo structure value passed back. The return value is an exact copy of the value returned by the name resolution function.

If the name is encoded using ACE, then it will contain the xn-- prefix for one or more components of the name. To convert these components into a readable form the AI_CANONIDN flag can be passed in addition to AI_CANONNAME. The resulting string is encoded using the current locale's encoding.

AI_IDN_ALLOW_UNASSIGNED, AI_IDN_USE_STD3_ASCII_RULES
Setting these flags will enable the IDNA_ALLOW_UNASSIGNED (allow unassigned Unicode code points) and IDNA_USE_STD3_ASCII_RULES (check output to make sure it is a STD3 conforming host name) flags respectively to be used in the IDNA handling.

RETURN VALUE

getaddrinfo(3) returns 0 if it succeeds, or one of the following non-zero error codes:
EAI_ADDRFAMILY
The specified network host does not have any network addresses in the requested address family.
EAI_AGAIN
The name server returned a temporary failure indication. Try again later.
EAI_BADFLAGS
ai_flags contains invalid flags.
EAI_FAIL
The name server returned a permanent failure indication.
EAI_FAMILY
The requested address family is not supported at all.
EAI_MEMORY
Out of memory.
EAI_NODATA
The specified network host exists, but does not have any network addresses defined.
EAI_NONAME
The node or service is not known; or both node and service are NULL; or AI_NUMERICSERV was specified in hints.ai_flags and service was not a numeric port-number string.
EAI_SERVICE
The requested service is not available for the requested socket type. It may be available through another socket type.
EAI_SOCKTYPE
The requested socket type is not supported at all.
EAI_SYSTEM
Other system error, check errno for details.

The gai_strerror(3) function translates these error codes to a human readable string, suitable for error reporting.

CONFORMING TO

POSIX.1-2001. The getaddrinfo() function is documented in RFC 2553.

NOTES

AI_ADDRCONFIG, AI_ALL, and AI_V4MAPPED are available since glibc 2.3.3. AI_NUMERICSERV is available since glibc 2.3.4.

EXAMPLE

The following programs demonstrate the use of getaddrinfo(), gai_strerror(), freeaddrinfo(), and getnameinfo(3). The programs are an echo server and client for UDP datagrams.

This is the server:

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>

#define BUF_SIZE 500

int
main(int argc, char *argv[])
{
    struct addrinfo hints;
    struct addrinfo *result, *rp;
    int sfd, s;
    struct sockaddr_storage peer_addr;
    socklen_t peer_addr_len;
    ssize_t nread;
    char buf[BUF_SIZE];

    if (argc != 2) {
        fprintf(stderr, "Usage: %s port\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
    hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
    hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
    hints.ai_protocol = 0;          /* Any protocol */

    s = getaddrinfo(NULL, argv[1], &hints, &result);
    if (s != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
        exit(EXIT_FAILURE);
    }

    /* getaddrinfo() returns a list of address structures.
       Try each address until we successfully bind().
       If socket() (or bind()) fails, we (close the socket
       and) try the next address. */

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        sfd = socket(rp->ai_family, rp->ai_socktype,
                rp->ai_protocol);
        if (sfd == -1)
            continue;

        if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
            break;                  /* Success */

        close(sfd);
    }

    if (rp == NULL) {               /* No address succeeded */
        fprintf(stderr, "Could not bind\n");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(result);           /* No longer needed */

    /* Read datagrams and echo them back to sender */

    for (;;) {
        peer_addr_len = sizeof(struct sockaddr_storage);
        nread = recvfrom(sfd, buf, BUF_SIZE, 0,
                (struct sockaddr *) &peer_addr, &peer_addr_len);
        if (nread == -1)
            continue;               /* Ignore failed request */

        char host[NI_MAXHOST], service[NI_MAXSERV];

        s = getnameinfo((struct sockaddr *) &peer_addr,
                        peer_addr_len, host, NI_MAXHOST,
                        service, NI_MAXSERV, NI_NUMERICSERV);
       if (s == 0)
            printf("Received %ld bytes from %s:%s\n",
                    (long) nread, host, service);
        else
            fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));

        if (sendto(sfd, buf, nread, 0,
                    (struct sockaddr *) &peer_addr,
                    peer_addr_len) != nread)
            fprintf(stderr, "Error sending response\n");
    }
}

This is the client:

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUF_SIZE 500

int
main(int argc, char *argv[])
{
    struct addrinfo hints;
    struct addrinfo *result, *rp;
    int sfd, s, j;
    size_t len;
    ssize_t nread;
    char buf[BUF_SIZE];

    if (argc < 3) {
        fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /* Obtain address(es) matching host/port */

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
    hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
    hints.ai_flags = 0;
    hints.ai_protocol = 0;          /* Any protocol */

    s = getaddrinfo(argv[1], argv[2], &hints, &result);
    if (s != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
        exit(EXIT_FAILURE);
    }

    /* getaddrinfo() returns a list of address structures.
       Try each address until we successfully connect().
       If socket() (or connect()) fails, we (close the socket
       and) try the next address. */

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        sfd = socket(rp->ai_family, rp->ai_socktype,
                     rp->ai_protocol);
        if (sfd == -1)
            continue;

        if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
            break;                  /* Success */

        close(sfd);
    }

    if (rp == NULL) {               /* No address succeeded */
        fprintf(stderr, "Could not connect\n");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(result);           /* No longer needed */

    /* Send remaining command-line arguments as separate
       datagrams, and read responses from server */

    for (j = 3; j < argc; j++) {
        len = strlen(argv[j]) + 1;
                /* +1 for terminating null byte */

        if (len + 1 > BUF_SIZE) {
            fprintf(stderr,
                    "Ignoring long message in argument %d\n", j);
            continue;
        }

        if (write(sfd, argv[j], len) != len) {
            fprintf(stderr, "partial/failed write\n");
            exit(EXIT_FAILURE);
        }

        nread = read(sfd, buf, BUF_SIZE);
        if (nread == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }

        printf("Received %ld bytes: %s\n", (long) nread, buf);
    }

    exit(EXIT_SUCCESS);
}

SEE ALSO

getipnodebyaddr(3), getipnodebyname(3) getnameinfo(3),


fwide(3)

FWIDE

Section: Linux Programmer's Manual (3)
Updated: 1999-11-17 Return to Main Contents

NAME

fwide - set and determine the orientation of a FILE stream

SYNOPSIS

#include <wchar.h>

int fwide(FILE *stream, int mode);

DESCRIPTION

When mode is zero, the fwide() function determines the current orientation of stream. It returns a value > 0 if stream is wide-character oriented, that is, if wide-character I/O is permitted but char I/O is disallowed. It returns a value < 0 if stream is byte oriented, i.e. if char I/O is permitted but wide-character I/O is disallowed. It returns zero if stream has no orientation yet; in this case the next I/O operation might change the orientation (to byte oriented if it is a char I/O operation, or to wide-character oriented if it is a wide-character I/O operation).

Once a stream has an orientation, it cannot be changed and persists until the stream is closed.

When mode is non-zero, the fwide() function first attempts to set stream's orientation (to wide-character oriented if mode > 0, or to byte oriented if mode < 0). It then returns a value denoting the current orientation, as above.

RETURN VALUE

The fwide() function returns the stream's orientation, after possibly changing it. A return value > 0 means wide-character oriented. A return value < 0 means byte oriented. A return value of zero means undecided.

CONFORMING TO

C99, POSIX.1-2001.

NOTES

Wide-character output to a byte oriented stream can be performed through the fprintf(3) function with the %lc and %ls directives.

Char oriented output to a wide-character oriented stream can be performed through the fwprintf(3) function with the %c and %s directives.

SEE ALSO

fprintf(3), fwprintf(3)


fts_read (3)

 Continue to this page.


fwprintf (3)

 Continue to this page.


iconv_close(3)

ICONV_CLOSE

Section: Linux Programmer's Manual (3)
Updated: 1999-11-27 Return to Main Contents

NAME

iconv_close - deallocate descriptor for character set conversion

SYNOPSIS

#include <iconv.h>

int iconv_close(iconv_t cd);

DESCRIPTION

The iconv_close() function deallocates a conversion descriptor cd previously allocated using iconv_open().

RETURN VALUE

When successful, the iconv_close() function returns 0. In case of error, it sets errno and returns -1.

CONFORMING TO

UNIX98, POSIX.1-2001.

SEE ALSO

iconv(3), iconv_open(3)


fcloseall(3)

FCLOSEALL

Section: Linux Programmer's Manual (3)
Updated: 2006-12-27 Return to Main Contents

NAME

fcloseall - close all open streams

SYNOPSIS

#define _GNU_SOURCE
#include <stdio.h>

int fcloseall(void);

DESCRIPTION

The fcloseall() function closes all of the calling process's open streams. Buffered output for each stream is written before it is closed (as for fflush(3)); buffered input is discarded.

The standard streams, stdin, stdout, and stderr are also closed.

RETURN VALUE

This function returns 0 if all files were successfully closed; on error, EOF is returned.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

close(2), fclose(3), fflush(3), fopen(3), setbuf(3), feature_test_macros(7)


fts_children (3)

 Continue to this page.


inet_ntop(3)

INET_NTOP

Section: Linux Programmer's Manual (3)
Updated: 2000-12-18 Return to Main Contents

NAME

inet_ntop - Parse network address structures

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

const char *inet_ntop(int af, const void *src,
                      char *dst, socklen_t cnt);

DESCRIPTION

This function converts the network address structure src in the af address family into a character string, which is copied to a character buffer dst, which is cnt bytes long.

inet_ntop(3) extends the inet_ntoa(3) function to support multiple address families, inet_ntoa(3) is now considered to be deprecated in favor of inet_ntop(3). The following address families are currently supported:

AF_INET
src points to a struct in_addr (network byte order format) which is converted to an IPv4 network address in the dotted-quad format, "ddd.ddd.ddd.ddd". The buffer dst must be at least INET_ADDRSTRLEN bytes long.
AF_INET6
src points to a struct in6_addr (network byte order format) which is converted to a representation of this address in the most appropriate IPv6 network address format for this address. The buffer dst must be at least INET6_ADDRSTRLEN bytes long.

RETURN VALUE

inet_ntop() returns a non-null pointer to dst. NULL is returned if there was an error, with errno set to EAFNOSUPPORT if af was not set to a valid address family, or to ENOSPC if the converted address string would exceed the size of dst given by the cnt argument.

CONFORMING TO

POSIX.1-2001. Note that RFC 2553 defines a prototype where the last parameter cnt is of type size_t. Many systems follow RFC 2553. Glibc 2.0 and 2.1 have size_t, but 2.2 has socklen_t.

BUGS

AF_INET6 converts IPv6-mapped IPv4 addresses into an IPv6 format.

SEE ALSO

inet_pton(3)


fts_close (3)

 Continue to this page.


getipnodebyname(3)

GETIPNODEBYNAME

Section: Linux Programmer's Manual (3)
Updated: 2002-04-03 Return to Main Contents

NAME

getipnodebyname, getipnodebyaddr, freehostent - get network host names and addresses

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

struct hostent *getipnodebyname(const char *name,
                         int af, int flags,
                         int *error_num);

struct hostent *getipnodebyaddr(const void *addr,
                         size_t len, int af,
                         int *error_num);

void freehostent(struct hostent *ip);

DESCRIPTION

These functions are deprecated. Use getaddrinfo(3) and getnameinfo(3) instead.

The getipnodebyname(3) and getipnodebyaddr(3) functions return the names and addresses of a network host. These functions return a pointer to the following structure:

struct  hostent {
        char    *h_name;
        char    **h_aliases;
        int     h_addrtype;
        int     h_length;
        char    **h_addr_list;
};

These functions replace the gethostbyname(3) and gethostbyaddr(3) functions, which could only access the IPv4 network address family. The getipnodebyname(3) and getipnodebyaddr(3) functions can access multiple network address families.

Unlike the gethostby functions, these functions return pointers to dynamically allocated memory. The freehostent(3) function is used to release the dynamically allocated memory after the caller no longer needs the hostent structure.

getipnodebyname parameters

The getipnodebyname(3) function looks up network addresses for the host specified by the name parameter. The af parameter specifies one of the following values:
AF_INET
The name parameter points to a dotted-quad IPv4 address or a name of an IPv4 network host.
AF_INET6
The name parameter points to a hexadecimal IPv6 address or a name of an IPv6 network host.

The flags parameter specifies additional options. More than one option can be specified by logically OR-ing them together. flags should be set to 0 if no options are desired.

AI_V4MAPPED
This flag is used with AF_INET6 to request a query for IPv4 addresses instead of IPv6 addresses; the IPv4 addresses will be mapped to IPv6 addresses.
AI_ALL
This flag is used with AI_V4MAPPED to request a query for both IPv4 and IPv6 addresses. Any IPv4 address found will be mapped to an IPv6 address.
AI_ADDRCONFIG
This flag is used with AF_INET6 to further request that queries for IPv6 addresses should not be made unless the system has at least one IPv6 address assigned to a network interface, and that queries for IPv4 addresses should not be made unless the system has at least one IPv4 address assigned to a network interface. This flag may be used by itself or with the AI_V4MAPPED flag.
AI_DEFAULT
This flag is equivalent to (AI_ADDRCONFIG | AI_V4MAPPED).

getipnodebyaddr parameters

The getipnodebyaddr(3) function looks up the name of the host whose network address is specified by the addr parameter. The af parameter specifies one of the following values:
AF_INET
The addr parameter points to a struct in_addr and len must be set to sizeof(struct in_addr).
AF_INET6
The addr parameter points to a struct in6_addr and len must be set to sizeof(struct in6_addr).

RETURN VALUE

A null pointer is returned if an error occurred, and error_num will contain an error code from the following list:
HOST_NOT_FOUND
The host name or network address was not found.
NO_ADDRESS
The domain name server recognized the network address or name, but no answer was returned. This can happen if the network host has only IPv4 addresses and a request has been made for IPv6 information only, or vice versa.
NO_RECOVERY
The domain name server returned a permanent failure response.
TRY_AGAIN
The domain name server returned a temporary failure response. You might have better luck next time.

A successful query returns a pointer to a hostent structure that contains the following fields:

h_name
This is the official name of this network host.
h_aliases
This is an array of pointers to unofficial aliases for the same host. The array is terminated by a null pointer.
h_addrtype
This is a copy of the af parameter to getipnodebyname(3) or getipnodebyaddr(3). h_addrtype will always be AF_INET if the af parameter was AF_INET. h_addrtype will always be AF_INET6 if the af parameter was AF_INET6.
h_length
This field will be set to sizeof(struct in_addr) if h_addrtype is AF_INET, and to sizeof(struct in6_addr) if h_addrtype is AF_INET6.
h_addr_list
This is an array of one or more pointers to network address structures for the network host. The array is terminated by a null pointer.

CONFORMING TO

RFC 2553.

NOTES

These functions have been present in glibc 2.1.91-95, but were removed again. Several Unix-like systems support them, but all call them deprecated.

SEE ALSO

getaddrinfo(3), getnameinfo(3), inet_ntop(3), inet_pton(3)


freeaddrinfo (3)

 Continue to this page.


gai_strerror (3)

 Continue to this page.


getipnodebyaddr (3)

 Continue to this page.


setkey (3)

 Continue to this page.


lockf(3)

LOCKF

Section: Linux Programmer's Manual (3)
Updated: 2002-04-22 Return to Main Contents

NAME

lockf - apply, test or remove a POSIX lock on an open file

SYNOPSIS

#include <unistd.h>

int lockf(int fd, int cmd, off_t len);

DESCRIPTION

Apply, test or remove a POSIX lock on a section of an open file. The file is specified by fd, a file descriptor open for writing, the action by cmd, and the section consists of byte positions pos..pos+len-1 if len is positive, and pos-len..pos-1 if len is negative, where pos is the current file position, and if len is zero, the section extends from the current file position to infinity, encompassing the present and future end-of-file positions. In all cases, the section may extend past current end-of-file.

On Linux, this call is just an interface for fcntl(2). (In general, the relation between lockf() and fcntl(2) is unspecified.)

Valid operations are given below:

F_LOCK
Set an exclusive lock on the specified section of the file. If (part of) this section is already locked, the call blocks until the previous lock is released. If this section overlaps an earlier locked section, both are merged. File locks are released as soon as the process holding the locks closes some file descriptor for the file. A child process does not inherit these locks.
F_TLOCK
Same as F_LOCK but the call never blocks and returns an error instead if the file is already locked.
F_ULOCK
Unlock the indicated section of the file. This may cause a locked section to be split into two locked sections.
F_TEST
Test the lock: return 0 if the specified section is unlocked or locked by this process; return -1, set errno to EAGAIN (EACCES on some other systems), if another process holds a lock.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

EACCES or EAGAIN
The file is locked and F_TLOCK or F_TEST was specified, or the operation is prohibited because the file has been memory-mapped by another process.
EBADF
fd is not an open file descriptor.
EDEADLK
The command was T_LOCK and this lock operation would cause a deadlock.
EINVAL
An invalid operation was specified in fd.
ENOLCK
Too many segment locks open, lock table is full.

CONFORMING TO

SVr4, POSIX.1-2001

SEE ALSO

fcntl(2), flock(2)
There are also locks.txt and mandatory.txt in /usr/src/linux/Documentation.


inet_pton(3)

INET_PTON

Section: Linux Programmer's Manual (3)
Updated: 2000-12-18 Return to Main Contents

NAME

inet_pton - Create a network address structure

SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int inet_pton(int af, const char *src, void *dst);

DESCRIPTION

This function converts the character string src into a network address structure in the af address family, then copies the network address structure to dst.

inet_pton(3) extends the inet_addr(3) function to support multiple address families, inet_addr(3) is now considered to be deprecated in favor of inet_pton(3). The following address families are currently supported:

AF_INET
src points to a character string containing an IPv4 network address in the dotted-quad format, "ddd.ddd.ddd.ddd". The address is converted to a struct in_addr and copied to dst, which must be sizeof(struct in_addr) bytes long.
AF_INET6
src points to a character string containing an IPv6 network address in any allowed IPv6 address format. The address is converted to a struct in6_addr and copied to dst, which must be sizeof(struct in6_addr) bytes long.

Certain legacy hex and octal formats of AF_INET addresses are not supported by inet_pton(), which rejects them.

RETURN VALUE

inet_pton() returns a negative value and sets errno to EAFNOSUPPORT if af does not contain a valid address family. 0 is returned if src does not contain a character string representing a valid network address in the specified address family. A positive value is returned if the network address was successfully converted.

CONFORMING TO

POSIX.1-2001.

BUGS

AF_INET6 does not recognize IPv4 addresses. An explicit IPv6-mapped IPv4 address must be supplied in src instead.

SEE ALSO

inet_ntop(3)


dlopen(3)

DLOPEN

Section: Linux Programmer's Manual (3)
Updated: 2003-11-17 Return to Main Contents

NAME

dladdr, dlclose, dlerror, dlopen, dlsym, dlvsym - programming interface to dynamic linking loader

SYNOPSIS

#include <dlfcn.h>

void *dlopen(const char *filename, int flag);

char *dlerror(void);

void *dlsym(void *handle, const char *symbol);

int dlclose(void *handle);

DESCRIPTION

The four functions dlopen(), dlsym(), dlclose(), dlerror() implement the interface to the dynamic linking loader.

dlerror

The function dlerror() returns a human readable string describing the most recent error that occurred from dlopen(), dlsym() or dlclose() since the last call to dlerror(). It returns NULL if no errors have occurred since initialization or since it was last called.

dlopen

The function dlopen() loads the dynamic library file named by the null-terminated string filename and returns an opaque "handle" for the dynamic library. If filename is NULL, then the returned handle is for the main program. If filename contains a slash ("/"), then it is interpreted as a (relative or absolute) pathname. Otherwise, the dynamic linker searches for the library as follows (see ld.so(8) for further details):
o
(ELF only) If the executable file for the calling program contains a DT_RPATH tag, and does not contain a DT_RUNPATH tag, then the directories listed in the DT_RPATH tag are searched.
o
If the environment variable LD_LIBRARY_PATH is defined to contain a colon-separated list of directories, then these are searched. (As a security measure this variable is ignored for set-user-ID and set-group-ID programs.)
o
(ELF only) If the executable file for the calling program contains a DT_RUNPATH tag, then the directories listed in that tag are searched.
o
The cache file /etc/ld.so.cache (maintained by ldconfig(8)) is checked to see whether it contains an entry for filename.
o
The directories /lib and /usr/lib are searched (in that order).

If the library has dependencies on other shared libraries, then these are also automatically loaded by the dynamic linker using the same rules. (This process may occur recursively, if those libraries in turn have dependencies, and so on.)

One of the following two values must be included in flag:

RTLD_LAZY
Perform lazy binding. Only resolve symbols as the code that references them is executed. If the symbol is never referenced, then it is never resolved. (Lazy binding is only performed for function references; references to variables are always immediately bound when the library is loaded.)
RTLD_NOW
If this value is specified, or the environment variable LD_BIND_NOW is set to a non-empty string, all undefined symbols in the library are resolved before dlopen() returns. If this cannot be done, an error is returned.

Zero of more of the following values may also be ORed in flag:

RTLD_GLOBAL
The symbols defined by this library will be made available for symbol resolution of subsequently loaded libraries.
RTLD_LOCAL
This is the converse of RTLD_GLOBAL, and the default if neither flag is specified. Symbols defined in this library are not made available to resolve references in subsequently loaded libraries.
RTLD_NODELETE (since glibc 2.2)
Do not unload the library during dlclose(). Consequently, the library's static variables are not reinitialized if the library is reloaded with dlopen() at a later time. This flag is not specified in POSIX.1-2001.
RTLD_NOLOAD (since glibc 2.2)
Don't load the library. This can be used to test if the library is already resident (dlopen() returns NULL if it is not, or the library's handle if it is resident). This flag can also be used to promote the flags on a library that is already loaded. For example, a library that was previously loaded with RTLD_LOCAL can be re-opened with RTLD_NOLOAD | RTLD_GLOBAL. This flag is not specified in POSIX.1-2001.
RTLD_DEEPBIND (since glibc 2.3.4)
Place the lookup scope of the symbols in this library ahead of the global scope. This means that a self-contained library will use its own symbols in preference to global symbols with the same name contained in libraries that have already been loaded. This flag is not specified in POSIX.1-2001.

If filename is a NULL pointer, then the returned handle is for the main program. When given to dlsym(), this handle causes a search for a symbol in the main program, followed by all shared libraries loaded at program startup, and then all shared libraries loaded by dlopen() with the flag RTLD_GLOBAL.

External references in the library are resolved using the libraries in that library's dependency list and any other libraries previously opened with the RTLD_GLOBAL flag. If the executable was linked with the flag "-rdynamic" (or, synonymously, "--export-dynamic"), then the global symbols in the executable will also be used to resolve references in a dynamically loaded library.

If the same library is loaded again with dlopen(), the same file handle is returned. The dl library maintains reference counts for library handles, so a dynamic library is not deallocated until dlclose() has been called on it as many times as dlopen() has succeeded on it. The _init routine, if present, is only called once. But a subsequent call with RTLD_NOW may force symbol resolution for a library earlier loaded with RTLD_LAZY.

If dlopen() fails for any reason, it returns NULL.

dlsym

The function dlsym() takes a "handle" of a dynamic library returned by dlopen() and the null-terminated symbol name, returning the address where that symbol is loaded into memory. If the symbol is not found, in the specified library or any of the libraries that were automatically loaded by dlopen() when that library was loaded, dlsym() returns NULL. (The search performed by dlsym() is breadth first through the dependency tree of these libraries.) Since the value of the symbol could actually be NULL (so that a NULL return from dlsym() need not indicate an error), the correct way to test for an error is to call dlerror() to clear any old error conditions, then call dlsym(), and then call dlerror() again, saving its return value into a variable, and check whether this saved value is not NULL.

There are two special pseudo-handles, RTLD_DEFAULT and RTLD_NEXT. The former will find the first occurrence of the desired symbol using the default library search order. The latter will find the next occurrence of a function in the search order after the current library. This allows one to provide a wrapper around a function in another shared library.

dlclose

The function dlclose() decrements the reference count on the dynamic library handle handle. If the reference count drops to zero and no other loaded libraries use symbols in it, then the dynamic library is unloaded.

The function dlclose() returns 0 on success, and non-zero on error.

The obsolete symbols _init and _fini

The linker recognizes special symbols _init and _fini. If a dynamic library exports a routine named _init, then that code is executed after the loading, before dlopen() returns. If the dynamic library exports a routine named _fini, then that routine is called just before the library is unloaded. In case you need to avoid linking against the system startup files, this can be done by giving gcc the "-nostartfiles" parameter on the command line.

Using these routines, or the gcc -nostartfiles or -nostdlib options, is not recommended. Their use may result in undesired behavior, since the constructor/destructor routines will not be executed (unless special measures are taken).

Instead, libraries should export routines using the __attribute__((constructor)) and __attribute__((destructor)) function attributes. See the gcc info pages for information on these. Constructor routines are executed before dlopen() returns, and destructor routines are executed before dlclose() returns.

Glibc extensions: dladdr() and dlvsym()

Glibc adds two functions not described by POSIX, with prototypes

#define _GNU_SOURCE
#include <dlfcn.h>

int dladdr(void *addr, Dl_info *info);

void *dlvsym(void *handle, char *symbol, char *version);

The function dladdr() takes a function pointer and tries to resolve name and file where it is located. Information is stored in the Dl_info structure:

typedef struct {
  const char *dli_fname;/* Filename of defining object */
  void *dli_fbase;      /* Load address of that object */
  const char *dli_sname;/* Name of nearest lower symbol */
  void *dli_saddr;      /* Exact value of nearest symbol */
} Dl_info;

dladdr() returns 0 on error, and non-zero on success.

The function dlvsym() does the same as dlsym() but takes a version string as an additional argument.

CONFORMING TO

POSIX.1-2001 describes dlclose(), dlerror(), dlopen(), and dlsym().

NOTES

The symbols RTLD_DEFAULT and RTLD_NEXT are defined by <dlfcn.h> only when _GNU_SOURCE was defined before including it.

Since glibc 2.2.3, atexit(3) can be used to register an exit handler that is automatically called when a library is unloaded.

History

The dlopen interface standard comes from SunOS. That system also has dladdr(), but not dlvsym().

EXAMPLE

Load the math library, and print the cosine of 2.0:

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int
main(int argc, char **argv)
{
    void *handle;
    double (*cosine)(double);
    char *error;

    handle = dlopen("libm.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }

    dlerror();    /* Clear any existing error */
    *(void **) (&cosine) = dlsym(handle, "cos");
    if ((error = dlerror()) != NULL)  {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }

    printf("%f\n", (*cosine)(2.0));
    dlclose(handle);
    exit(EXIT_SUCCESS);
}

If this program were in a file named "foo.c", you would build the program with the following command:

gcc -rdynamic -o foo foo.c -ldl

Libraries exporting _init() and _fini() will want to be compiled as follows, using bar.c as the example name:

gcc -shared -nostartfiles -o bar bar.c

SEE ALSO

ld(1), ldd(1), dl_iterate_phdr(3), feature_test_macros(7) ld.so(8), ldconfig(8), ld.so info pages, gcc info pages, ld info pages


callrpc (3)

 Continue to this page.


dlclose (3)

 Continue to this page.


fenv(3)

FENV

Section: Linux Programmer's Manual (3)
Updated: 2000-08-12 Return to Main Contents

NAME

feclearexcept, fegetexceptflag, feraiseexcept, fesetexceptflag, fetestexcept, fegetenv, fegetround, feholdexcept, fesetround, fesetenv, feupdateenv, feenableexcept, fedisableexcept, fegetexcept - floating point rounding and exception handling

SYNOPSIS

#include <fenv.h>

int feclearexcept(int excepts);

int fegetexceptflag(fexcept_t *flagp, int excepts);

int feraiseexcept(int excepts);

int fesetexceptflag(const fexcept_t *flagp, int excepts);

int fetestexcept(int excepts);

int fegetround(void);

int fesetround(int rounding_mode);

int fegetenv(fenv_t *envp);

int feholdexcept(fenv_t *envp);

int fesetenv(const fenv_t *envp);

int feupdateenv(const fenv_t *envp);

Link with -lm.

DESCRIPTION

These eleven functions were defined in C99, and describe the handling of floating point rounding and exceptions (overflow, zero-divide etc.).

Exceptions

The DivideByZero exception occurs when an operation on finite numbers produces infinity as exact answer.

The Overflow exception occurs when a result has to be represented as a floating point number, but has (much) larger absolute value than the largest (finite) floating point number that is representable.

The Underflow exception occurs when a result has to be represented as a floating point number, but has smaller absolute value than the smallest positive normalized floating point number (and would lose much accuracy when represented as a denormalized number).

The Inexact exception occurs when the rounded result of an operation is not equal to the infinite precision result. It may occur whenever Overflow or Underflow occurs.

The Invalid exception occurs when there is no well-defined result for an operation, as for 0/0 or infinity - infinity or sqrt(-1).

Exception handling

Exceptions are represented in two ways: as a single bit (exception present/absent), and these bits correspond in some implementation-defined way with bit positions in an integer, and also as an opaque structure that may contain more information about the exception (perhaps the code address where it occurred).

Each of the macros FE_DIVBYZERO, FE_INEXACT, FE_INVALID, FE_OVERFLOW, FE_UNDERFLOW is defined when the implementation supports handling of the corresponding exception, and if so then defines the corresponding bit(s), so that one can call exception handling functions, for example, using the integer argument FE_OVERFLOW|FE_UNDERFLOW. Other exceptions may be supported. The macro FE_ALL_EXCEPT is the bitwise OR of all bits corresponding to supported exceptions.

The feclearexcept() function clears the supported exceptions represented by the bits in its argument.

The fegetexceptflag() function stores a representation of the state of the exception flags represented by the argument excepts in the opaque object *flagp.

The feraiseexcept() function raises the supported exceptions represented by the bits in excepts.

The fesetexceptflag() function sets the complete status for the exceptions represented by excepts to the value *flagp. This value must have been obtained by an earlier call of fegetexceptflag() with a last argument that contained all bits in excepts.

The fetestexcept() function returns a word in which the bits are set that were set in the argument excepts and for which the corresponding exception is currently set.

Rounding

Each of the macros FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD is defined when the implementation supports getting and setting the corresponding rounding direction.

The fegetround() function returns the macro corresponding to the current rounding mode.

The fesetround() function sets the rounding mode as specified by its argument and returns zero when it was successful.

Floating point environment

The entire floating point environment, including control modes and status flags, can be handled as one opaque object, of type fenv_t. The default environment is denoted by FE_DFL_ENV (of type const fenv_t *). This is the environment setup at program start and it is defined by ISO C to have round to nearest, all exceptions cleared and a non-stop (continue on exceptions) mode.

The fegetenv() function saves the current floating point environment in the object *envp.

The feholdexcept() function does the same, then clears all exception flags, and sets a non-stop (continue on exceptions) mode, if available. It returns zero when successful.

The fesetenv() function restores the floating point environment from the object *envp. This object must be known to be valid, for example, the result of a call to fegetenv() or feholdexcept() or equal to FE_DFL_ENV. This call does not raise exceptions.

The feupdateenv() function installs the floating-point environment represented by the object *envp, except that currently raised exceptions are not cleared. After calling this function, the raised exceptions will be a bitwise OR of those previously set with those in *envp. As before, the object *envp must be known to be valid.

RETURN VALUE

These functions return zero on success and non-zero if an error occurred.

CONFORMING TO

IEC 60559 (IEC 559:1989), ANSI/IEEE 854, C99.

NOTES

Glibc Notes

If possible, the GNU C Library defines a macro FE_NOMASK_ENV which represents an environment where every exception raised causes a trap to occur. You can test for this macro using #ifdef. It is only defined if _GNU_SOURCE is defined. The C99 standard does not define a way to set individual bits in the floating point mask, for example, to trap on specific flags. glibc 2.2 supports the functions feenableexcept() and fedisableexcept() to set individual floating point traps, and fegetexcept() to query the state.

#define _GNU_SOURCE

#include <fenv.h>

int feenableexcept(int excepts);

int fedisableexcept(int excepts);

int fegetexcept(void);

The feenableexcept() and fedisableexcept() functions enable (disable) traps for each of the exceptions represented by excepts and return the previous set of enabled exceptions when successful, and -1 otherwise. The fegetexcept() function returns the set of all currently enabled exceptions.

SEE ALSO

feature_test_macros(7)


dlerror (3)

 Continue to this page.


llabs (3)

 Continue to this page.


dlsym (3)

 Continue to this page.


encrypt(3)

ENCRYPT

Section: Linux Programmer's Manual (3)
Updated: 2003-04-04 Return to Main Contents

NAME

encrypt, setkey, encrypt_r, setkey_r - encrypt 64-bit messages

SYNOPSIS

#define _XOPEN_SOURCE
#include <unistd.h>

void encrypt(char block[64], int edflag);

#define _XOPEN_SOURCE
#include <stdlib.h>

void setkey(const char *key);

#define _GNU_SOURCE
#include <crypt.h>

void setkey_r(const char *key, struct crypt_data *data);
void encrypt_r(char *block, int edflag, struct crypt_data *data);

Each of these requires linking with -lcrypt.

DESCRIPTION

These functions encrypt and decrypt 64-bit messages. The setkey() function sets the key used by encrypt(). The key parameter used here is an array of 64 bytes, each of which has numerical value 1 or 0. The bytes key[n] where n=8*i-1 are ignored, so that the effective key length is 56 bits.

The encrypt() function modifies the passed buffer, encoding if edflag is 0, and decoding if 1 is being passed. Like the key parameter also block is a bit vector representation of the actual value that is encoded. The result is returned in that same vector.

These two functions are not reentrant, that is, the key data is kept in static storage. The functions setkey_r() and encrypt_r() are the reentrant versions. They use the following structure to hold the key data:

struct crypt_data {
    char     keysched[16 * 8];
    char     sb0[32768];
    char     sb1[32768];
    char     sb2[32768];
    char     sb3[32768];
    char     crypt_3_buf[14];
    char     current_salt[2];
    long int current_saltbits;
    int      direction;
    int      initialized;
};
Before calling setkey_r() set data->initialized to zero.

RETURN VALUE

These functions do not return any value.

ERRORS

Set errno to zero before calling the above functions. On success, it is unchanged.
ENOSYS
The function is not provided. (For example because of former USA export restrictions.)

CONFORMING TO

The functions encrypt() and setkey() conform to SVr4, SUSv2, and POSIX.1-2001. The functions encrypt_r() and setkey_r() are GNU extensions.

NOTES

In glibc 2.2 these functions use the DES algorithm.

EXAMPLE

You need to link with libcrypt to compile this example with glibc 2.2. To do useful work the key[] and txt[] arrays must be filled with a useful bit pattern.

#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdlib.h>

int
main(void)
{
    char key[64];      /* bit pattern for key */
    char txt[64];      /* bit pattern for messages */

    setkey(key);
    encrypt(txt, 0);   /* encode */
    encrypt(txt, 1);   /* decode */
}

SEE ALSO

cbc_crypt(3), crypt(3), ecb_crypt(3), feature_test_macros(7)


daemon(3)

DAEMON

Section: Linux Programmer's Manual (3)
Updated: 1993-06-09 Return to Main Contents

NAME

daemon - run in the background

SYNOPSIS

#include <unistd.h>

int daemon(int nochdir, int noclose);

DESCRIPTION

The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons.

Unless the argument nochdir is non-zero, daemon() changes the current working directory to the root ("/").

Unless the argument noclose is non-zero, daemon() will redirect standard input, standard output and standard error to /dev/null.

RETURN VALUE

(This function forks, and if the fork(2) succeeds, the parent does _exit(0), so that further errors are seen by the child only.) On success zero will be returned. If an error occurs, daemon() returns -1 and sets the global variable errno to any of the errors specified for the fork(2) and setsid(2).

CONFORMING TO

Not in POSIX.1-2001. A similar function appears on the BSDs. The daemon() function first appeared in 4.4BSD.

NOTES

The glibc implementation can also return -1 when /dev/null exists but is not a character device with the expected major and minor numbers. In this case errno need not be set.

SEE ALSO

fork(2), setsid(2)


clnt_call (3)

 Continue to this page.


strtok_r (3)

 Continue to this page.


swprintf (3)

 Continue to this page.


freehostent (3)

 Continue to this page.


feclearexcept (3)

 Continue to this page.


auth_destroy (3)

 Continue to this page.


authnone_create (3)

 Continue to this page.


vfwprintf (3)

 Continue to this page.


pmap_set (3)

 Continue to this page.


vswprintf (3)

 Continue to this page.


pmap_unset (3)

 Continue to this page.


vwprintf (3)

 Continue to this page.


authunix_create (3)

 Continue to this page.


authunix_create_default (3)

 Continue to this page.


clnt_broadcast (3)

 Continue to this page.


clnt_destroy (3)

 Continue to this page.


clnt_create (3)

 Continue to this page.


clnt_control (3)

 Continue to this page.


clnt_freeres (3)

 Continue to this page.


clnt_geterr (3)

 Continue to this page.


clnt_pcreateerror (3)

 Continue to this page.


clnt_perrno (3)

 Continue to this page.


clnt_perror (3)

 Continue to this page.


clnt_sperrno (3)

 Continue to this page.


clnt_sperror (3)

 Continue to this page.


clntraw_create (3)

 Continue to this page.


clnttcp_create (3)

 Continue to this page.


clntudp_create (3)

 Continue to this page.


clntudp_bufcreate (3)

 Continue to this page.


get_myaddress (3)

 Continue to this page.


pmap_getmaps (3)

 Continue to this page.


pmap_getport (3)

 Continue to this page.


wprintf(3)

WPRINTF

Section: Linux Programmer's Manual (3)
Updated: 1999-11-20 Return to Main Contents

NAME

wprintf, fwprintf, swprintf, vwprintf, vfwprintf, vswprintf - formatted wide-character output conversion

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

int wprintf(const wchar_t *format, ...);
int fwprintf(FILE *stream, const wchar_t *format, ...);
int swprintf(wchar_t *wcs, size_t maxlen,
             const wchar_t *format, ...);

#include <stdarg.h>

int vwprintf(const wchar_t *format, va_list args);
int vfwprintf(FILE *stream, const wchar_t *format, va_list args);
int vswprintf(wchar_t *wcs, size_t maxlen,
              const wchar_t *format, va_list args);

DESCRIPTION

The wprintf() family of functions is the wide-character equivalent of the printf(3) family of functions. It performs formatted output of wide characters.

The wprintf() and vwprintf() functions perform wide-character output to stdout. stdout must not be byte oriented; see function fwide(3) for more information.

The fwprintf() and vfwprintf() functions perform wide-character output to stream. stream must not be byte oriented; see function fwide(3) for more information.

The swprintf() and vswprintf() functions perform wide-character output to an array of wide characters. The programmer must ensure that there is room for at least maxlen wide characters at wcs.

These functions are like
the
printf(3),

vprintf(3),

fprintf(3),

vfprintf(3),

sprintf(3),

vsprintf(3)

functions except for the
following differences:

*
The format string is a wide-character string.
*
The output consists of wide characters, not bytes.
*
swprintf() and vswprintf() take a maxlen argument, sprintf(3) and vsprintf(3) do not. (snprintf(3) and vsnprintf(3) take a maxlen argument, but these functions do not return -1 upon buffer overflow on Linux.)

The treatment of the conversion characters c and s is different:

c
If no l modifier is present, the int argument is converted to a wide character by a call to the btowc(3) function, and the resulting wide character is written. If an l modifier is present, the wint_t (wide character) argument is written.
s
If no l modifier is present: The ``const char *'' argument is expected to be a pointer to an array of character type (pointer to a string) containing a multibyte character sequence beginning in the initial shift state. Characters from the array are converted to wide characters (each by a call to the mbrtowc(3) function with a conversion state starting in the initial state before the first byte). The resulting wide characters are written up to (but not including) the terminating null wide character. If a precision is specified, no more wide characters than the number specified are written. Note that the precision determines the number of wide characters written, not the number of bytes or screen positions. The array must contain a terminating null byte, unless a precision is given and it is so small that the number of converted wide characters reaches it before the end of the array is reached. If an l modifier is present: The ``const wchar_t *'' argument is expected to be a pointer to an array of wide characters. Wide characters from the array are written up to (but not including) a terminating null wide character. If a precision is specified, no more than the number specified are written. The array must contain a terminating null wide character, unless a precision is given and it is smaller than or equal to the number of wide characters in the array.

RETURN VALUE

The functions return the number of wide characters written, excluding the terminating null wide character in case of the functions swprintf() and vswprintf(). They return -1 when an error occurs.

CONFORMING TO

C99.

NOTES

The behavior of wprintf() et al. depends on the LC_CTYPE category of the current locale.

If the format string contains non-ASCII wide characters, the program will only work correctly if the LC_CTYPE category of the current locale at run time is the same as the LC_CTYPE category of the current locale at compile time. This is because the wchar_t representation is platform and locale dependent. (The GNU libc represents wide characters using their Unicode (ISO-10646) code point, but other platforms don't do this. Also, the use of C99 universal character names of the form \unnnn does not solve this problem.) Therefore, in internationalized programs, the format string should consist of ASCII wide characters only, or should be constructed at run time in an internationalized way (e.g., using gettext(3) or iconv(3), followed by mbstowcs(3)).

SEE ALSO

fprintf(3), fputwc(3), fwide(3), printf(3), snprintf(3)


pmap_rmtcall (3)

 Continue to this page.


clnt_spcreateerror (3)

 Continue to this page.


registerrpc (3)

 Continue to this page.


svc_destroy (3)

 Continue to this page.


svcraw_create (3)

 Continue to this page.


svcudp_create (3)

 Continue to this page.


svc_freeargs (3)

 Continue to this page.


svc_getargs (3)

 Continue to this page.


svc_getcaller (3)

 Continue to this page.


svc_getreqset (3)

 Continue to this page.


svc_getreq (3)

 Continue to this page.


svc_register (3)

 Continue to this page.


svc_run (3)

 Continue to this page.


svc_sendreply (3)

 Continue to this page.


svc_unregister (3)

 Continue to this page.


svcerr_auth (3)

 Continue to this page.


svcerr_decode (3)

 Continue to this page.


svcerr_noproc (3)

 Continue to this page.


svcerr_noprog (3)

 Continue to this page.


svcerr_progvers (3)

 Continue to this page.


svcerr_systemerr (3)

 Continue to this page.


svcerr_weakauth (3)

 Continue to this page.


svcfd_create (3)

 Continue to this page.


svctcp_create (3)

 Continue to this page.


svcudp_bufcreate (3)

 Continue to this page.


strfmon(3)

STRFMON

Section: Linux Programmer's Manual (3)
Updated: 2000-12-05 Return to Main Contents

NAME

strfmon - convert monetary value to a string

SYNOPSIS

#include <monetary.h>

ssize_t strfmon(char *s, size_t max, const char *format, ...);

DESCRIPTION

The strfmon() function formats the specified amounts according to the format specification format and places the result in the character array s of size max.

Ordinary characters in format are copied to s without conversion. Conversion specifiers are introduced by a `%' character. Immediately following it there can be zero or more of the following flags:

=f
The single-byte character f is used as the numeric fill character (to be used with a left precision, see below). When not specified, the space character is used.
^
Do not use any grouping characters that might be defined for the current locale. By default, grouping is enabled.
( or +
The ( flag indicates that negative amounts should be enclosed between parentheses. The + flag indicates that signs should be handled in the default way, that is, amounts are preceded by the locale's sign indication, for example, nothing for positive, "-" for negative.
!
Omit the currency symbol.
-
Left justify all fields. The default is right justification.

Next, there may be a field width: a decimal digit string specifying a minimum field width in bytes. The default is 0. A result smaller than this width is padded with spaces (on the left, unless the left-justify flag was given).

Next, there may be a left precision of the form "#" followed by a decimal digit string. If the number of digits left of the radix character is smaller than this, the representation is padded on the left with the numeric fill character. Grouping characters are not counted in this field width.

Next, there may be a right precision of the form "." followed by a decimal digit string. The amount being formatted is rounded to the specified number of digits prior to formatting. The default is specified in the frac_digits and int_frac_digits items of the current locale. If the right precision is 0, no radix character is printed. (The radix character here is determined by LC_MONETARY, and may differ from that specified by LC_NUMERIC.)

Finally, the conversion specification must be ended with a conversion character. The three conversion characters are

%
(In this case the entire specification must be exactly "%%".) Put a `%' character in the result string.
i
One argument of type double is converted using the locale's international currency format.
n
One argument of type double is converted using the locale's national currency format.

RETURN VALUE

The strfmon() function returns the number of characters placed in the array s, not including the terminating null byte, provided the string, including the terminating null byte, fits. Otherwise, it sets errno to E2BIG, returns -1, and the contents of the array is undefined.

CONFORMING TO

Not in POSIX.1-2001. Present on several other systems.

EXAMPLE

The call

strfmon(buf, sizeof(buf), "[%^=*#6n] [%=*#6i]",
        1234.567, 1234.567);
outputs

[ fl **1234,57] [ NLG **1 234,57]

in the Dutch locale (with fl for "florijnen" and NLG for Netherlands Guilders). The grouping character is very ugly because it takes as much space as a digit, while it should not take more than half that, and will no doubt cause confusion. Surprisingly, the "fl" is preceded and followed by a space, and "NLG" is preceded by one and followed by two spaces. This may be a bug in the locale files. The Italian, Australian, Swiss and Portuguese locales yield

[ L. **1235] [ ITL **1.235]
[ $**1234.57] [ AUD **1,234.57]
[Fr. **1234,57] [CHF **1.234,57]
[ **1234$57Esc] [ **1.234$57PTE ]

SEE ALSO

setlocale(3), sprintf(3), locale(7)


fegetexceptflag (3)

 Continue to this page.


feraiseexcept (3)

 Continue to this page.


fegetenv (3)

 Continue to this page.


fesetexceptflag (3)

 Continue to this page.


fetestexcept (3)

 Continue to this page.


fegetround (3)

 Continue to this page.


feholdexcept (3)

 Continue to this page.


fesetround (3)

 Continue to this page.


fesetenv (3)

 Continue to this page.


feupdateenv (3)

 Continue to this page.


getnameinfo(3)

GETNAMEINFO

Section: Linux Programmer's Manual (3)
Updated: 2007-06-08 Return to Main Contents

NAME

getnameinfo - address-to-name translation in protocol-independent manner

SYNOPSIS

#include <sys/socket.h>
#include <netdb.h>

int getnameinfo(const struct sockaddr *sa, socklen_t salen,
                char *host, size_t hostlen,
                char *serv, size_t servlen, int flags);

DESCRIPTION

The getnameinfo(3) function is defined for protocol-independent address-to-nodename translation. It combines the functionality of gethostbyaddr(3) and getservbyport(3) and is the inverse of getaddrinfo(3). The sa argument is a pointer to a generic socket address structure (of type sockaddr_in or sockaddr_in6) of size salen that holds the input IP address and port number. The arguments host and serv are pointers to buffers (of size hostlen and servlen respectively) to hold the return values.

The caller can specify that no hostname (or no service name) is required by providing a NULL host (or serv) argument or a zero hostlen (or servlen) parameter. However, at least one of hostname or service name must be requested.

The flags argument modifies the behavior of getnameinfo(3) as follows:

NI_NOFQDN
If set, return only the hostname part of the FQDN for local hosts.
NI_NUMERICHOST
If set, then the numeric form of the hostname is returned. (When not set, this will still happen in case the node's name cannot be looked up.)
NI_NAMEREQD
If set, then a error is returned if the hostname cannot be looked up.
NI_NUMERICSERV
If set, then the service address is returned in numeric form, for example by its port number.
NI_DGRAM
If set, then the service is datagram (UDP) based rather than stream (TCP) based. This is required for the few ports (512-514) that have different services for UDP and TCP.

Extensions to getaddrinfo() for Internationalized Domain Names

Starting with glibc 2.3.4, getnameinfo() has been extended to selectively allow host names to be transparently converted to and from the Internationalized Domain Name (IDN) format (see RFC 3490, Internationalizing Domain Names in Applications (IDNA)). Three new flags are defined:

NI_IDN
If this flag is used, then the name found in the lookup process is converted from IDN format to the locale's encoding if necessary. ASCII-only names are not affected by the conversion, which makes this flag usable in existing programs and environments.
NI_IDN_ALLOW_UNASSIGNED, NI_IDN_USE_STD3_ASCII_RULES
Setting these flags will enable the IDNA_ALLOW_UNASSIGNED (allow unassigned Unicode code points) and IDNA_USE_STD3_ASCII_RULES (check output to make sure it is a STD3 conforming host name) flags respectively to be used in the IDNA handling.

RETURN VALUE

On success 0 is returned, and node and service names, if requested, are filled with null-terminated strings, possibly truncated to fit the specified buffer lengths. On error one of the following non-zero error codes is returned:
EAI_AGAIN
The name could not be resolved at this time. Try again later.
EAI_BADFLAGS
The flags parameter has an invalid value.
EAI_FAIL
A non-recoverable error occurred.
EAI_FAMILY
The address family was not recognized, or the address length was invalid for the specified family.
EAI_MEMORY
Out of memory.
EAI_NONAME
The name does not resolve for the supplied parameters. NI_NAMEREQD is set and the host's name cannot be located, or neither hostname nor service name were requested.
EAI_OVERFLOW
The buffer pointed to by host or serv was too small.
EAI_SYSTEM
A system error occurred. The error code can be found in errno.

The gai_strerror(3) function translates these error codes to a human readable string, suitable for error reporting.

FILES

/etc/hosts
/etc/nsswitch.conf
/etc/resolv.conf

CONFORMING TO

RFC 2553, POSIX.1-2001.

NOTES

In order to assist the programmer in choosing reasonable sizes for the supplied buffers, <netdb.h> defines the constants

# define NI_MAXHOST      1025
# define NI_MAXSERV      32

The former is the constant MAXDNAME in recent versions of BIND's <arpa/nameser.h> header file. The latter is a guess based on the services listed in the current Assigned Numbers RFC.

EXAMPLE

The following code tries to get the numeric hostname and service name, for a given socket address. Note that there is no hardcoded reference to a particular address family.

struct sockaddr *sa;    /* input */
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), sbuf,
            sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV) == 0)
    printf("host=%s, serv=%s\n", hbuf, sbuf);

The following version checks if the socket address has a reverse address mapping.

struct sockaddr *sa;    /* input */
char hbuf[NI_MAXHOST];

if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf),
            NULL, 0, NI_NAMEREQD))
    printf("could not resolve hostname");
else
    printf("host=%s\n", hbuf);

An example program using getnameinfo() can be found in getaddrinfo(3).

SEE ALSO

socket(2), getaddrinfo(3), gethostbyaddr(3), getservbyname(3), getservbyport(3), inet_ntop(3), hosts(5), services(5), hostname(7), named(8)

R. Gilligan, S. Thomson, J. Bound and W. Stevens, Basic Socket Interface Extensions for IPv6, RFC 2553, March 1999.

Tatsuya Jinmei and Atsushi Onoe, An Extension of Format for IPv6 Scoped Addresses, internet draft, work in progress. ftp://ftp.ietf.org/internet-drafts/draft-ietf-ipngwg-scopedaddr-format-02.txt

Craig Metz, Protocol Independence Using the Sockets API, Proceedings of the freenix track: 2000 USENIX annual technical conference, June 2000. http://www.usenix.org/publications/library/proceedings/usenix2000/freenix/metzprotocol.html


imaxabs (3)

 Continue to this page.


atoll (3)

 Continue to this page.


lrint(3)

LRINT

Section: Linux Programmer's Manual (3)
Updated: 2001-05-31 Return to Main Contents

NAME

lrint, lrintf, lrintl, llrint, llrintf, llrintl - round to nearest integer

SYNOPSIS

#include <math.h>

long int lrint(double x);

long int lrintf(float x);

long int lrintl(long double x);

long long int llrint(double x);

long long int llrintf(float x);

long long int llrintl(long double x);

Compile with -std=c99; link with -lm.

DESCRIPTION

These functions round their argument to the nearest integer value, using the current rounding direction. If x is infinite or NaN, or if the rounded value is outside the range of the return type, the numeric result is unspecified. A domain error may occur if the magnitude of x is too large.

RETURN VALUE

The rounded integer value.

ERRORS

EDOM
The magnitude of x is too large and (math_errhandling & MATH_ERRNO) is non-zero.

CONFORMING TO

C99.

SEE ALSO

ceil(3), floor(3), lround(3), nearbyint(3), rint(3), round(3)


atoq (3)

 Continue to this page.


basename(3)

DIRNAME

Section: Linux Programmer's Manual (3)
Updated: 2000-12-14 Return to Main Contents

NAME

dirname, basename - parse pathname components

SYNOPSIS

#include <libgen.h>

char *dirname(char *path);

char *basename(char *path);

DESCRIPTION

Warning: there are two different functions basename() - see below.

The functions dirname() and basename() break a null-terminated pathname string into directory and filename components. In the usual case, dirname() returns the string up to, but not including, the final '/', and basename() returns the component following the final '/'. Trailing '/' characters are not counted as part of the pathname.

If path does not contain a slash, dirname() returns the string "." while basename() returns a copy of path. If path is the string "/", then both dirname() and basename() return the string "/". If path is a NULL pointer or points to an empty string, then both dirname() and basename() return the string ".".

Concatenating the string returned by dirname(), a "/", and the string returned by basename() yields a complete pathname.

Both dirname() and basename() may modify the contents of path, so it may be desirable to pass a copy when calling one of these functions.

These functions may return pointers to statically allocated memory which may be overwritten by subsequent calls. Alternatively, they may return a pointer to some part of path, so that the string referred to by path should not be modified or freed until the pointer returned by the function is no longer required.

The following list of examples (taken from SUSv2) shows the strings returned by dirname() and basename() for different paths:

path            dirname         basename
"/usr/lib"      "/usr"          "lib"
"/usr/"         "/"             "usr"
"usr"           "."             "usr"
"/"             "/"             "/"
"."             "."             "."
".."            "."             ".."

RETURN VALUE

Both dirname() and basename() return pointers to null-terminated strings.

CONFORMING TO

POSIX.1-2001

NOTES

There are two different versions of basename() - the POSIX version described above, and the GNU version, which one gets after

    #define _GNU_SOURCE

    #include <string.h>
The GNU version never modifies its argument, and returns the empty string when path has a trailing slash, and in particular also when it is "/". There is no GNU version of dirname().

With glibc, one gets the POSIX version of basename() when <libgen.h> is included, and the GNU version otherwise.

BUGS

In the glibc implementation of the POSIX versions of these functions they modify their argument, and segfault when called with a static string like "/usr/". Before glibc 2.2.1, the glibc version of dirname() did not correctly handle pathnames with trailing '/' characters, and generated a segfault if given a NULL argument.

EXAMPLE

char *dirc, *basec, *bname, *dname;
char *path = "/etc/passwd";

dirc = strdup(path);
basec = strdup(path);
dname = dirname(dirc);
bname = basename(basec);
printf("dirname=%s, basename=%s\n", dname, bname);

SEE ALSO

basename(1), dirname(1), feature_test_macros(7)


dirname (3)

 Continue to this page.


nl_langinfo(3)

NL_LANGINFO

Section: Linux Programmer's Manual (3)
Updated: 2001-05-11 Return to Main Contents

NAME

nl_langinfo - query language and locale information

SYNOPSIS

#include <langinfo.h>

char *nl_langinfo(nl_item item);

DESCRIPTION

The nl_langinfo() function provides access to locale information in a more flexible way than localeconv(3) does. Individual and additional elements of the locale categories can be queried.

Examples for the locale elements that can be specified in item using the constants defined in <langinfo.h> are:

CODESET (LC_CTYPE)
Return a string with the name of the character encoding used in the selected locale, such as "UTF-8", "ISO-8859-1", or "ANSI_X3.4-1968" (better known as US-ASCII). This is the same string that you get with "locale charmap". For a list of character encoding names, try "locale -m", cf. locale(1).
D_T_FMT (LC_TIME)
Return a string that can be used as a format string for strftime(3) to represent time and date in a locale-specific way.
D_FMT (LC_TIME)
Return a string that can be used as a format string for strftime(3) to represent a date in a locale-specific way.
T_FMT (LC_TIME)
Return a string that can be used as a format string for strftime(3) to represent a time in a locale-specific way.
DAY_{1-7} (LC_TIME)
Return name of the n-th day of the week. [Warning: this follows the US convention DAY_1 = Sunday, not the international convention (ISO 8601) that Monday is the first day of the week.]
ABDAY_{1-7} (LC_TIME)
Return abbreviated name of the n-th day of the week.
MON_{1-12} (LC_TIME)
Return name of the n-th month.
ABMON_{1-12} (LC_TIME)
Return abbreviated name of the n-th month.
RADIXCHAR (LC_NUMERIC)
Return radix character (decimal dot, decimal comma, etc.).
THOUSEP (LC_NUMERIC)
Return separator character for thousands (groups of three digits).
YESEXPR (LC_MESSAGES)
Return a regular expression that can be used with the regex(3) function to recognize a positive response to a yes/no question.
NOEXPR (LC_MESSAGES)
Return a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.
CRNCYSTR (LC_MONETARY)
Return the currency symbol, preceded by "-" if the symbol should appear before the value, "+" if the symbol should appear after the value, or "." if the symbol should replace the radix character.

The above list covers just some examples of items that can be requested. For a more detailed list, consult The GNU C Library Reference Manual.

RETURN VALUE

If no locale has been selected for the appropriate category, nl_langinfo() returns a pointer to the corresponding string in the "C" locale.

If item is not valid, a pointer to an empty string is returned.

This pointer may point to static data that may be overwritten on the next call to nl_langinfo() or setlocale(3).

CONFORMING TO

SUSv2, POSIX.1-2001.

SEE ALSO

locale(1), localeconv(3), setlocale(3), charsets(7), locale(7) The GNU C Library Reference Manual


lround(3)

LROUND

Section: Linux Programmer's Manual (3)
Updated: 2001-05-31 Return to Main Contents

NAME

lround, lroundf, lroundl, llround, llroundf, llroundl - round to nearest integer, away from zero

SYNOPSIS

#include <math.h>

long int lround(double x);

long int lroundf(float x);

long int lroundl(long double x);

long long int llround(double x);

long long int llroundf(float x);

long long int llroundl(long double x);

Compile with -std=c99; link with -lm.

DESCRIPTION

These functions round their argument to the nearest integer value, rounding away from zero, regardless of the current rounding direction. If x is infinite or NaN, or if the rounded value is outside the range of the return type, the numeric result is unspecified. A domain error may occur if the magnitude of x is too large.

RETURN VALUE

The rounded integer value. Note that unlike round(3), ceil(3), etc., the return type of these functions differs from that of their arguments.

ERRORS

EDOM
The magnitude of x is too large and (math_errhandling & MATH_ERRNO) is non-zero.

CONFORMING TO

C99.

SEE ALSO

ceil(3), floor(3), lrint(3), nearbyint(3), rint(3), round(3)


round(3)

ROUND

Section: Linux Programmer's Manual (3)
Updated: 2001-05-31 Return to Main Contents

NAME

round, roundf, roundl - round to nearest integer, away from zero

SYNOPSIS

#include <math.h>

double round(double x);

float roundf(float x);

long double roundl(long double x);

Compile with -std=c99; link with -lm.

DESCRIPTION

These functions round x to the nearest integer, but round halfway cases away from zero (regardless of the current rounding direction), instead of to the nearest even integer like rint(3).

RETURN VALUE

The rounded integer value. If x is integral or infinite, x itself is returned.

ERRORS

No errors other than EDOM and ERANGE can occur. If x is NaN, then NaN is returned and errno may be set to EDOM.

CONFORMING TO

C99.

NOTES

POSIX.1-2001 contains text about overflow (which might set errno to ERANGE, or raise an exception). In practice, the result cannot overflow on any current machine, so this error-handling stuff is just nonsense. (More precisely, overflow can happen only when the maximum value of the exponent is smaller than the number of mantissa bits. For the IEEE-754 standard 32-bit and 64-bit floating point numbers the maximum value of the exponent is 128 (resp. 1024), and the number of mantissa bits is 24 (resp. 53).)

SEE ALSO

ceil(3), floor(3), lround(3), nearbyint(3), rint(3), trunc(3)


trunc(3)

TRUNC

Section: Linux Programmer's Manual (3)
Updated: 2001-05-31 Return to Main Contents

NAME

trunc, truncf, truncl - round to integer, towards zero

SYNOPSIS

#include <math.h>

double trunc(double x);

float truncf(float x);

long double truncl(long double x);

Compile with -std=c99; link with -lm.

DESCRIPTION

These functions round x to the nearest integer not larger in absolute value.

RETURN VALUE

The rounded integer value. If x is integral, infinite or NaN, x itself is returned.

ERRORS

None.

CONFORMING TO

C99.

SEE ALSO

ceil(3), floor(3), lrint(3), nearbyint(3), rint(3), round(3)


ceilf (3)

 Continue to this page.


ceill (3)

 Continue to this page.


floorf (3)

 Continue to this page.


floorl (3)

 Continue to this page.


llrint (3)

 Continue to this page.


llrintf (3)

 Continue to this page.


llrintl (3)

 Continue to this page.


lrintl (3)

 Continue to this page.


lrintf (3)

 Continue to this page.


llround (3)

 Continue to this page.


llroundf (3)

 Continue to this page.


llroundl (3)

 Continue to this page.


lroundl (3)

 Continue to this page.


lroundf (3)

 Continue to this page.


nearbyint (3)

 Continue to this page.


nearbyintf (3)

 Continue to this page.


nearbyintl (3)

 Continue to this page.


rintf (3)

 Continue to this page.


rintl (3)

 Continue to this page.


roundf (3)

 Continue to this page.


roundl (3)

 Continue to this page.


truncf (3)

 Continue to this page.


truncl (3)

 Continue to this page.


fabsf (3)

 Continue to this page.


fabsl (3)

 Continue to this page.


strtof (3)

 Continue to this page.


strtold (3)

 Continue to this page.


lldiv (3)

 Continue to this page.


getdelim (3)

 Continue to this page.


endrpcent (3)

 Continue to this page.


setlogmask(3)

SETLOGMASK

Section: Linux Programmer's Manual (3)
Updated: 2001-10-05 Return to Main Contents

NAME

setlogmask - set log priority mask

SYNOPSIS

#include <syslog.h>

int setlogmask(int mask);

DESCRIPTION

A process has a log priority mask that determines which calls to syslog(3) may be logged. All other calls will be ignored. Logging is enabled for the priorities that have the corresponding bit set in mask. The initial mask is such that logging is enabled for all priorities.

The setlogmask() function sets this logmask for the current process, and returns the previous mask. If the mask argument is 0, the current logmask is not modified.

The eight priorities are LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO and LOG_DEBUG. The bit corresponding to a priority p is LOG_MASK(p). Some systems also provide a macro LOG_UPTO(p) for the mask of all priorities in the above list up to and including p.

RETURN VALUE

This function returns the previous log priority mask.

ERRORS

None.

CONFORMING TO

POSIX.1-2001. Note that the description in POSIX.1-2001 is flawed.

SEE ALSO

closelog(3), openlog(3), syslog(3)


getrpcbyname (3)

 Continue to this page.


getline(3)

GETLINE

Section: Linux Programmer's Manual (3)
Updated: 2006-05-17 Return to Main Contents

NAME

getline, getdelim - delimited string input

SYNOPSIS

#define _GNU_SOURCE
#include <stdio.h>

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);

DESCRIPTION

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary. In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively.

getdelim() works like getline(), except a line delimiter other than newline can be specified as the delimiter argument. As with getline(), a delimiter character is not added if one was not present in the input before end of file was reached.

RETURN VALUE

On success, getline() and getdelim() return the number of characters read, including the delimiter character, but not including the terminating null byte. This value can be used to handle embedded null bytes in the line read.

Both functions return -1 on failure to read a line (including end of file condition).

ERRORS

EINVAL
Bad parameters (n or lineptr is NULL, or stream is not valid).

CONFORMING TO

Both getline() and getdelim() are GNU extensions. They are available since libc 4.6.27.

EXAMPLE

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);
    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu :\n", read);
        printf("%s", line);
    }
    if (line)
        free(line);
    return EXIT_SUCCESS;
}

SEE ALSO

read(2), fgets(3), fopen(3), fread(3), gets(3), scanf(3), feature_test_macros(7)


getrpcbynumber (3)

 Continue to this page.


endutxent (3)

 Continue to this page.


setrpcent (3)

 Continue to this page.


valloc (3)

 Continue to this page.


xdr_accepted_reply (3)

 Continue to this page.


getutxent (3)

 Continue to this page.


xdr_array (3)

 Continue to this page.


memalign (3)

 Continue to this page.


xdr_authunix_parms (3)

 Continue to this page.


getutxid (3)

 Continue to this page.


xdr_bool (3)

 Continue to this page.


getutxline (3)

 Continue to this page.


xdr_bytes (3)

 Continue to this page.


mkdtemp(3)

MKDTEMP

Section: Linux Programmer's Manual (3)
Updated: 2001-10-07 Return to Main Contents

NAME

mkdtemp - create a unique temporary directory

SYNOPSIS

#include <stdlib.h>

char *mkdtemp(char *template);

DESCRIPTION

The mkdtemp() function generates a uniquely-named temporary directory from template. The last six characters of template must be XXXXXX and these are replaced with a string that makes the directory name unique. The directory is then created with permissions 0700. Since it will be modified, template must not be a string constant, but should be declared as a character array.

RETURN VALUE

The mkdtemp() function returns a pointer to the modified template string on success, and NULL on failure, in which case errno is set appropriately.

ERRORS

EINVAL
The last six characters of template were not XXXXXX. Now template is unchanged.

Also see mkdir(2) for other possible values for errno.

VERSIONS

Available since glibc 2.1.91.

CONFORMING TO

This function is present on the BSDs.

SEE ALSO

mkdir(2), mkstemp(3), mktemp(3), tempnam(3), tmpfile(3), tmpnam(3)


xdr_callhdr (3)

 Continue to this page.


posix_memalign(3)

POSIX_MEMALIGN

Section: Linux Programmer's Manual (3)
Updated: 2003-08-22 Return to Main Contents

NAME

posix_memalign, memalign, valloc - Allocate aligned memory

SYNOPSIS

#define _XOPEN_SOURCE 600
#include <stdlib.h>

int posix_memalign(void **memptr, size_t alignment, size_t size);

#include <malloc.h>

void *valloc(size_t size);
void *memalign(size_t boundary, size_t size);

DESCRIPTION

The function posix_memalign() allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated memory will be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *).

The obsolete function memalign() allocates size bytes and returns a pointer to the allocated memory. The memory address will be a multiple of boundary, which must be a power of two.

The obsolete function valloc() allocates size bytes and returns a pointer to the allocated memory. The memory address will be a multiple of the page size. It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).

For all three routines, the memory is not zeroed.

RETURN VALUE

memalign() and valloc() return the pointer to the allocated memory, or NULL if the request fails.

posix_memalign() returns zero on success, or one of the error values listed in the next section on failure. Note that errno is not set.

ERRORS

EINVAL
The alignment parameter was not a power of two, or was not a multiple of sizeof(void *).
ENOMEM
There was insufficient memory to fulfill the allocation request.

VERSIONS

The functions memalign() and valloc() have been available in all Linux libc libraries. The function posix_memalign() is available since glibc 2.1.91.

CONFORMING TO

The function valloc() appeared in 3.0BSD. It is documented as being obsolete in 4.3BSD, and as legacy in SUSv2. It does not appear in POSIX.1-2001. The function memalign() appears in SunOS 4.1.3 but not in 4.4BSD. The function posix_memalign() comes from POSIX.1d.

Headers

Everybody agrees that posix_memalign() is declared in <stdlib.h>. In order to declare it, glibc needs _GNU_SOURCE defined, or _XOPEN_SOURCE defined to a value not less than 600.

On some systems memalign() is declared in <stdlib.h> instead of <malloc.h>.

According to SUSv2, valloc() is declared in <stdlib.h>. Libc4,5 and glibc declare it in <malloc.h> and perhaps also in <stdlib.h> (namely, if _GNU_SOURCE is defined, or _BSD_SOURCE is defined, or, for glibc, if _XOPEN_SOURCE_EXTENDED is defined, or, equivalently, _XOPEN_SOURCE is defined to a value not less than 500).

NOTES

On many systems there are alignment restrictions, for example, on buffers used for direct block device I/O. POSIX specifies the pathconf(path,_PC_REC_XFER_ALIGN) call that tells what alignment is needed. Now one can use posix_memalign() to satisfy this requirement.

posix_memalign() verifies that alignment matches the requirements detailed above. memalign() may not check that the boundary parameter is correct.

POSIX requires that memory obtained from posix_memalign() can be freed using free(3). Some systems provide no way to reclaim memory allocated with memalign() or valloc() (because one can only pass to free(3) a pointer gotten from malloc(3), while, for example, memalign() would call malloc(3) and then align the obtained value). GNU libc allows memory obtained from any of these three routines to be reclaimed with free(3).

GNU libc malloc(3) always returns 8-byte aligned memory addresses, so these routines are only needed if you require larger alignment values.

SEE ALSO

brk(2), getpagesize(2), free(3), malloc(3), feature_test_macros(7)


xdr_callmsg (3)

 Continue to this page.


pututxline (3)

 Continue to this page.


xdr_char (3)

 Continue to this page.


flockfile(3)

LOCKFILE

Section: Linux Programmer's Manual (3)
Updated: 2001-10-18 Return to Main Contents

NAME

flockfile, ftrylockfile, funlockfile - lock FILE for stdio

SYNOPSIS

#include <stdio.h>

void flockfile(FILE *filehandle);

int ftrylockfile(FILE *filehandle);

void funlockfile(FILE *filehandle);

DESCRIPTION

The stdio functions are thread-safe. This is achieved by assigning to each FILE object a lockcount and (if the lockcount is non-zero) an owning thread. For each library call, these functions wait until the FILE object is no longer locked by a different thread, then lock it, do the requested I/O, and unlock the object again.

(Note: this locking has nothing to do with the file locking done by functions like flock(2) and lockf(3).)

All this is invisible to the C-programmer, but there may be two reasons to wish for more detailed control. On the one hand, maybe a series of I/O actions by one thread belongs together, and should not be interrupted by the I/O of some other thread. On the other hand, maybe the locking overhead should be avoided for greater efficiency.

To this end, a thread can explicitly lock the FILE object, then do its series of I/O actions, then unlock. This prevents other threads from coming in between. If the reason for doing this was to achieve greater efficiency, one does the I/O with the non-locking versions of the stdio functions: with getc_unlocked(3) and putc_unlocked(3) instead of getc(3) and putc(3).

The flockfile() function waits for *filehandle to be no longer locked by a different thread, then makes the current thread owner of *filehandle, and increments the lockcount.

The funlockfile() function decrements the lock count.

The ftrylockfile() function is a non-blocking version of flockfile(). It does nothing in case some other thread owns *filehandle, and it obtains ownership and increments the lockcount otherwise.

RETURN VALUE

The ftrylockfile() function returns zero for success (the lock was obtained), and non-zero for failure.

ERRORS

None.

CONFORMING TO

POSIX.1-2001.

AVAILABILITY

These functions are available when _POSIX_THREAD_SAFE_FUNCTIONS is defined. They are in libc since libc 5.1.1 and in glibc since glibc 2.0.

SEE ALSO

unlocked_stdio(3)


xdr_destroy (3)

 Continue to this page.


setutxent (3)

 Continue to this page.


xdr_double (3)

 Continue to this page.


strerror_r (3)

 Continue to this page.


xdr_enum (3)

 Continue to this page.


clearenv(3)

CLEARENV

Section: Linux Programmer's Manual (3)
Updated: 2001-10-17 Return to Main Contents

NAME

clearenv - clear the environment

SYNOPSIS

#include <stdlib.h>

int clearenv(void);

DESCRIPTION

The clearenv() function clears the environment of all name-value pairs and sets the value of the external variable environ to NULL.

RETURN VALUE

The clearenv() function returns zero on success, and a non-zero value on failure.

VERSIONS

Not in libc4, libc5. In glibc since glibc 2.0.

CONFORMING TO

Various Unix variants (DG/UX, HP-UX, QNX, ...). POSIX.9 (bindings for FORTRAN77). POSIX.1-1996 did not accept clearenv() and putenv(3), but changed its mind and scheduled these functions for some later issue of this standard (cf. B.4.6.1). However, POSIX.1-2001 only adds putenv(3), and rejected clearenv().

NOTES

Used in security-conscious applications. If it is unavailable the assignment
    environ = NULL;
will probably do.

The DG/UX and Tru64 man pages write: If environ has been modified by anything other than the putenv(3), getenv(3), or clearenv() functions, then clearenv() will return an error and the process environment will remain unchanged.

SEE ALSO

getenv(3), putenv(3), setenv(3), unsetenv(3), environ(7)


xdr_float (3)

 Continue to this page.


xdr_free (3)

 Continue to this page.


feof_unlocked (3)

 Continue to this page.


xdr_getpos (3)

 Continue to this page.


strdupa (3)

 Continue to this page.


xdr_inline (3)

 Continue to this page.


xdr_int (3)

 Continue to this page.


strndup (3)

 Continue to this page.


xdr_long (3)

 Continue to this page.


unlocked_stdio(3)

UNLOCKED_STDIO

Section: Linux Programmer's Manual (3)
Updated: 2001-10-18 Return to Main Contents

NAME

getc_unlocked, getchar_unlocked, putc_unlocked, putchar_unlocked, - non-locking stdio functions

SYNOPSIS

#include <stdio.h>

int getc_unlocked(FILE *stream);
int getchar_unlocked(void);
int putc_unlocked(int c, FILE *stream);
int putchar_unlocked(int c);

#define _BSD_SOURCE /* or _SVID_SOURCE or _GNU_SOURCE */
#include <stdio.h>

void clearerr_unlocked(FILE *stream);
int feof_unlocked(FILE *stream);
int ferror_unlocked(FILE *stream);
int fileno_unlocked(FILE *stream);
int fflush_unlocked(FILE *stream);
int fgetc_unlocked(FILE *stream);
int fputc_unlocked(int c, FILE *stream);
size_t fread_unlocked(void *ptr, size_t size, size_t n,
        FILE *stream);
size_t fwrite_unlocked(const void *ptr, size_t size, size_t n,
        FILE *stream);

#define _GNU_SOURCE
#include <stdio.h>

char *fgets_unlocked(char *s, int n, FILE *stream);
int fputs_unlocked(const char *s, FILE *stream);

#define _GNU_SOURCE
#include <wchar.h>

wint_t getwc_unlocked(FILE *stream);
wint_t getwchar_unlocked(void);
wint_t fgetwc_unlocked(FILE *stream);
wint_t fputwc_unlocked(wchar_t wc, FILE *stream);
wint_t putwc_unlocked(wchar_t wc, FILE *stream);
wint_t putwchar_unlocked(wchar_t wc);
wchar_t *fgetws_unlocked(wchar_t *ws, int n, FILE *stream);
int fputws_unlocked(const wchar_t *ws, FILE *stream);

DESCRIPTION

Each of these functions has the same behavior as its counterpart without the `_unlocked' suffix, except that they do not use locking (they do not set locks themselves, and do not test for the presence of locks set by others) and hence are thread-unsafe. See flockfile(3).

CONFORMING TO

The four functions getc_unlocked(), getchar_unlocked(), putc_unlocked(), putchar_unlocked() are in POSIX.1-2001.

The nonstandard *_unlocked() variants occur on a few Unix systems, and are available in recent glibc. They should probably not be used.

SEE ALSO

flockfile(3), stdio(3), feature_test_macros(7)


xdr_opaque (3)

 Continue to this page.


strndupa (3)

 Continue to this page.


xdr_opaque_auth (3)

 Continue to this page.


xdr_pmap (3)

 Continue to this page.


fgetc_unlocked (3)

 Continue to this page.


xdr_pmaplist (3)

 Continue to this page.


fgets_unlocked (3)

 Continue to this page.


xdr_pointer (3)

 Continue to this page.


ftrylockfile (3)

 Continue to this page.


xdr_reference (3)

 Continue to this page.


xdr_rejected_reply (3)

 Continue to this page.


fputc_unlocked (3)

 Continue to this page.


xdr_replymsg (3)

 Continue to this page.


fputs_unlocked (3)

 Continue to this page.


xdr_setpos (3)

 Continue to this page.


xdr_short (3)

 Continue to this page.


xdr_string (3)

 Continue to this page.


funlockfile (3)

 Continue to this page.


fread_unlocked (3)

 Continue to this page.


xdr_u_char (3)

 Continue to this page.


xdr_u_int (3)

 Continue to this page.


getc_unlocked (3)

 Continue to this page.


xdr_u_long (3)

 Continue to this page.


xdr_u_short (3)

 Continue to this page.


xdr_union (3)

 Continue to this page.


xdr_vector (3)

 Continue to this page.


xdr_void (3)

 Continue to this page.


clearerr_unlocked (3)

 Continue to this page.


xdr_wrapstring (3)

 Continue to this page.


xdrmem_create (3)

 Continue to this page.


getwc_unlocked (3)

 Continue to this page.


xdrrec_create (3)

 Continue to this page.


xdrrec_endofrecord (3)

 Continue to this page.


xdrrec_eof (3)

 Continue to this page.


ferror_unlocked (3)

 Continue to this page.


xdrrec_skiprecord (3)

 Continue to this page.


xdrstdio_create (3)

 Continue to this page.


putc_unlocked (3)

 Continue to this page.


xprt_register (3)

 Continue to this page.


fflush_unlocked (3)

 Continue to this page.


xprt_unregister (3)

 Continue to this page.


fgetwc_unlocked (3)

 Continue to this page.


fgetws_unlocked (3)

 Continue to this page.


fileno_unlocked (3)

 Continue to this page.


fputwc_unlocked (3)

 Continue to this page.


fputws_unlocked (3)

 Continue to this page.


fwrite_unlocked (3)

 Continue to this page.


getchar_unlocked (3)

 Continue to this page.


getwchar_unlocked (3)

 Continue to this page.


putchar_unlocked (3)

 Continue to this page.


putwc_unlocked (3)

 Continue to this page.


putwchar_unlocked (3)

 Continue to this page.


ftello (3)

 Continue to this page.


fseeko(3)

FSEEKO

Section: Linux Programmer's Manual (3)
Updated: 2001-11-05 Return to Main Contents

NAME

fseeko, ftello - seek to or report file position

SYNOPSIS

#include <stdio.h>

int fseeko(FILE *stream, off_t offset, int whence);

off_t ftello(FILE *stream);
.fi

DESCRIPTION

The fseeko() and ftello() functions are identical to fseek(3) and ftell(3) (see fseek(3)), respectively, except that the offset argument of fseeko() and the return value of ftello() is of type off_t instead of long.

On many architectures both off_t and long are 32-bit types, but compilation with

#define _FILE_OFFSET_BITS 64
will turn off_t into a 64-bit type.

RETURN VALUE

On successful completion, fseeko() returns 0, while ftello() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error.

ERRORS

See the ERRORS in fseek(3).

CONFORMING TO

SUSv2, POSIX.1-2001.

NOTES

These functions are found on System V-like systems. They are not present in libc4, libc5, glibc 2.0 but are available since glibc 2.1.

SEE ALSO

fseek(3)


makecontext(3)

MAKECONTEXT

Section: Linux Programmer's Manual (3)
Updated: 2001-11-15 Return to Main Contents

NAME

makecontext, swapcontext - manipulate user context

SYNOPSIS

#include <ucontext.h>

void makecontext(ucontext_t *ucp, void *func(),

int argc, ...);
int swapcontext(ucontext_t *oucp, ucontext_t *ucp);

DESCRIPTION

In a System V-like environment, one has the type ucontext_t defined in <ucontext.h> and the four functions getcontext(2), setcontext(2), makecontext() and swapcontext() that allow user-level context switching between multiple threads of control within a process.

For the type and the first two functions, see getcontext(2).

The makecontext() function modifies the context pointed to by ucp (which was obtained from a call to getcontext(2)). Before invoking makecontext(), the caller must allocate a new stack for this context and assign its address to ucp->uc_stack, and define a successor context and assign its address to ucp->uc_link.

When this context is later activated (using setcontext(2) or swapcontext()) the function func is called, and passed the series of integer (int) arguments that follow argc; the caller must specify the number of these arguments in argc. When this function returns, the successor context is activated. If the successor context pointer is NULL, the thread exits.

The swapcontext() function saves the current context in the structure pointed to by oucp, and then activates the context pointed to by ucp.

RETURN VALUE

When successful, swapcontext() does not return. (But we may return later, in case oucp is activated, in which case it looks like swapcontext() returns 0.) On error, swapcontext() returns -1 and sets errno appropriately.

ERRORS

ENOMEM
Insufficient stack space left.

CONFORMING TO

SUSv2, POSIX.1-2001.

NOTES

The interpretation of ucp->uc_stack is just as in sigaltstack(2), namely, this struct contains the start and length of a memory area to be used as the stack, regardless of the direction of growth of the stack. Thus, it is not necessary for the user program to worry about this direction.

EXAMPLE

The example program below demonstrates the use of getcontext(2), makecontext(), and swapcontext(). Running the program produces the following output:

$ ./a.out
main: swapcontext(&uctx_main, &uctx_func2)
func2: started
func2: swapcontext(&uctx_func2, &uctx_func1)
func1: started
func1: swapcontext(&uctx_func1, &uctx_func2)
func2: returning
func1: returning
main: exiting

#include <ucontext.h>
#include <stdio.h>
#include <stdlib.h>

static ucontext_t uctx_main, uctx_func1, uctx_func2;

#define die(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)

static void
func1(void)
{
    printf("func1: started\n");
    printf("func1: swapcontext(&uctx_func1, &uctx_func2)\n");
    if (swapcontext(&uctx_func1, &uctx_func2) == -1)
        die("swapcontext");
    printf("func1: returning\n");
}

static void
func2(void)
{
    printf("func2: started\n");
    printf("func2: swapcontext(&uctx_func2, &uctx_func1)\n");
    if (swapcontext(&uctx_func2, &uctx_func1) == -1)
        die("swapcontext");
    printf("func2: returning\n");
}

int
main(int argc, char *argv[])
{
    char func1_stack[16384];
    char func2_stack[16384];

    if (getcontext(&uctx_func1) == -1)
        die("getcontext");
    uctx_func1.uc_stack.ss_sp = func1_stack;
    uctx_func1.uc_stack.ss_size = sizeof(func1_stack);
    uctx_func1.uc_link = &uctx_main;
    makecontext(&uctx_func1, func1, 0);

    if (getcontext(&uctx_func2) == -1)
        die("getcontext");
    uctx_func2.uc_stack.ss_sp = func2_stack;
    uctx_func2.uc_stack.ss_size = sizeof(func2_stack);
    /* Successor context is f1(), unless argc > 1 */
    uctx_func2.uc_link = (argc > 1) ? NULL : &uctx_func1;
    makecontext(&uctx_func2, func2, 0);

    printf("main: swapcontext(&uctx_main, &uctx_func2)\n");
    if (swapcontext(&uctx_main, &uctx_func2) == -1)
        die("swapcontext");

    printf("main: exiting\n");
    exit(EXIT_SUCCESS);
}

SEE ALSO

getcontext(2), sigaction(2), sigaltstack(2), sigprocmask(2), sigsetjmp(3)


swapcontext (3)

 Continue to this page.


klogctl (3)

 Continue to this page.


dysize(3)

DYSIZE

Section: Linux Programmer's Manual (3)
Updated: 2001-11-12 Return to Main Contents

NAME

dysize - get number of days for a given year

SYNOPSIS

#define _BSD_SOURCE /* or: #define _SVID_SOURCE */
#include <time.h>

int dysize(int year);

DESCRIPTION

The function returns 365 for a normal year and 366 for a leap year. The calculation for leap year is based on:

(year) %4 == 0 && ((year) %100 != 0 || (year) %400 == 0)

The formula is defined in the macro __isleap(year) also found in <time.h>.

CONFORMING TO

This function occurs in SunOS 4.x.

NOTES

This is a compatibility function only. Don't use it in new programs. The SCO version of this function had a year-2000 problem.

SEE ALSO

strftime(3), feature_test_macros(7)


CMSG_ALIGN (3)

 Continue to this page.


CMSG_FIRSTHDR (3)

 Continue to this page.


CMSG_NXTHDR (3)

 Continue to this page.


CMSG_SPACE (3)

 Continue to this page.


hstrerror (3)

 Continue to this page.


fpurge(3)

FPURGE

Section: Linux Programmer's Manual (3)
Updated: 2001-12-15 Return to Main Contents

NAME

fpurge, __fpurge - purge a stream

SYNOPSIS

/* unsupported */
#include <stdio.h>

int fpurge(FILE *stream);

/* supported */
#include <stdio.h>

#include <stdio_ext.h>

void  __fpurge(FILE *stream);

DESCRIPTION

The function fpurge() clears the buffers of the given stream. For output streams this discards any unwritten output. For input streams this discards any input read from the underlying object but not yet obtained via getc(3); this includes any text pushed back via ungetc(3). See also fflush(3).

The function __fpurge() does precisely the same, but without returning a value.

RETURN VALUE

Upon successful completion fpurge() returns 0. On error, it returns -1 and sets errno appropriately.

ERRORS

EBADF
stream is not an open stream.

CONFORMING TO

These functions are nonstandard and not portable. The function fpurge() was introduced in 4.4BSD and is not available under Linux. The function __fpurge() was introduced in Solaris, and is present in glibc 2.1.95 and later.

NOTES

Usually it is a mistake to want to discard input buffers.

SEE ALSO

fflush(3), setbuf(3), stdio_ext(3)


__fpurge (3)

 Continue to this page.


__fbufsize (3)

 Continue to this page.


__fpending (3)

 Continue to this page.


stdio_ext(3)

STDIO_EXT

Section: Linux Programmer's Manual (3)
Updated: 2001-12-16 Return to Main Contents

NAME

__fbufsize, __flbf, __fpending, __fpurge, __freadable, __freading, __fsetlocking, __fwritable, __fwriting, _flushlbf - interfaces to stdio FILE structure

SYNOPSIS

#include <stdio.h>
#include <stdio_ext.h>

size_t __fbufsize(FILE *stream);
size_t __fpending(FILE *stream);
int __flbf(FILE *stream);
int __freadable(FILE *stream);
int __fwritable(FILE *stream);
int __freading(FILE *stream);
int __fwriting(FILE *stream);
int __fsetlocking(FILE *stream, int type);
void _flushlbf(void);
void __fpurge(FILE *stream);

DESCRIPTION

Solaris introduced routines to allow portable access to the internals of the FILE structure, and glibc also implemented these.

The __fbufsize() function returns the size of the buffer currently used by the given stream.

The __fpending() function returns the number of bytes in the output buffer. For wide-oriented streams the unit is wide characters. This function is undefined on buffers in reading mode, or opened read-only.

The __flbf() function returns a non-zero value if the stream is line-buffered, and zero otherwise.

The __freadable() function returns a non-zero value if the stream allows reading, and zero otherwise.

The __fwritable() function returns a non-zero value if the stream allows writing, and zero otherwise.

The __freading() function returns a non-zero value if the stream is read-only, or if the last operation on the stream was a read operation, and zero otherwise.

The __fwriting() function returns a non-zero value if the stream is write-only (or append-only), or if the last operation on the stream was a write operation, and zero otherwise.

The __fsetlocking() function can be used to select the desired type of locking on the stream. It returns the current type. The type parameter can take the following three values:

FSETLOCKING_INTERNAL
Perform implicit locking around every operation on the given stream (except for the *_unlocked ones). This is the default.
FSETLOCKING_BYCALLER
The caller will take care of the locking (possibly using flockfile(3) in case there is more than one thread), and the stdio routines will not do locking until the state is reset to FSETLOCKING_INTERNAL.
FSETLOCKING_QUERY
Don't change the type of locking. (Only return it.)

The _flushlbf() function flushes all line-buffered streams. (Presumably so that output to a terminal is forced out, say before reading keyboard input.)

The __fpurge() function discards the contents of the stream's buffer.

SEE ALSO

flockfile(3), fpurge(3)


__flbf (3)

 Continue to this page.


__freading (3)

 Continue to this page.


__fwritable (3)

 Continue to this page.


__freadable (3)

 Continue to this page.


__fwriting (3)

 Continue to this page.


__fsetlocking (3)

 Continue to this page.


_flushlbf (3)

 Continue to this page.


dprintf(3)

DPRINTF

Section: Linux Programmer's Manual (3)
Updated: 2001-12-18 Return to Main Contents

NAME

dprintf, vdprintf - print to a file descriptor

SYNOPSIS

#define _GNU_SOURCE
#include <stdio.h>

int dprintf(int fd, const char *format, ...);

int vdprintf(int fd, const char *format, va_list ap);

DESCRIPTION

The functions dprintf() and vdprintf() (as found in the glibc2 library) are exact analogs of fprintf(3) and vfprintf(3), except that they output to a file descriptor fd instead of to a given stream.

CONFORMING TO

These functions are GNU extensions.

NOTES

These functions are GNU extensions, not in C or POSIX. Clearly, the names were badly chosen. Many systems (like MacOS) have incompatible functions called dprintf(), usually some debugging version of printf(3), perhaps with a prototype like

void dprintf(int level, const char *format, ...);

where the first parameter is a debugging level (and output is to stderr). Moreover, dprintf() (or DPRINTF) is also a popular macro name for a debugging printf. So, probably, it is better to avoid this function in programs intended to be portable.

A better name would have been fdprintf().

SEE ALSO

printf(3), feature_test_macros(7)


vdprintf (3)

 Continue to this page.


asprintf(3)

ASPRINTF

Section: Linux Programmer's Manual (3)
Updated: 2001-12-18 Return to Main Contents

NAME

asprintf, vasprintf - print to allocated string

SYNOPSIS

#define _GNU_SOURCE
#include <stdio.h>

int asprintf(char **strp, const char *fmt, ...);

int vasprintf(char **strp, const char *fmt, va_list ap);

DESCRIPTION

The functions asprintf() and vasprintf() are analogs of sprintf(3) and vsprintf(3), except that they allocate a string large enough to hold the output including the terminating null byte, and return a pointer to it via the first parameter. This pointer should be passed to free(3) to release the allocated storage when it is no longer needed.

RETURN VALUE

When successful, these functions return the number of bytes printed, just like sprintf(3). If memory allocation wasn't possible, or some other error occurs, these functions will return -1, and the contents of strp is undefined.

CONFORMING TO

These functions are GNU extensions, not in C or POSIX. They are also available under *BSD. The FreeBSD implementation sets strp to NULL on error.

SEE ALSO

free(3), malloc(3), printf(3), feature_test_macros(7)


vasprintf (3)

 Continue to this page.


strverscmp(3)

STRVERSCMP

Section: Linux Programmer's Manual (3)
Updated: 2001-12-19 Return to Main Contents

NAME

strverscmp - compare two version strings

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

int strverscmp(const char *s1, const char *s2);

DESCRIPTION

Often one has files jan1, jan2, ..., jan9, jan10, ... and it feels wrong when ls orders them jan1, jan10, ..., jan2, ..., jan9. In order to rectify this, GNU introduced the -v option to ls(1), which is implemented using versionsort(3), which again uses strverscmp().

Thus, the task of strverscmp() is to compare two strings and find the "right" order, while strcmp(3) only finds the lexicographic order. This function does not use the locale category LC_COLLATE, so is meant mostly for situations where the strings are expected to be in ASCII.

What this function does is the following. If both strings are equal, return 0. Otherwise find the position between two bytes with the property that before it both strings are equal, while directly after it there is a difference. Find the largest consecutive digit strings containing (or starting at, or ending at) this position. If one or both of these is empty, then return what strcmp(3) would have returned (numerical ordering of byte values). Otherwise, compare both digit strings numerically, where digit strings with one or more leading zeroes are interpreted as if they have a decimal point in front (so that in particular digit strings with more leading zeroes come before digit strings with fewer leading zeroes). Thus, the ordering is 000, 00, 01, 010, 09, 0, 1, 9, 10.

RETURN VALUE

The strverscmp() function returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be earlier than, equal to, or later than s2.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

rename(1), strcasecmp(3), strcmp(3), strcoll(3), feature_test_macros(7)


versionsort (3)

 Continue to this page.


hsearch_r (3)

 Continue to this page.


hcreate_r (3)

 Continue to this page.


hdestroy_r (3)

 Continue to this page.


getdate(3)

GETDATE

Section: Linux Programmer's Manual (3)
Updated: 2001-12-26 Return to Main Contents

NAME

getdate - convert a string to struct tm

SYNOPSIS

#define _XOPEN_SOURCE
#define _XOPEN_SOURCE_EXTENDED
#include <time.h>

struct tm *getdate(const char *string);

extern int getdate_err;

#define _GNU_SOURCE
#include <time.h>

int getdate_r (const char *string, struct tm *res);

DESCRIPTION

The function getdate() converts a string pointed to by string into the tm structure that it returns. This tm structure may be found in static storage, so that it will be overwritten by the next call.

In contrast to strptime(3), (which has a format argument), getdate() uses the formats found in the file of which the full pathname is given in the environment variable DATEMSK. The first line in the file that matches the given input string is used for the conversion.

The matching is done case insensitively. Superfluous whitespace, either in the pattern or in the string to be converted, is ignored.

The conversion specifications that a pattern can contain are those given for strptime(3). One more conversion specification is accepted:

%Z
Timezone name.

When %Z is given, the value to be returned is initialized to the broken-down time corresponding to the current time in the given time zone. Otherwise, it is initialized to the broken-down time corresponding to the current local time.

When only the weekday is given, the day is taken to be the first such day on or after today.

When only the month is given (and no year), the month is taken to be the first such month equal to or after the current month. If no day is given, it is the first day of the month.

When no hour, minute and second are given, the current hour, minute and second are taken.

If no date is given, but we know the hour, then that hour is taken to be the first such hour equal to or after the current hour.

RETURN VALUE

When successful, this function returns a pointer to a struct tm. Otherwise, it returns NULL and sets the global variable getdate_err. Changes to errno are unspecified. The following values for getdate_err are defined:
1
The DATEMSK environment variable is null or undefined.
2
The template file cannot be opened for reading.
3
Failed to get file status information.
4
The template file is not a regular file.
5
An error is encountered while reading the template file.
6
Memory allocation failed (not enough memory available).
7
There is no line in the file that matches the input.
8
Invalid input specification.

ENVIRONMENT

DATEMSK
File containing format patterns.
TZ, LC_TIME
Variables used by strptime(3).

CONFORMING TO

POSIX.1-2001

NOTES

Since getdate() is not reentrant because of the use of getdate_err and the static buffer to return the result in, glibc provides a thread-safe variant. The functionality is the same. The result is returned in the buffer pointed to by res and in case of an error the return value is non-zero with the same values as given above for getdate_err.

The POSIX.1-2001 specification for strptime(3) contains conversion specifications using the %E or %O modifier, while such specifications are not given for getdate(). The glibc implementation implements getdate() using strptime(3) so that automatically precisely the same conversions are supported by both.

The glibc implementation does not support the %Z conversion specification.

SEE ALSO

time(2), localtime(3), setlocale(3), strftime(3), strptime(3), feature_test_macros(7)


getdate_r (3)

 Continue to this page.


forkpty (3)

 Continue to this page.


login_tty (3)

 Continue to this page.


openpty(3)

OPENPTY

Section: Linux Programmer's Manual (3)
Updated: 2003-07-18 Return to Main Contents

NAME

openpty, login_tty, forkpty - tty utility functions

SYNOPSIS

#include <pty.h>
 /* for openpty and forkpty */

#include <utmp.h>
/* for login_tty */

int openpty(int *amaster, int *aslave, char *name,
            struct termios *termp, struct winsize *winp);

int login_tty(int fd);

pid_t forkpty(int *amaster, char *name, struct termios *termp,
              struct winsize *winp);

Link with -lutil.

DESCRIPTION

The openpty() function finds an available pseudo-terminal and returns file descriptors for the master and slave in amaster and aslave. If name is not NULL, the filename of the slave is returned in name. If termp is not NULL, the terminal parameters of the slave will be set to the values in termp. If winp is not NULL, the window size of the slave will be set to the values in winp.

The login_tty() function prepares for a login on the tty fd (which may be a real tty device, or the slave of a pseudo-terminal as returned by openpty()) by creating a new session, making fd the controlling terminal for the current process, setting fd to be the standard input, output, and error streams of the current process, and closing fd.

The forkpty() function combines openpty(), fork(2), and login_tty() to create a new process operating in a pseudo-terminal. The file descriptor of the master side of the pseudo-terminal is returned in amaster, and the filename of the slave in name if it is not NULL. The termp and winp parameters, if not NULL, will determine the terminal attributes and window size of the slave side of the pseudo-terminal.

RETURN VALUE

If a call to openpty(), login_tty(), or forkpty() is not successful, -1 is returned and errno is set to indicate the error. Otherwise, openpty(), login_tty(), and the child process of forkpty() return 0, and the parent process of forkpty() returns the process ID of the child process.

ERRORS

openpty() will fail if:
ENOENT
There are no available ttys.

login_tty() will fail if ioctl(2) fails to set fd to the controlling terminal of the current process.

forkpty() will fail if either openpty() or fork(2) fails.

CONFORMING TO

These are BSD functions, present in libc5 and glibc2.

NOTES

In versions of glibc before 2.0.92, openpty() returns file descriptors for a BSD pseudo-terminal pair; since glibc 2.0.92, it first attempts to open a Unix 98 pseudo-terminal pair, and falls back to opening a BSD pseudo-terminal pair if that fails.

BUGS

Nobody knows how much space should be reserved for name. So, calling openpty() or forkpty() with non-NULL name may not be secure.

SEE ALSO

fork(2), pty(7)


getloadavg(3)

GETLOADAVG

Section: C Library Functions (3) Return to Main Contents

BSD mandoc
4.3BSD

NAME

getloadavg - get system load averages

SYNOPSIS

Fd #define _BSD_SOURCE Fd #include <stdlib.h> Ft int Fn getloadavg double loadavg[] int nelem

DESCRIPTION

The Fn getloadavg function returns the number of processes in the system run queue averaged over various periods of time. Up to Fa nelem samples are retrieved and assigned to successive elements of Fa loadavg Ns Bq . The system imposes a maximum of 3 samples, representing averages over the last 1, 5, and 15 minutes, respectively.

RETURN VALUE

If the load average was unobtainable, -1 is returned; otherwise, the number of samples actually retrieved is returned.

HISTORY

The Fn getloadavg function appeared in BSD 4.3 Reno

VERSIONS

This function is available in glibc since version 2.2.

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs and Solaris.

SEE ALSO

uptime(1), proc(5), feature_test_macros7


timelocal (3)

 Continue to this page.


timegm(3)

TIMEGM

Section: Linux Programmer's Manual (3)
Updated: 2001-12-26 Return to Main Contents

NAME

timegm, timelocal - inverses for gmtime and localtime

SYNOPSIS

#include <time.h>

time_t timelocal(struct tm *tm);

time_t timegm(struct tm *tm);

DESCRIPTION

The functions timelocal() and timegm() are the inverses to localtime(3) and gmtime(3).

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs.

NOTES

These functions are GNU extensions. The timelocal() function is equivalent to the POSIX standard function mktime(3). There is no reason to ever use it.

For a portable version of timegm(), set the TZ environment variable to UTC, call mktime(3) and restore the value of TZ. Something like

#include <time.h>
#include <stdlib.h>

time_t
my_timegm(struct tm *tm)
{
    time_t ret;
    char *tz;

    tz = getenv("TZ");
    setenv("TZ", "", 1);
    tzset();
    ret = mktime(tm);
    if (tz)
        setenv("TZ", tz, 1);
    else
        unsetenv("TZ");
    tzset();
    return ret;
}

SEE ALSO

gmtime(3), localtime(3), mktime(3), tzset(3)


gethostbyname2 (3)

 Continue to this page.


gethostbyname2_r (3)

 Continue to this page.


gethostbyname_r (3)

 Continue to this page.


vsyslog (3)

 Continue to this page.


dirfd(3)

DIRFD

Section: Linux Programmer's Manual (3)
Updated: 2002-01-05 Return to Main Contents

NAME

dirfd - get directory stream file descriptor

SYNOPSIS

#include <sys/types.h>
#include <dirent.h>

int dirfd(DIR *dir);

DESCRIPTION

The function dirfd() returns the file descriptor associated with the directory stream dir.

This descriptor is the one used internally by the directory stream. As a result, it is only useful for functions which do not depend on or alter the file position, such as fstat(2) and fchdir(2). It will be automatically closed when closedir(3) is called.

ERRORS

On error -1 is returned.

CONFORMING TO

This is a BSD extension, present in 4.3BSD-Reno, not in 4.2BSD. It is present in libc5 (since 5.1.2) and in glibc2. This function is under consideration for inclusion in a future version of POSIX.1.

NOTES

The prototype for dirfd() is only available if _BSD_SOURCE or _SVID_SOURCE is defined.

SEE ALSO

open(2), closedir(3), opendir(3), readdir(3), rewinddir(3), scandir(3), seekdir(3), telldir(3)


memrchr (3)

 Continue to this page.


strtoull (3)

 Continue to this page.


strtoll (3)

 Continue to this page.


getfsspec (3)

 Continue to this page.


getfsent(3)

GETFSENT

Section: Linux Programmer's Manual (3)
Updated: 2002-02-28 Return to Main Contents

NAME

getfsent, getfsspec, getfsfile, setfsent, endfsent - handle fstab entries

SYNOPSIS

#include <fstab.h>

void endfsent(void);

struct fstab *getfsent(void);

struct fstab *getfsfile(const char *mount_point);

struct fstab *getfsspec(const char *special_file);

int setfsent(void);

DESCRIPTION

These functions read from the file /etc/fstab. The struct fstab is defined by

struct fstab {
     char *fs_spec;          /* block device name */
     char *fs_file;          /* mount point */
     char *fs_vfstype;       /* filesystem type */
     char *fs_mntops;        /* mount options */
     const char *fs_type;    /* rw/rq/ro/sw/xx option */
     int fs_freq;            /* dump frequency, in days */
     int fs_passno;          /* pass number on parallel dump */
};
Here the field fs_type contains (on a *BSD system) one of the five strings "rw", "rq", "ro", "sw", "xx" (read-write, read-write with quota, read-only, swap, ignore).

The function setfsent() opens the file when required and positions it at the first line.

The function getfsent() parses the next line from the file. (After opening it when required.)

The function endfsent() closes the file when required.

The function getfsspec() searches the file from the start and returns the first entry found for which the fs_spec field matches the special_file argument.

The function getfsfile() searches the file from the start and returns the first entry found for which the fs_file field matches the mount_point argument.

RETURN VALUE

Upon success, the functions getfsent(), getfsfile(), and getfsspec() return a pointer to a struct fstab, while setfsent() returns 1. Upon failure or end-of-file, these functions return NULL and 0, respectively.

CONFORMING TO

These functions are not in POSIX.1-2001. Several operating systems have them, e.g., *BSD, SunOS, Digital Unix, AIX (which also has a getfstype()). HP-UX has functions of the same names, that however use a struct checklist instead of a struct fstab, and calls these functions obsolete, superseded by getmntent(3).

NOTES

These functions are not thread-safe.

Since Linux allows mounting a block special device in several places, and since several devices can have the same mount point, where the last device with a given mount point is the interesting one, while getfsfile() and getfsspec() only return the first occurrence, these two functions are not suitable for use under Linux.

SEE ALSO

getmntent(3), fstab(5)


queue(3)

QUEUE

Section: C Library Functions (3) Return to Main Contents

BSD mandoc
4BSD

NAME

LIST_ENTRY LIST_HEAD LIST_INIT LIST_INSERT_AFTER LIST_INSERT_HEAD LIST_REMOVE TAILQ_ENTRY TAILQ_HEAD TAILQ_INIT TAILQ_INSERT_AFTER TAILQ_INSERT_HEAD TAILQ_INSERT_TAIL TAILQ_REMOVE CIRCLEQ_ENTRY CIRCLEQ_HEAD CIRCLEQ_INIT CIRCLEQ_INSERT_AFTER CIRCLEQ_INSERT_BEFORE CIRCLEQ_INSERT_HEAD CIRCLEQ_INSERT_TAIL CIRCLEQ_REMOVE - implementations of lists, tail queues, and circular queues

SYNOPSIS

Fd #include <sys/queue.h> Fn LIST_ENTRY TYPE Fn LIST_HEAD HEADNAME TYPE Fn LIST_INIT LIST_HEAD *head Fn LIST_INSERT_AFTER LIST_ENTRY *listelm TYPE *elm LIST_ENTRY NAME Fn LIST_INSERT_HEAD LIST_HEAD *head TYPE *elm LIST_ENTRY NAME Fn LIST_REMOVE TYPE *elm LIST_ENTRY NAME Fn TAILQ_ENTRY TYPE Fn TAILQ_HEAD HEADNAME TYPE Fn TAILQ_INIT TAILQ_HEAD *head Fn TAILQ_INSERT_AFTER TAILQ_HEAD *head TYPE *listelm TYPE *elm TAILQ_ENTRY NAME Fn TAILQ_INSERT_HEAD TAILQ_HEAD *head TYPE *elm TAILQ_ENTRY NAME Fn TAILQ_INSERT_TAIL TAILQ_HEAD *head TYPE *elm TAILQ_ENTRY NAME Fn TAILQ_REMOVE TAILQ_HEAD *head TYPE *elm TAILQ_ENTRY NAME Fn CIRCLEQ_ENTRY TYPE Fn CIRCLEQ_HEAD HEADNAME TYPE Fn CIRCLEQ_INIT CIRCLEQ_HEAD *head Fn CIRCLEQ_INSERT_AFTER CIRCLEQ_HEAD *head TYPE *listelm TYPE *elm CIRCLEQ_ENTRY NAME Fn CIRCLEQ_INSERT_BEFORE CIRCLEQ_HEAD *head TYPE *listelm TYPE *elm CIRCLEQ_ENTRY NAME Fn CIRCLEQ_INSERT_HEAD CIRCLEQ_HEAD *head TYPE *elm CIRCLEQ_ENTRY NAME Fn CIRCLEQ_INSERT_TAIL CIRCLEQ_HEAD *head TYPE *elm CIRCLEQ_ENTRY NAME Fn CIRCLEQ_REMOVE CIRCLEQ_HEAD *head TYPE *elm CIRCLEQ_ENTRY NAME

DESCRIPTION

These macros define and operate on three types of data structures: lists, tail queues, and circular queues. All three structures support the following functionality:

  1. Insertion of a new entry at the head of the list.
  2. Insertion of a new entry after any element in the list.
  3. Removal of any entry in the list.
  4. Forward traversal through the list.

Lists are the simplest of the three data structures and support only the above functionality.

Tail queues add the following functionality:

  1. Entries can be added at the end of a list.

However:

  1. All list insertions and removals must specify the head of the list.
  2. Each head entry requires two pointers rather than one.
  3. Code size is about 15% greater and operations run about 20% slower than lists.

Circular queues add the following functionality:

  1. Entries can be added at the end of a list.
  2. Entries can be added before another entry.
  3. They may be traversed backwards, from tail to head.

However:

  1. All list insertions and removals must specify the head of the list.
  2. Each head entry requires two pointers rather than one.
  3. The termination condition for traversal is more complex.
  4. Code size is about 40% greater and operations run about 45% slower than lists.

In the macro definitions, Fa TYPE is the name of a user defined structure, that must contain a field of type LIST_ENTRY TAILQ_ENTRY or CIRCLEQ_ENTRY named Fa NAME . The argument Fa HEADNAME is the name of a user defined structure that must be declared using the macros LIST_HEAD TAILQ_HEAD or CIRCLEQ_HEAD See the examples below for further explanation of how these macros are used.

LISTS

A list is headed by a structure defined by the LIST_HEAD macro. This structure contains a single pointer to the first element on the list. The elements are doubly linked so that an arbitrary element can be removed without traversing the list. New elements can be added to the list after an existing element or at the head of the list. A Fa LIST_HEAD structure is declared as follows:
LIST_HEAD(HEADNAME, TYPE) head;

where Fa HEADNAME is the name of the structure to be defined, and Fa TYPE is the type of the elements to be linked into the list. A pointer to the head of the list can later be declared as:

struct HEADNAME *headp;

(The names head and headp are user selectable.)

The macro LIST_ENTRY declares a structure that connects the elements in the list.

The macro LIST_INIT initializes the list referenced by Fa head .

The macro LIST_INSERT_HEAD inserts the new element Fa elm at the head of the list.

The macro LIST_INSERT_AFTER inserts the new element Fa elm after the element Fa listelm .

The macro LIST_REMOVE removes the element Fa elm from the list.

LIST EXAMPLE

LIST_HEAD(listhead, entry) head;
struct listhead *headp;         /* List head. */
struct entry {
        ...
        LIST_ENTRY(entry) entries;      /* List. */
        ...
} *n1, *n2, *np;

LIST_INIT(&head);                       /* Initialize the list. */

n1 = malloc(sizeof(struct entry));      /* Insert at the head. */
LIST_INSERT_HEAD(&head, n1, entries);

n2 = malloc(sizeof(struct entry));      /* Insert after. */
LIST_INSERT_AFTER(n1, n2, entries);
                                        /* Forward traversal. */
for (np = head.lh_first; np != NULL; np = np->entries.le_next)
        np-> ...

while (head.lh_first != NULL)           /* Delete. */
        LIST_REMOVE(head.lh_first, entries);

TAIL QUEUES

A tail queue is headed by a structure defined by the TAILQ_HEAD macro. This structure contains a pair of pointers, one to the first element in the tail queue and the other to the last element in the tail queue. The elements are doubly linked so that an arbitrary element can be removed without traversing the tail queue. New elements can be added to the tail queue after an existing element, at the head of the tail queue, or at the end of the tail queue. A Fa TAILQ_HEAD structure is declared as follows:
TAILQ_HEAD(HEADNAME, TYPE) head;

where HEADNAME is the name of the structure to be defined, and TYPE is the type of the elements to be linked into the tail queue. A pointer to the head of the tail queue can later be declared as:

struct HEADNAME *headp;

(The names head and headp are user selectable.)

The macro TAILQ_ENTRY declares a structure that connects the elements in the tail queue.

The macro TAILQ_INIT initializes the tail queue referenced by Fa head .

The macro TAILQ_INSERT_HEAD inserts the new element Fa elm at the head of the tail queue.

The macro TAILQ_INSERT_TAIL inserts the new element Fa elm at the end of the tail queue.

The macro TAILQ_INSERT_AFTER inserts the new element Fa elm after the element Fa listelm .

The macro TAILQ_REMOVE removes the element Fa elm from the tail queue.

TAIL QUEUE EXAMPLE

TAILQ_HEAD(tailhead, entry) head;
struct tailhead *headp;         /* Tail queue head. */
struct entry {
        ...
        TAILQ_ENTRY(entry) entries;     /* Tail queue. */
        ...
} *n1, *n2, *np;

TAILQ_INIT(&head);                      /* Initialize the queue. */

n1 = malloc(sizeof(struct entry));      /* Insert at the head. */
TAILQ_INSERT_HEAD(&head, n1, entries);

n1 = malloc(sizeof(struct entry));      /* Insert at the tail. */
TAILQ_INSERT_TAIL(&head, n1, entries);

n2 = malloc(sizeof(struct entry));      /* Insert after. */
TAILQ_INSERT_AFTER(&head, n1, n2, entries);
                                        /* Forward traversal. */
for (np = head.tqh_first; np != NULL; np = np->entries.tqe_next)
        np-> ...
                                        /* Delete. */
while (head.tqh_first != NULL)
        TAILQ_REMOVE(&head, head.tqh_first, entries);

CIRCULAR QUEUES

A circular queue is headed by a structure defined by the CIRCLEQ_HEAD macro. This structure contains a pair of pointers, one to the first element in the circular queue and the other to the last element in the circular queue. The elements are doubly linked so that an arbitrary element can be removed without traversing the queue. New elements can be added to the queue after an existing element, before an existing element, at the head of the queue, or at the end of the queue. A Fa CIRCLEQ_HEAD structure is declared as follows:
CIRCLEQ_HEAD(HEADNAME, TYPE) head;

where HEADNAME is the name of the structure to be defined, and TYPE is the type of the elements to be linked into the circular queue. A pointer to the head of the circular queue can later be declared as:

struct HEADNAME *headp;

(The names head and headp are user selectable.)

The macro CIRCLEQ_ENTRY declares a structure that connects the elements in the circular queue.

The macro CIRCLEQ_INIT initializes the circular queue referenced by Fa head .

The macro CIRCLEQ_INSERT_HEAD inserts the new element Fa elm at the head of the circular queue.

The macro CIRCLEQ_INSERT_TAIL inserts the new element Fa elm at the end of the circular queue.

The macro CIRCLEQ_INSERT_AFTER inserts the new element Fa elm after the element Fa listelm .

The macro CIRCLEQ_INSERT_BEFORE inserts the new element Fa elm before the element Fa listelm .

The macro CIRCLEQ_REMOVE removes the element Fa elm from the circular queue.

CIRCULAR QUEUE EXAMPLE

CIRCLEQ_HEAD(circleq, entry) head;
struct circleq *headp;                  /* Circular queue head. */
struct entry {
        ...
        CIRCLEQ_ENTRY(entry) entries;           /* Circular queue. */
        ...
} *n1, *n2, *np;

CIRCLEQ_INIT(&head);                    /* Initialize the circular queue. */

n1 = malloc(sizeof(struct entry));      /* Insert at the head. */
CIRCLEQ_INSERT_HEAD(&head, n1, entries);

n1 = malloc(sizeof(struct entry));      /* Insert at the tail. */
CIRCLEQ_INSERT_TAIL(&head, n1, entries);

n2 = malloc(sizeof(struct entry));      /* Insert after. */
CIRCLEQ_INSERT_AFTER(&head, n1, n2, entries);

n2 = malloc(sizeof(struct entry));      /* Insert before. */
CIRCLEQ_INSERT_BEFORE(&head, n1, n2, entries);
                                        /* Forward traversal. */
for (np = head.cqh_first; np != (void *)&head; np = np->entries.cqe_next)
        np-> ...
                                        /* Reverse traversal. */
for (np = head.cqh_last; np != (void *)&head; np = np->entries.cqe_prev)
        np-> ...
                                        /* Delete. */
while (head.cqh_first != (void *)&head)
        CIRCLEQ_REMOVE(&head, head.cqh_first, entries);

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs. The queue functions first appeared in BSD 4.4


getfsfile (3)

 Continue to this page.


setfsent (3)

 Continue to this page.


endfsent (3)

 Continue to this page.


err(3)

ERR

Section: C Library Functions (3) Return to Main Contents

BSD mandoc

NAME

err verr errx verrx warn vwarn warnx vwarnx - formatted error messages

SYNOPSIS

Fd #include <err.h> Ft void Fn err int eval const char *fmt ... Ft void Fn errx int eval const char *fmt ... Ft void Fn warn const char *fmt ... Ft void Fn warnx const char *fmt ... Fd #include <stdarg.h> Ft void Fn verr int eval const char *fmt va_list args Ft void Fn verrx int eval const char *fmt va_list args Ft void Fn vwarn const char *fmt va_list args Ft void Fn vwarnx const char *fmt va_list args

DESCRIPTION

The Fn err and Fn warn family of functions display a formatted error message on the standard error output. In all cases, the last component of the program name, a colon character, and a space are output. If the Fa fmt argument is not NULL, the printf(3) -like formatted error message is output. The output is terminated by a newline character.

The Fn err , Fn verr , Fn warn , and Fn vwarn functions append an error message obtained from strerror(3) based on a code or the global variable errno preceded by another colon and space unless the Fa fmt argument is NULL

The Fn err , Fn verr , Fn warn , and Fn vwarn functions use the global variable errno to look up the error message.

The Fn errx and Fn warnx functions do not append an error message.

The Fn err , Fn verr , Fn errx , and Fn verrx functions do not return, but exit with the value of the argument Fa eval .

EXAMPLES

Display the current errno information string and exit:
if ((p = malloc(size)) == NULL)
        err(1, NULL);
if ((fd = open(file_name, O_RDONLY, 0)) == -1)
        err(1, "%s", file_name);

Display an error message and exit:

if (tm.tm_hour < START_TIME)
        errx(1, "too early, wait until %s", start_time_string);

Warn of an error:

if ((fd = open(raw_device, O_RDONLY, 0)) == -1)
        warnx("%s: %s: trying the block device",
            raw_device, strerror(errno));
if ((fd = open(block_device, O_RDONLY, 0)) == -1)
        err(1, "%s", block_device);

CONFORMING TO

These functions are non-standard BSD extensions.

HISTORY

The Fn err and Fn warn functions first appeared in BSD 4.4

SEE ALSO

error(3), exit(3), printf(3), perror(3), strerror(3)


errx (3)

 Continue to this page.


verr (3)

 Continue to this page.


verrx (3)

 Continue to this page.


vwarn (3)

 Continue to this page.


vwarnx (3)

 Continue to this page.


warn (3)

 Continue to this page.


warnx (3)

 Continue to this page.


a64l(3)

A64L

Section: Linux Programmer's Manual (3)
Updated: 2002-02-15 Return to Main Contents

NAME

a64l, l64a - convert between long and base-64

SYNOPSIS

#include <stdlib.h>

long a64l(char *str64);

char *l64a(long value);

DESCRIPTION

These functions provide a conversion between 32-bit long integers and little-endian base-64 ASCII strings (of length zero to six). If the string used as argument for a64l() has length greater than six, only the first six bytes are used. If longs have more than 32 bits, then l64a() uses only the low order 32 bits of value, and a64l() sign-extends its 32-bit result.

The 64 digits in the base 64 system are:

'.'     represents a 0
'/'     represents a 1
0-9     represent  2-11
A-Z     represent 12-37
a-z     represent 38-63
So 123 = 59*64^0 + 1*64^1 = "v/".

CONFORMING TO

POSIX.1-2001.

NOTES

The value returned by a64l() may be a pointer to a static buffer, possibly overwritten by later calls.

The behavior of l64a() is undefined when value is negative. If value is zero, it returns an empty string.

These functions are broken in glibc before 2.2.5 (puts most significant digit first).

This is not the encoding used by uuencode(1).

SEE ALSO

uuencode(1), strtoul(3)


l64a (3)

 Continue to this page.


strtoq (3)

 Continue to this page.


strtouq (3)

 Continue to this page.


ether_aton(3)

ETHER_ATON

Section: Linux Programmer's Manual (3)
Updated: 2002-07-20 Return to Main Contents

NAME

ether_aton, ether_ntoa, ether_ntohost, ether_hostton, ether_line, ether_ntoa_r, ether_aton_r - Ethernet address manipulation routines

SYNOPSIS

#include <netinet/ether.h>

char *ether_ntoa(const struct ether_addr *addr);

struct ether_addr *ether_aton(const char *asc);

int ether_ntohost(char *hostname, const struct ether_addr *addr);

int ether_hostton(const char *hostname, struct ether_addr *addr);

int ether_line(const char *line, struct ether_addr *addr,
               char *hostname);

/* GNU extensions */

char *ether_ntoa_r(const struct ether_addr *addr, char *buf);

struct ether_addr *ether_aton_r(const char *asc,
                                struct ether_addr *addr);

DESCRIPTION

ether_aton() converts the 48-bit Ethernet host address asc from the standard hex-digits-and-colons notation into binary data in network byte order and returns a pointer to it in a statically allocated buffer, which subsequent calls will overwrite. ether_aton() returns NULL if the address is invalid.

The ether_ntoa() function converts the Ethernet host address addr given in network byte order to a string in standard hex-digits-and-colons notation, omitting leading zeroes. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.

The ether_ntohost() function maps an Ethernet address to the corresponding hostname in /etc/ethers and returns non-zero if it cannot be found.

The ether_hostton() function maps a hostname to the corresponding Ethernet address in /etc/ethers and returns non-zero if it cannot be found.

The ether_line() function parses a line in /etc/ethers format (ethernet address followed by whitespace followed by hostname; '#' introduces a comment) and returns an address and hostname pair, or non-zero if it cannot be parsed. The buffer pointed to by hostname must be sufficiently long, for example, have the same length as line.

The functions ether_ntoa_r() and ether_aton_r() are re-entrant threadsafe versions of ether_ntoa() and ether_aton() respectively, and do not use static buffers.

The structure ether_addr is defined in net/ethernet.h as:

struct ether_addr {
    u_int8_t ether_addr_octet[6];
}

CONFORMING TO

4.3BSD, SunOS

BUGS

The glibc 2.2.5 implementation of ether_line() is broken.

SEE ALSO

ethers(5)


mtrace(3)

MTRACE

Section: Linux Programmer's Manual (3)
Updated: 2002-07-20 Return to Main Contents

NAME

mtrace, muntrace - malloc debugging

SYNOPSIS

#include <mcheck.h>

void mtrace(void);

void muntrace(void);

DESCRIPTION

The function mtrace() installs handlers for malloc(3), realloc(3) and free(3). The function muntrace() disables these handlers.
The environment variable MALLOC_TRACE defines a file where mtrace() writes its output. This file must be writable to the user or mtrace() will do nothing. If the file is not empty it will be truncated.

CONFORMING TO

These are GNU extensions.

NOTES

The output of mtrace() will be ASCII but not in a friendly format. So glibc comes with a perl-script called mtrace to make sense of it.

SEE ALSO

malloc(3), malloc_hook(3)


ether_ntoa (3)

 Continue to this page.


ether_ntohost (3)

 Continue to this page.


ether_hostton (3)

 Continue to this page.


ether_line (3)

 Continue to this page.


ether_ntoa_r (3)

 Continue to this page.


ether_aton_r (3)

 Continue to this page.


argz_add(3)

ARGZ_ADD

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

argz_add, argz_add_sep, argz_append, argz_count, argz_create, argz_create_sep, argz_delete, argz_extract, argz_insert, argz_next, argz_replace, argz_stringify - functions to handle an argz list

SYNOPSIS

#include <argz.h>

error_t
argz_add(char **argz, size_t *argz_len, const char *str);

error_t
argz_add_sep(char **argz, size_t *argz_len,

                    const char *str, int delim);

error_t
argz_append(char **argz, size_t *argz_len,

                    const char *buf, size_t buf_len);

size_t
argz_count(const char *argz, size_t argz_len);

error_t
argz_create(char * const argv[], char **argz,

                    size_t *argz_len);

error_t
argz_create_sep(const char *str, int sep, char **argz,

                    size_t *argz_len);

error_t
argz_delete(char **argz, size_t *argz_len, char *entry);

void
argz_extract(char *argz, size_t argz_len, char  **argv);

error_t
argz_insert(char **argz, size_t *argz_len, char *before,

                    const char *entry);

char *
argz_next(char *argz, size_t argz_len, const char *entry);

error_t
argz_replace(char **argz, size_t *argz_len, const char *str,

                    const char *with, unsigned int *replace_count);

void
argz_stringify(char *argz, size_t len, int sep);

DESCRIPTION

These functions are glibc-specific.

An argz vector is a pointer to a character buffer together with a length. The intended interpretation of the character buffer is an array of strings, where the strings are separated by null bytes ('\0'). If the length is non-zero, the last byte of the buffer must be a null byte.

These functions are for handling argz vectors. The pair (NULL,0) is an argz vector, and, conversely, argz vectors of length 0 must have NULL pointer. Allocation of nonempty argz vectors is done using malloc(3), so that free(3) can be used to dispose of them again.

argz_add() adds the string str at the end of the array *argz, and updates *argz and *argz_len.

argz_add_sep() is similar, but splits the string str into substrings separated by the delimiter delim. For example, one might use this on a Unix search path with delimiter ':'.

argz_append() appends the argz vector (buf,buf_len) after (*argz,*argz_len) and updates *argz and *argz_len. (Thus, *argz_len will be increased by buf_len.)

argz_count() counts the number of strings, that is, the number of null bytes ('\0'), in (argz,argz_len).

argz_create() converts a Unix-style argument vector argv, terminated by (char *) 0, into an argz vector (*argz,*argz_len).

argz_create_sep() converts the null-terminated string str into an argz vector (*argz,*argz_len) by breaking it up at every occurrence of the separator sep.

argz_delete() removes the substring pointed to by entry from the argz vector (*argz,*argz_len) and updates *argz and *argz_len.

argz_extract() is the opposite of argz_create(). It takes the argz vector (argz,argz_len) and fills the array starting at argv with pointers to the substrings, and a final NULL, making a Unix-style argv vector. The array argv must have room for argz_count(argz,argz_len) + 1 pointers.

argz_insert() is the opposite of argz_delete(). It inserts the argument entry at position before into the argz vector (*argz,*argz_len) and updates *argz and *argz_len. If before is NULL, then entry will inserted at the end.

argz_next() is a function to step trough the argz vector. If entry is NULL, the first entry is returned. Otherwise, the entry following is returned. It returns NULL if there is no following entry.

argz_replace() replaces each occurrence of str with with, reallocating argz as necessary. If replace_count is non-NULL, *replace_count will be incremented by the number of replacements.

argz_stringify() is the opposite of argz_create_sep(). It transforms the argz vector into a normal string by replacing all null bytes ('\0') except the last by sep.

RETURN VALUE

All argz functions that do memory allocation have a return type of error_t, and return 0 for success, and ENOMEM if an allocation error occurs.

CONFORMING TO

These functions are a GNU extension. Handle with care.

BUGS

Argz vectors without a terminating null byte may lead to Segmentation Faults.

SEE ALSO

envz(3)


argz_add_sep (3)

 Continue to this page.


argz_append (3)

 Continue to this page.


argz_count (3)

 Continue to this page.


argz_create (3)

 Continue to this page.


argz_create_sep (3)

 Continue to this page.


argz_delete (3)

 Continue to this page.


argz_extract (3)

 Continue to this page.


argz_insert (3)

 Continue to this page.


argz_next (3)

 Continue to this page.


argz_replace (3)

 Continue to this page.


argz_stringify (3)

 Continue to this page.


envz_add(3)

ENVZ_ADD

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

envz_add, envz_entry, envz_get, envz_merge, envz_remove, envz_strip - environment string support

SYNOPSIS

#include <envz.h>

error_t
envz_add(char **envz, size_t *envz_len,

                const char *name, const char *value);

char *
envz_entry(const char *envz, size_t *envz_len, const char *name);

char *
envz_get(const char *envz, size_t *envz_len, const char *name);

error_t
envz_merge(char **envz, size_t *envz_len,

                const char *envz2, size_t envz2_len, int override);

void
envz_remove(char **envz, size_t *envz_len, const char *name);

void
envz_strip(char **envz, size_t *envz_len);

DESCRIPTION

These functions are glibc-specific.

An argz vector is a pointer to a character buffer together with a length, see argz_add(3). An envz vector is a special argz vector, namely one where the strings have the form "name=value". Everything after the first '=' is considered to be the value. If there is no '=', the value is taken to be NULL. (While the value in case of a trailing '=' is the empty string "".)

These functions are for handling envz vectors.

envz_add() adds the string name = value (in case value is non-NULL) or name (in case value is NULL) to the envz vector (*envz,*envz_len) and updates *envz and *envz_len. If an entry with the same name existed, it is removed.

envz_entry() looks for name in the envz vector (envz,envz_len) and returns the entry if found, or NULL if not.

envz_get() looks for name in the envz vector (envz,envz_len) and returns the value if found, or NULL if not. (Note that the value can also be NULL, namely when there is an entry for name without '=' sign.)

envz_merge() adds each entry in envz2 to *envz, as if with envz_add(). If override is true, then values in envz2 will supersede those with the same name in *envz, otherwise not.

envz_remove() removes the entry for name from (*envz,*envz_len) if there was one.

envz_strip() removes all entries with value NULL.

RETURN VALUE

All envz functions that do memory allocation have a return type of error_t, and return 0 for success, and ENOMEM if an allocation error occurs.

CONFORMING TO

These functions are a GNU extension. Handle with care.

EXAMPLE

#include <stdio.h>
#include <envz.h>

int
main(int argc, char *argv[], char *envp[])
{
    int i, e_len = 0;
    char *str;

    for (i=0; envp[i] != NULL; i++)
        e_len += strlen(envp[i]) + 1;

    str = envz_entry(*envp, e_len, "HOME");
    printf("%s\n", str);
    str = envz_get(*envp, e_len, "HOME");
    printf("%s\n", str);
    exit(EXIT_SUCCESS);
}

SEE ALSO

argz(3)


envz_entry (3)

 Continue to this page.


envz_get (3)

 Continue to this page.


envz_merge (3)

 Continue to this page.


envz_remove (3)

 Continue to this page.


envz_strip (3)

 Continue to this page.


shm_open(3)

SHM_OPEN

Section: Linux Programmer's Manual (3)
Updated: 2004-12-17 Return to Main Contents

NAME

shm_open, shm_unlink - Create/open or unlink POSIX shared memory objects

SYNOPSIS

#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h> /* For O_* constants */

int shm_open(const char *name, int oflag, mode_t mode);

int shm_unlink(const char *name);

Link with -lrt.

DESCRIPTION

shm_open() creates and opens a new, or opens an existing, POSIX shared memory object. A POSIX shared memory object is in effect a handle which can be used by unrelated processes to mmap(2) the same region of shared memory. The shm_unlink() function performs the converse operation, removing an object previously created by shm_open().

The operation of shm_open() is analogous to that of open(2). name specifies the shared memory object to be created or opened. For portable use, name should have an initial slash (/) and contain no embedded slashes.

oflag is a bit mask created by ORing together exactly one of O_RDONLY or O_RDWR and any of the other flags listed here:

O_RDONLY
Open the object for read access. A shared memory object opened in this way can only be mmap(2)ed for read (PROT_READ) access.
O_RDWR
Open the object for read-write access.
O_CREAT
Create the shared memory object if it does not exist. The user and group ownership of the object are taken from the corresponding effective IDs of the calling process, and the object's permission bits are set according to the low-order 9 bits of mode, except that those bits set in the process file mode creation mask (see umask(2)) are cleared for the new object. A set of macro constants which can be used to define mode is listed in open(2).

A new shared memory object initially has zero length --- the size of the object can be set using ftruncate(2). The newly allocated bytes of a shared memory object are automatically initialized to 0.

O_EXCL
If O_CREAT was also specified, and a shared memory object with the given name already exists, return an error. The check for the existence of the object, and its creation if it does not exist, are performed atomically.
O_TRUNC
If the shared memory object already exists, truncate it to zero bytes.

On successful completion shm_open() returns a new file descriptor referring to the shared memory object. This file descriptor is guaranteed to be the lowest-numbered file descriptor not previously opened within the process. The FD_CLOEXEC flag (see fcntl(2)) is set for the file descriptor.

The file descriptor is normally used in subsequent calls to ftruncate(2) (for a newly created object) and mmap(2). After a call to mmap(2) the file descriptor may be closed without affecting the memory mapping.

The operation of shm_unlink() is analogous to unlink(2): it removes a shared memory object name, and, once all processes have unmapped the object, de-allocates and destroys the contents of the associated memory region. After a successful shm_unlink(), attempts to shm_open() an object with the same name will fail (unless O_CREAT was specified, in which case a new, distinct object is created).

RETURN VALUE

On success, shm_open() returns a non-negative file descriptor. On failure, shm_open() returns -1. shm_unlink() returns 0 on success, or -1 on error.

ERRORS

On failure, errno is set to indicate the cause of the error. Values which may appear in errno include the following:
EACCES
Permission to shm_unlink() the shared memory object was denied.
EACCES
Permission was denied to shm_open() name in the specified mode, or O_TRUNC was specified and the caller does not have write permission on the object.
EEXIST
Both O_CREAT and O_EXCL were specified to shm_open() and the shared memory object specified by name already exists.
EINVAL
The name argument to shm_open() was invalid.
EMFILE
The process already has the maximum number of files open.
ENAMETOOLONG
The length of name exceeds PATH_MAX.
ENFILE
The limit on the total number of files open on the system has been reached.
ENOENT
An attempt was made to shm_open() a name that did not exist, and O_CREAT was not specified.
ENOENT
An attempt was to made to shm_unlink() a name that does not exist.

VERSIONS

These functions are provided in glibc 2.2 and later.

CONFORMING TO

POSIX.1-2001.

POSIX.1-2001 says that the group ownership of a newly created shared memory object is set to either the calling process's effective group ID or "a system default group ID"

NOTES

POSIX leaves the behavior of the combination of O_RDONLY and O_TRUNC unspecified. On Linux, this will successfully truncate an existing shared memory object --- this may not be so on other Unix systems.

The POSIX shared memory object implementation on Linux 2.4 makes use of a dedicated file system, which is normally mounted under /dev/shm.

SEE ALSO

close(2), fchmod(2), fchown(2), fcntl(2), fstat(2), ftruncate(2), mmap(2), open(2), umask(2)


ttyname_r (3)

 Continue to this page.


ttyslot(3)

TTYSLOT

Section: Linux Programmer's Manual (3)
Updated: 2002-07-20 Return to Main Contents

NAME

ttyslot - find the slot of the current user's terminal in some file

SYNOPSIS

#include <unistd.h> /* on BSD-like systems */
#include <stdlib.h> /* on System V-like systems */

int ttyslot(void);

DESCRIPTION

The legacy function ttyslot() returns the index of the current user's entry in some file.

Now "What file?" you ask. Well, let's first look at some history.

Ancient History

There used to be a file /etc/ttys in Unix V6, that was read by the init(8) program to find out what to do with each terminal line. Each line consisted of three characters. The first character was either '0' or '1', where '0' meant "ignore". The second character denoted the terminal: '8' stood for "/dev/tty8". The third character was an argument to getty(8) indicating the sequence of line speeds to try ('-' was: start trying 110 baud). Thus a typical line was "18-". A hang on some line was solved by changing the '1' to a '0', signaling init, changing back again, and signaling init again.

In Unix V7 the format was changed: here the second character was the argument to getty(8) indicating the sequence of line speeds to try ('0' was: cycle through 300-1200-150-110 baud; '4' was for the on-line console DECwriter) while the rest of the line contained the name of the tty. Thus a typical line was "14console".

Later systems have more elaborate syntax. System V-like systems have /etc/inittab instead.

Ancient History (2)

On the other hand, there is the file /etc/utmp listing the people currently logged in. It is maintained by login(8). It has a fixed size, and the appropriate index in the file was determined by login(8) using the ttyslot() call to find the number of the line in /etc/ttys (counting from 1).

The semantics of ttyslot

Thus, the function ttyslot() returns the index of the controlling terminal of the current process in the file /etc/ttys, and that is (usually) the same as the index of the entry for the current user in the file /etc/utmp. BSD still has the /etc/ttys file, but System V-like systems do not, and hence cannot refer to it. Thus, on such systems the documentation says that ttyslot() returns the current user's index in the user accounting data base.

RETURN VALUE

If successful, this function returns the slot number. On error (e.g., if none of the file descriptors 0, 1 or 2 is associated with a terminal that occurs in this data base) it returns 0 on Unix V6 and V7 and BSD-like systems, but -1 on System V-like systems.

CONFORMING TO

SUSv1; marked as LECACY in SUSv2; removed in POSIX.1-2001. SUSv2 requires -1 on error.

NOTES

The utmp file is found various places on various systems, such as /etc/utmp, /var/adm/utmp, /var/run/utmp.

The glibc2 implementation of this function reads the file _PATH_TTYS, defined in <ttyent.h> as "/etc/ttys". It returns 0 on error. Since Linux systems do not usually have "/etc/ttys", it will always return 0.

Minix also has fttyslot(fd).

SEE ALSO

getttyent(3), ttyname(3), utmp(5)


getttyent(3)

GETTTYENT

Section: Linux Programmer's Manual (3)
Updated: 2002-07-18 Return to Main Contents

NAME

getttyent, getttynam, setttyent, endttyent - get ttys file entry

SYNOPSIS

#include <ttyent.h>

struct ttyent *getttyent(void);

struct ttyent *getttynam(const char *name);

int setttyent(void);

int endttyent(void);

DESCRIPTION

These functions provide an interface to the file _PATH_TTYS (e.g., /etc/ttys).

The function setttyent() opens the file or rewinds it if already open.

The function endttyent() closes the file.

The function getttynam() searches for a given ttyname in the file. It returns a pointer to a struct ttyent (description below).

The function getttyent() opens the file _PATH_TTYS (if necessary) and returns the first entry. If the file is already open, the next entry.

The ttyent structure

struct ttyent {
        char    *ty_name;       /* terminal device name */
        char    *ty_getty;      /* command to execute, usually getty */
        char    *ty_type;       /* terminal type for termcap */
        int     ty_status;      /* status flags */
        char    *ty_window;     /* command to start up window manager */
        char    *ty_comment;    /* comment field */
};

ty_status can be

#define TTY_ON       0x01   /* enable logins (start ty_getty program) */
#define TTY_SECURE   0x02   /* allow UID 0 to login */

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs, and perhaps other systems.

NOTES

Under Linux the file /etc/ttys, and the functions described above, are not used.

SEE ALSO

ttyname(3), ttyslot(3)


setttyent (3)

 Continue to this page.


getttynam (3)

 Continue to this page.


endttyent (3)

 Continue to this page.


key_setsecret(3)

KEY_SETSECRET

Section: Linux Programmer's Manual (3)
Updated: 2002-07-18 Return to Main Contents

NAME

key_decryptsession, key_encryptsession, key_setsecret, key_gendes, key_secretkey_is_set - interfaces to rpc keyserver daemon

SYNOPSIS

#include <rpc/rpc.h>

int key_decryptsession(const char *remotename, des_block *deskey);

int key_encryptsession(const char *remotename, des_block *deskey);

int key_gendes(des_block *deskey);

int key_setsecret(const char *key);

int key_secretkey_is_set(void);

DESCRIPTION

The functions here are used within the RPC's secure authentication mechanism (AUTH_DES). There should be no need for user programs to use this functions.

The function key_decryptsession() uses the (remote) server netname and takes the DES key for decrypting. It uses the public key of the server and the secret key associated with the effective UID of the calling process.

The function key_encryptsession() is the inverse of key_decryptsession(). It encrypts the DES keys with the public key of the server and the secret key associated with the effective UID of the calling process.

The function key_gendes() is used to ask the keyserver for a secure conversation key.

The function key_setsecret() is used to set the key for the effective UID of the calling process.

The function key_secretkey_is_set() can be used to determine whether a key has been set for the effective UID of the calling process.

RETURN VALUE

These functions return 1 on success and 0 on failure.

NOTES

Note that we talk about two types of encryption here. One is asymmetric using a public and secret key. The other is symmetric, the 64-bit DES.
The routines were part of the linux/doors-project, abandoned by now.

SEE ALSO

crypt(3)


key_gendes (3)

 Continue to this page.


key_secretkey_is_set (3)

 Continue to this page.


nan(3)

NAN

Section: Linux Programmer's Manual (3)
Updated: 2002-08-10 Return to Main Contents

NAME

nan, nanf, nanl - return 'Not a Number'

SYNOPSIS

#include <math.h>

double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

Compile with -std=c99; link with -lm.

DESCRIPTION

These functions return a representation (determined by tagp) of a quiet NaN. If the implementation does not support quiet NaNs, these functions return zero.

The call nan(char-sequence) is equivalent to strtod (NAN(char-sequence),NULL) and similarly calls to nanf() and nanl() are equivalent to analogous calls to strtof(3) and strtold(3).

The argument tagp is used in an unspecified manner. On IEEE 754 systems, there are many representations of NaN, and tagp selects one. On other systems it may do nothing.

CONFORMING TO

C99. See also IEC 559 and the appendix with recommended functions in IEEE 754/IEEE 854.

SEE ALSO

isnan(3), strtod(3)


key_encryptsession (3)

 Continue to this page.


key_decryptsession (3)

 Continue to this page.


muntrace (3)

 Continue to this page.


assert_perror(3)

ASSERT_PERROR

Section: Linux Programmer's Manual (3)
Updated: 2002-08-25 Return to Main Contents

NAME

assert_perror - test errnum and abort

SYNOPSIS

#define _GNU_SOURCE
#include <assert.h>

void assert_perror(int errnum);

DESCRIPTION

If the macro NDEBUG was defined at the moment <assert.h> was last included, the macro assert_perror() generates no code, and hence does nothing at all. Otherwise, the macro assert_perror() prints an error message to standard error and terminates the program by calling abort(3) if errnum is non-zero. The message contains the filename, function name and line number of the macro call, and the output of strerror(errnum).

RETURN VALUE

No value is returned.

CONFORMING TO

This is a GNU extension.

BUGS

The purpose of the assert macros is to help the programmer find bugs in his program, things that cannot happen unless there was a coding mistake. However, with system or library calls the situation is rather different, and error returns can happen, and will happen, and should be tested for. Not by an assert, where the test goes away when NDEBUG is defined, but by proper error handling code. Never use this macro.

SEE ALSO

abort(3), assert(3), exit(3), strerror(3), feature_test_macros(7)


malloc_hook(3)

MALLOC_HOOK

Section: Linux Programmer's Manual (3)
Updated: 2002-07-20 Return to Main Contents

NAME

__malloc_hook, __malloc_initialize_hook, __memalign_hook, __free_hook, __realloc_hook, __after_morecore_hook - malloc debugging variables

SYNOPSIS

#include <malloc.h>

void *(*__malloc_hook)(size_t size, const void *caller);

void *(*__realloc_hook)(void *ptr, size_t size, const void *caller);

void *(*__memalign_hook)(size_t alignment, size_t size, const void *caller);

void (*__free_hook)(void *ptr, const void *caller);

void (*__malloc_initialize_hook)(void);

void (*__after_morecore_hook)(void);

DESCRIPTION

The GNU C library lets you modify the behavior of malloc(3), realloc(3), and free(3) by specifying appropriate hook functions. You can use these hooks to help you debug programs that use dynamic memory allocation, for example.

The variable __malloc_initialize_hook points at a function that is called once when the malloc implementation is initialized. This is a weak variable, so it can be overridden in the application with a definition like the following:

    void (*__malloc_initialize_hook)(void) = my_init_hook;

Now the function my_init_hook() can do the initialization of all hooks.

The four functions pointed to by __malloc_hook, __realloc_hook, __memalign_hook, __free_hook have a prototype like the functions malloc(3), realloc(3), memalign(3), free(3), respectively, except that they have a final argument caller that gives the address of the caller of malloc(3), etc.

The variable __after_morecore_hook points at a function that is called each time after sbrk(2) was asked for more memory.

CONFORMING TO

These functions are GNU extensions.

EXAMPLE

Here is a short example of how to use these variables.

#include <stdio.h>
#include <malloc.h>

/* Prototypes for our hooks.  */
static void my_init_hook(void);
static void *my_malloc_hook(size_t, const void *);

/* Variables to save original hooks. */
static void *(*old_malloc_hook)(size_t, const void *);

/* Override initializing hook from the C library. */
void (*__malloc_initialize_hook) (void) = my_init_hook;

static void
my_init_hook(void)
{
    old_malloc_hook = __malloc_hook;
    __malloc_hook = my_malloc_hook;
}

static void *
my_malloc_hook(size_t size, const void *caller)
{
    void *result;

    /* Restore all old hooks */
    __malloc_hook = old_malloc_hook;

    /* Call recursively */
    result = malloc(size);

    /* Save underlying hooks */
    old_malloc_hook = __malloc_hook;

    /* `printf' might call `malloc', so protect it too. */
    printf("malloc(%u) called from %p returns %p\n",
            (unsigned int) size, caller, result);

    /* Restore our own hooks */
    __malloc_hook = my_malloc_hook;

    return result;
}

SEE ALSO

mallinfo(3), malloc(3), mcheck(3), mtrace(3)


nanl (3)

 Continue to this page.


__malloc_hook (3)

 Continue to this page.


nanf (3)

 Continue to this page.


gsignal(3)

GSIGNAL

Section: Linux Programmer's Manual (3)
Updated: 2002-08-25 Return to Main Contents

NAME

gsignal, ssignal - software signal facility

SYNOPSIS

#include <signal.h>

typedef void (*sighandler_t)(int);

int gsignal(signum);

sighandler_t ssignal(int signum, sighandler_t action);

DESCRIPTION

Don't use these functions under Linux. Due to a historical mistake, under Linux these functions are aliases for raise(3) and signal(2), respectively.

Elsewhere, on System V-like systems, these functions implement software signaling, entirely independent of the classical signal and kill functions. The function ssignal() defines the action to take when the software signal with number signum is raised using the function gsignal(), and returns the previous such action or SIG_DFL. The function gsignal() does the following: if no action (or the action SIG_DFL) was specified for signum, then it does nothing and returns 0. If the action SIG_IGN was specified for signum, then it does nothing and returns 1. Otherwise, it resets the action to SIG_DFL and calls the action function with parameter signum, and returns the value returned by that function. The range of possible values signum varies (often 1-15 or 1-17).

CONFORMING TO

These functions are available under AIX, DG/UX, HP-UX, SCO, Solaris, Tru64. They are called obsolete under most of these systems, and are broken under Linux libc and glibc. Some systems also have gsignal_r() and ssignal_r().

SEE ALSO

kill(2), signal(2), raise(3)


ssignal (3)

 Continue to this page.


qecvt(3)

QECVT

Section: Linux Programmer's Manual (3)
Updated: 2002-08-25 Return to Main Contents

NAME

qecvt, qfcvt, qgcvt - convert a floating-point number to a string

SYNOPSIS

#include <stdlib.h>

char *qecvt(long double number, int ndigits, int *decpt, int *sign);

char *qfcvt(long double number, int ndigits, int *decpt, int *sign);

char *qgcvt(long double number, int ndigit, char *buf);

DESCRIPTION

The functions qecvt(), qfcvt() and qgcvt() are identical to ecvt(3), fcvt(3) and gcvt(3) respectively, except that they use a long double argument number. See ecvt(3) and gcvt(3).

CONFORMING TO

SVr4. Not seen in most common Unix implementations, but occurs in SunOS. Not supported by libc4 and libc5. Supported by glibc.

NOTES

These functions are obsolete. Instead, sprintf(3) is recommended.

SEE ALSO

ecvt(3), ecvt_r(3), gcvt(3), sprintf(3)


qfcvt (3)

 Continue to this page.


ecvt_r(3)

ECVT_R

Section: Linux Programmer's Manual (3)
Updated: 2004-10-05 Return to Main Contents

NAME

ecvt_r, fcvt_r, qecvt_r, qfcvt_r - convert a floating-point number to a string

SYNOPSIS

#include <stdlib.h>

int ecvt_r(double number, int ndigits, int *decpt,
           int *sign, char *buf, size_t len);

int fcvt_r(double number, int ndigits, int *decpt,
           int *sign, char *buf, size_t len);

int qecvt_r(long double number, int ndigits, int *decpt,
           int *sign, char *buf, size_t len);

int qfcvt_r(long double number, int ndigits, int *decpt,
           int *sign, char *buf, size_t len);

DESCRIPTION

The functions ecvt_r(), fcvt_r(), qecvt_r() and qfcvt_r() are identical to ecvt, fcvt, qecvt and qfcvt, respectively, except that they do not return their result in a static buffer, but instead use the supplied buf of size len. See ecvt(3) and qecvt(3).

RETURN VALUE

These functions return 0 on success, and -1 otherwise.

CONFORMING TO

These functions are GNU extensions.

NOTES

These functions are obsolete. Instead, sprintf(3) is recommended.

SEE ALSO

ecvt(3), qecvt(3), sprintf(3)


qgcvt (3)

 Continue to this page.


fcvt_r (3)

 Continue to this page.


qecvt_r (3)

 Continue to this page.


qfcvt_r (3)

 Continue to this page.


y0f (3)

 Continue to this page.


j0f (3)

 Continue to this page.


y0l (3)

 Continue to this page.


y1f (3)

 Continue to this page.


y1l (3)

 Continue to this page.


ynf (3)

 Continue to this page.


ynl (3)

 Continue to this page.


j0l (3)

 Continue to this page.


j1f (3)

 Continue to this page.


j1l (3)

 Continue to this page.


jnf (3)

 Continue to this page.


jnl (3)

 Continue to this page.


getumask(3)

GETUMASK

Section: Linux Programmer's Manual (3)
Updated: 2002-08-25 Return to Main Contents

NAME

getumask - get file creation mask

SYNOPSIS

#include <sys/types.h>
#include <sys/stat.h>

mode_t getumask(void);

DESCRIPTION

This function returns the current file creation mask. It is equivalent to

mode_t getumask(void)
{
    mode_t mask = umask( 0 );
    umask(mask);
    return mask;
}
except that it is documented to be thread-safe (that is, shares a lock with the umask(2) library call).

CONFORMING TO

This is a vaporware GNU extension.

NOTES

This function is documented but not implemented yet in glibc 2.2.5.

SEE ALSO

umask(2)


copysignf (3)

 Continue to this page.


copysignl (3)

 Continue to this page.


signbit(3)

SIGNBIT

Section: Linux Programmer's Manual (3)
Updated: 2002-08-10 Return to Main Contents

NAME

signbit - test sign of a real floating point number

SYNOPSIS

#include <math.h>

int signbit(X);

Compile with -std=c99; link with -lm.

DESCRIPTION

`signbit' is a generic macro which can work on all real floating-point types. It returns a non-zero value if the value of X has its sign bit set.

This is not the same as `x < 0.0', because IEEE 754 floating point allows zero to be signed. The comparison `-0.0 < 0.0' is false, but `signbit (-0.0)' will return a non-zero value.

CONFORMING TO

C99. This function is defined in IEC 559 (and the appendix with recommended functions in IEEE 754/IEEE 854).

SEE ALSO

copysign(3)


nextafter(3)

NEXTAFTER

Section: Linux Programmer's Manual (3)
Updated: 2002-08-10 Return to Main Contents

NAME

nextafter, nextafterf, nextafterl, nexttoward, nexttowardf, nexttowardl - floating point number manipulation

SYNOPSIS

#include <math.h>

double nextafter(double x, double y);
float nextafterf(float x, float y);
long double nextafterl(long double x, long double y);

double nexttoward(double x, long double y);
float nexttowardf(float x, long double y);
long double nexttowardl(long double x, long double y);

Link with -lm.

DESCRIPTION

The nextafter() functions return the next representable neighbor of x in the direction towards y. The size of the step between x and the result depends on the type of the result. If x = y the function simply returns y. If either value is NaN, then NaN is returned. Otherwise a value corresponding to the value of the least significant bit in the mantissa is added or subtracted, depending on the direction.

The nexttoward() functions do the same as the nextafter() functions, except that they have a long double second argument.

These functions will signal overflow or underflow if the result goes outside of the range of normalized numbers.

CONFORMING TO

C99. This function is defined in IEC 559 (and the appendix with recommended functions in IEEE 754/IEEE 854).

SEE ALSO

nearbyint(3)


nextafterf (3)

 Continue to this page.


nexttoward (3)

 Continue to this page.


nextafterl (3)

 Continue to this page.


nexttowardf (3)

 Continue to this page.


nexttowardl (3)

 Continue to this page.


gamma(3)

GAMMA

Section: Linux Programmer's Manual (3)
Updated: 2002-08-10 Return to Main Contents

NAME

gamma, gammaf, gammal - (logarithm of the) gamma function

SYNOPSIS

#include <math.h>

double gamma(double x);
float gammaf(float x);
long double gammal(long double x);

Link with -lm.

DESCRIPTION

For the definition of the Gamma function, see tgamma(3).

*BSD version

4.4BSD and FreeBSD libm have a gamma() function that computes the Gamma function, as one would expect.

glibc version

Glibc has a gamma() function that is equivalent to lgamma() and computes the natural logarithm of the Gamma function. (This is for compatibility reasons only. Don't use this function.)

CONFORMING TO

4.2BSD. Compatible with previous mistakes.

NOTES

History

4.2BSD had a gamma() that computed ln(|Gamma(|x|)|), leaving the sign of Gamma(|x|) in the external integer signgam. In 4.3BSD the name was changed to lgamma(), and the man page promises

"At some time in the future the name gamma will be rehabilitated and used for the Gamma function"

This did indeed happen in 4.4BSD, where gamma() computes the Gamma function (with no effect on signgam). However, this came too late, and we now have tgamma(), the "true gamma" function.

SEE ALSO

lgamma(3), signgam(3), tgamma(3)


gammaf (3)

 Continue to this page.


gammal (3)

 Continue to this page.


lgammaf (3)

 Continue to this page.


lgammal (3)

 Continue to this page.


lgammal_r (3)

 Continue to this page.


lgammaf_r (3)

 Continue to this page.


lgamma_r (3)

 Continue to this page.


tgamma(3)

TGAMMA

Section: Linux Programmer's Manual (3)
Updated: 2004-11-15 Return to Main Contents

NAME

tgamma, tgammaf, tgammal - true gamma function

SYNOPSIS

#include <math.h>

double tgamma(double x);
float tgammaf(float x);
long double tgammal(long double x);

Compile with -std=c99; link with -lm.

DESCRIPTION

The Gamma function is defined by

Gamma(x) = integral from 0 to infinity of t^(x-1) e^-t dt

It is defined for every real number except for non-positive integers. For non-negative integral m one has

Gamma(m+1) = m!

and, more generally, for all x:

Gamma(x+1) = x * Gamma(x)

Furthermore, the following is valid for all values of x outside the poles:

Gamma(x) * Gamma(1 - x) = PI / sin(PI * x)

This function returns the value of the Gamma function for the argument x. It had to be called "true gamma function" since there is already a function gamma(3) that returns something else.

ERRORS

In order to check for errors, set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

A range error occurs if x is too large. A pole error occurs if x is zero. A domain error (or a pole error) occurs if x is a negative integer.

CONFORMING TO

C99.

SEE ALSO

gamma(3), lgamma(3)


tgammaf (3)

 Continue to this page.


tgammal (3)

 Continue to this page.


getpt(3)

GETPT

Section: Linux Programmer's Manual (3)
Updated: 2002-10-09 Return to Main Contents

NAME

getpt - open the pseudo-terminal master (PTM)

SYNOPSIS

#include <stdlib.h>

int getpt(void)

DESCRIPTION

getpt() opens a pseudo-terminal master and returns its file descriptor. It is equivalent to open(/dev/ptmx,O_RDWR|O_NOCTTY) on Linux systems, though the pseudo-terminal master is located elsewhere on some systems that use GNU Libc.

RETURN VALUE

getpt() returns an open file descriptor upon successful completion. Otherwise, it returns -1 and sets errno to indicate the error.

CONFORMING TO

getpt() is specific to GNU Libc.

SEE ALSO

grantpt(3), ptsname(3), posix_openpt(3), unlockpt(3), ptmx(4), pty(7)


grantpt(3)

GRANTPT

Section: Linux Programmer's Manual (3)
Updated: 2003-01-30 Return to Main Contents

NAME

grantpt - grant access to the slave pseudo-terminal

SYNOPSIS

#define _XOPEN_SOURCE

#include <stdlib.h>

int grantpt(int fd);

DESCRIPTION

The grantpt() function changes the mode and owner of the slave pseudo-terminal device (pty) corresponding to the master pty referred to by fd. The user ID of the slave is set to the real UID of the calling process. The group ID is set to an unspecified value (e.g., tty). The mode of the slave is set to 0620 (crw--w----).

The behavior of grantpt() is unspecified if a signal handler is installed to catch SIGCHLD signals.

RETURN VALUE

When successful, grantpt() returns 0. Otherwise, it returns -1 and sets errno appropriately.

ERRORS

EACCES
The corresponding slave pty could not be accessed.
EBADF
The fd argument is not a valid open file descriptor.
EINVAL
The fd argument is valid but not associated with a master pty.

CONFORMING TO

POSIX.1-2001

NOTES

This is part of the Unix98 pty support, see pts(4). Many systems implement this function via a set-user-ID helper binary called "pt_chown". With Linux devpts no such helper binary is required.

SEE ALSO

open(2), posix_openpt(3), ptsname(3), unlockpt(3), pts(4), feature_test_macros(7), pty(7)


tcgetsid(3)

TCGETSID

Section: Linux Programmer's Manual (3)
Updated: 2003-01-30 Return to Main Contents

NAME

tcgetsid - get session ID

SYNOPSIS

#include <termios.h>

pid_t tcgetsid(int fd);

DESCRIPTION

The function tcgetsid() returns the session ID of the current session that has the terminal associated to fd as controlling terminal. This terminal must be the controlling terminal of the calling process.

RETURN VALUE

When fd refers to the controlling terminal of our session, the function tcgetsid() will return the session ID of this session. Otherwise, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
fd is not a valid file descriptor.
ENOTTY
The calling process does not have a controlling terminal, or it has one but it is not described by fd.

CONFORMING TO

POSIX.1-2001

NOTES

This function is implemented via the TIOCGSID ioctl(2), present since Linux 2.1.71.

SEE ALSO

getsid(2)


ptsname(3)

PTSNAME

Section: Linux Programmer's Manual (3)
Updated: 2004-12-17 Return to Main Contents

NAME

ptsname, ptsname_r - get the name of the slave pseudo-terminal

SYNOPSIS

#define _XOPEN_SOURCE

#include <stdlib.h>

char *ptsname(int fd);

#define _GNU_SOURCE

#include <stdlib.h>

char *ptsname_r(int fd, char *buf, size_t buflen);

DESCRIPTION

The ptsname() function returns the name of the slave pseudo-terminal (pty) device corresponding to the master referred to by fd.

The ptsname_r() function is the reentrant equivalent of ptsname(). It returns the name of the slave pseudo-terminal device as a null-terminated string in the buffer pointed to by buf. The buflen argument specifies the number of bytes available in buf.

RETURN VALUE

On success, ptsname() returns a pointer to a string in static storage which will be overwritten by subsequent calls. This pointer must not be freed. On failure, a NULL pointer is returned.

On success, ptsname_r() returns 0. On failure, a non-zero value is returned and errno is set to indicate the error.

ERRORS

EINVAL
(ptsname_r() only) buf is NULL.
ENOTTY
fd does not refer to a pseudo-terminal master device.
ERANGE
(ptsname_r() only) buf is too small.

CONFORMING TO

ptsname() is part of the Unix98 pseudo-terminal support (see pts(4)). This function is specified in POSIX.1-2001.

ptsname_r() is a Linux extension. A version of this function is documented on Tru64 and HP-UX, but on those implementations, -1 is returned on error, with errno set to indicate the error. Avoid using this function in portable programs.

SEE ALSO

grantpt(3), posix_openpt(3), ttyname(3), unlockpt(3), pts(4), feature_test_macros(7), pty(7)


unlockpt(3)

UNLOCKPT

Section: Linux Programmer's Manual (3)
Updated: 2003-01-30 Return to Main Contents

NAME

unlockpt - unlock a pseudo-terminal master/slave pair

SYNOPSIS

#define _XOPEN_SOURCE

#include <stdlib.h>

int unlockpt(int fd);

DESCRIPTION

The unlockpt() function unlocks the slave pseudo-terminal device (pty) corresponding to the master pty referred to by fd.

unlockpt() should be called before opening the slave side of a pty.

RETURN VALUE

When successful, unlockpt() returns 0. Otherwise, it returns -1 and sets errno appropriately.

ERRORS

EBADF
The fd argument is not a file descriptor open for writing.
EINVAL
The fd argument is not associated with a master pty.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

grantpt(3), posix_openpt(3), ptsname(3), pts(4), feature_test_macros(7), pty(7)


clog2(3)

CLOG2

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

clog2, clog2f, clog2l - base-2 logarithm of a complex number

SYNOPSIS

#include <complex.h>

double complex clog2(double complex z);
float complex clog2f(float complex z);
long double complex clog2l(long double complex z);

DESCRIPTION

The call clog2(z) is equivalent to clog(z)/log(2).

The other functions perform the same task for float and long double.

Note that z close to zero will cause an overflow.

CONFORMING TO

These function names are reserved for future use in C99.

AVAILABILITY

Not yet in glibc, as at version 2.4.

SEE ALSO

cabs(3), cexp(3), clog(3), clog10(3), complex(7)


clogf (3)

 Continue to this page.


clogl (3)

 Continue to this page.


csinhf (3)

 Continue to this page.


csinhl (3)

 Continue to this page.


aio_return(3)

AIO_RETURN

Section: Linux Programmer's Manual (3)
Updated: 2003-11-14 Return to Main Contents

NAME

aio_return - get return status of asynchronous I/O operation

SYNOPSIS

#include <aio.h>

ssize_t aio_return(struct aiocb *aiocbp);

DESCRIPTION

The aio_return() function returns the final return status for the asynchronous I/O request with control block pointed to by aiocbp.

This function should be called only once for any given request, after aio_error(3) returns something other than EINPROGRESS.

RETURN VALUE

If the asynchronous I/O operation has completed, this function returns the value that would have been returned in case of a synchronous read, write, or fsync request. Otherwise the return value is undefined. On error, the error value is returned.

ERRORS

EINVAL
aiocbp does not point at a control block for an asynchronous I/O request of which the return status has not been retrieved yet.

CONFORMING TO

POSIX.1-2001

SEE ALSO

aio_cancel(3), aio_error(3), aio_fsync(3), aio_read(3), aio_suspend(3), aio_write(3)


expm1f (3)

 Continue to this page.


expm1l (3)

 Continue to this page.


endnetgrent (3)

 Continue to this page.


dl_iterate_phdr(3)

DL_ITERATE_PHDR

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

dl_iterate_phdr - walk through list of shared objects

SYNOPSIS

#define _GNU_SOURCE
#include <link.h>

int dl_iterate_phdr(
          int (*callback) (struct dl_phdr_info *info,
                           size_t size, void *data),
          void *data);

DESCRIPTION

The dl_iterate_phdr() function allows an application to inquire at run-time to find out which shared objects it has loaded.

The dl_iterate_phdr() function walks through the list of an application's shared objects and calls the function callback once for each object, until either all shared objects have been processed or callback returns a non-zero value.

Each call to callback receives three arguments: info, which is a pointer to a structure containing information about the shared object; size, which is the size of the structure pointed to by info; and data, which is a copy of whatever value was passed by the calling program as the second argument (also named data) in the call to dl_iterate_phdr().

The info argument is a structure of the following type:

  struct dl_phdr_info {
    ElfW(Addr)        dlpi_addr;  /* Base address of object */
    const char       *dlpi_name;  /* (Null-terminated) name of
                                     object
    const ElfW(Phdr) *dlpi_phdr;  /* Pointer to array of
                                     ELF program headers
                                     for this object */
    ElfW(Half)        dlpi_phnum; /* # of items in 'dlpi_phdr' */
  };

(The ElfW() macro definition turns its argument into the name of an ELF data type suitable for the hardware architecture. For example, on a 32-bit platform, ElfW(Addr) yields the data type name Elf32_Addr. Further information on these types can be found in the <elf.h> and <link.h> header files.)

The dlpi_addr field indicates the base address of the shared object (i.e., the difference between the virtual memory address of the shared object and the offset of that object in the file from which it was loaded). The dlpi_name field is a null-terminated string giving the pathname from which the shared object was loaded.

To understand the meaning of the dlpi_phdr and dlpi_phnum fields, we need to be aware that an ELF shared object consists of a number of segments, each of which has a corresponding program header describing the segment. The dlpi_phdr field is a pointer to an array of the program headers for this shared object. The dlpi_phnum field indicates the size of this array.

These program headers are structures of the following form:

  typedef struct
  {
    Elf32_Word  p_type;    /* Segment type */
    Elf32_Off   p_offset;  /* Segment file offset */
    Elf32_Addr  p_vaddr;   /* Segment virtual address */
    Elf32_Addr  p_paddr;   /* Segment physical address */
    Elf32_Word  p_filesz;  /* Segment size in file */
    Elf32_Word  p_memsz;   /* Segment size in memory */
    Elf32_Word  p_flags;   /* Segment flags */
    Elf32_Word  p_align;   /* Segment alignment */
  } Elf32_Phdr;

Note that we can calculate the location of a particular program header, x, in virtual memory using the formula:

  addr == info->dlpi_addr + info->dlpi_phdr[x].p_vaddr;

RETURN VALUE

The dl_iterate_phdr() function returns whatever value was returned by the last call to callback.

VERSIONS

dl_iterate_phdr() has been supported in glibc since version 2.2.4.

CONFORMING TO

The dl_iterate_phdr() function is Linux specific and should be avoided in portable applications.

EXAMPLE

The following program displays a list of pathnames of the shared objects it has loaded. For each shared object, the program lists the virtual addresses at which the object's ELF segments are loaded.

#define _GNU_SOURCE
#include <link.h>
#include <stdlib.h>
#include <stdio.h>

static int
callback(struct dl_phdr_info *info, size_t size, void *data)
{
    int j;

    printf("name=%s (%d segments)\n", info->dlpi_name,
        info->dlpi_phnum);

    for (j = 0; j < info->dlpi_phnum; j++)
         printf("\t\t header %2d: address=%10p\n", j,
             (void *) (info->dlpi_addr + info->dlpi_phdr[j].p_vaddr));
    return 0;
}

int
main(int argc, char *argv[])
{
    dl_iterate_phdr(callback, NULL);

    exit(EXIT_SUCCESS);
}

SEE ALSO

ldd(1), objdump(1), readelf(1), dlopen(3), feature_test_macros(7), ld.so(8), and the Executable and Linking Format Specification available at various locations online.


isfinite (3)

 Continue to this page.


innetgr (3)

 Continue to this page.


setnetgrent(3)

SETNETGRENT

Section: Linux Programmer's Manual (3)
Updated: 2002-08-20 Return to Main Contents

NAME

setnetgrent, endnetgrent, getnetgrent, getnetgrent_r, innetgr - handle network group entries

SYNOPSIS

#include <netdb.h>

int setnetgrent(const char *netgroup);
void endnetgrent(void);
int getnetgrent(char **host, char **user, char **domain);

int getnetgrent_r(char **host, char **user, char **domain, char *buf, int buflen);

int innetgr(const char *netgroup, const char *host, const char *user, const char *domain);

DESCRIPTION

The netgroup is a SunOS invention. A netgroup database is a list of string triples (hostname,username,domainname) or other netgroup names. Any of the elements in a triple can be empty, which means that anything matches. The functions described here allow access to the netgroup databases. The file /etc/nsswitch.conf defines what database is searched.

The setnetgrent() call defines the netgroup that will be searched by subsequent getnetgrent() calls. The getnetgrent() function retrieves the next netgroup entry, and returns pointers in host, user, domain. A NULL pointer means that the corresponding entry matches any string. The pointers are valid only as long as there is no call to other netgroup-related functions. To avoid this problem you can use the GNU function getnetgrent_r() that stores the strings in the supplied buffer. To free all allocated buffers use endnetgrent().

In most cases you only want to check if the triplet (hostname,username,domainname) is a member of a netgroup. The function innetgr() can be used for this without calling the above three functions. Again, a NULL pointer is a wildcard and matches any string. The function is thread-safe.

RETURN VALUE

These functions return 1 on success and 0 for failure.

FILES

/etc/netgroup
/etc/nsswitch.conf

NOTES

In the BSD implementation, setnetgrent() returns void.

SEE ALSO

sethostent(3), setservent(3), setprotoent(3)


lrand48_r (3)

 Continue to this page.


conjf (3)

 Continue to this page.


conjl (3)

 Continue to this page.


ptsname_r (3)

 Continue to this page.


clog10(3)

CLOG10

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

clog10, clog10f, clog10l - base-10 logarithm of a complex number

SYNOPSIS

#define _GNU_SOURCE
#include <complex.h>

double complex clog10(double complex z);
float complex clog10f(float complex z);
long double complex clog10l(long double complex z);

Link with -lm.

DESCRIPTION

The call clog10(z) is equivalent to clog(z)/log(10). The other functions perform the same task for float and long double.

Note that z close to zero will cause an overflow.

CONFORMING TO

This function is a GNU extension. It is reserved for future use in C99.

SEE ALSO

cabs(3), cexp(3), clog(3), clog2(3), complex(7), feature_test_macros(7)


clog2f (3)

 Continue to this page.


clog2l (3)

 Continue to this page.


ctanhf (3)

 Continue to this page.


ctanhl (3)

 Continue to this page.


coshf (3)

 Continue to this page.


coshl (3)

 Continue to this page.


fegetexcept (3)

 Continue to this page.


cpowf (3)

 Continue to this page.


cpowl (3)

 Continue to this page.


cproj(3)

CPROJ

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cproj, cprojf, cprojl - project into Riemann Sphere

SYNOPSIS

#include <complex.h>

double complex cproj(double complex z);
float complex cprojf(float complex z);
long double complex cprojl(long double complex z);

Link with -lm.

DESCRIPTION

This function projects a point in the plane onto the surface of a Riemann Sphere, the one-point compactification of the complex plane. Each finite point z projects to z itself. Every complex infinite value is projected to a single infinite value, namely to positive infinity on the real axis.

CONFORMING TO

C99

NOTES

The glibc implementation is broken and does something entirely different.

SEE ALSO

cabs(3), complex(7)


srand48_r (3)

 Continue to this page.


fmtmsg(3)

FMTMSG

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

fmtmsg - print formatted error messages

SYNOPSIS

#include <fmtmsg.h>

int fmtmsg(long classification, const char *label,

           int severity, const char *text,

           const char *action, const char *tag);

DESCRIPTION

This function displays a message described by its parameters on the device(s) specified in the classification parameter. For messages written to stderr, the format depends on the MSGVERB environment variable.

The label parameter identifies the source of the message. The string must consist of two colon separated parts where the first part has not more than 10 and the second part not more than 14 characters.

The text parameter describes the condition of the error.

The action parameter describes possible steps to recover from the error. If it is printed, it is prefixed by "TO FIX: ".

The tag parameter is a reference to the online documentation where more information can be found. It should contain the label value and a unique identification number.

Dummy parameters

Each of the parameters can have a dummy value. The dummy classification value MM_NULLMC (0L) does not specify any output, so nothing is printed. The dummy severity value NO_SEV (0) says that no severity is supplied. The values MM_NULLLBL, MM_NULLTXT, MM_NULLACT, MM_NULLTAG are synonyms for ((char *) 0), the empty string, and MM_NULLSEV is a synonym for NO_SEV.

The classification parameter

The classification parameter is the sum of values describing 4 types of information.

The first value defines the output channel.

MM_PRINT
Output to stderr.
MM_CONSOLE
Output to the system console.
MM_PRINT | MM_CONSOLE
Output to both.

The second value is the source of the error:

MM_HARD
A hardware error occurred.
MM_FIRM
A firmware error occurred.
MM_SOFT
A software error occurred.

The third value encodes the detector of the problem:

MM_APPL
It is detected by an application.
MM_UTIL
It is detected by a utility.
MM_OPSYS
It is detected by the operating system.

The fourth value shows the severity of the incident:

MM_RECOVER
It is a recoverable error.
MM_NRECOV
It is a non-recoverable error.

The severity parameter

The severity parameter can take one of the following values:
MM_NOSEV
No severity is printed.
MM_HALT
This value is printed as HALT.
MM_ERROR
This value is printed as ERROR.
MM_WARNING
This value is printed as WARNING.
MM_INFO
This value is printed as INFO.

The numeric values are between 0 and 4. Using addseverity(3) or the environment variable SEV_LEVEL you can add more levels and strings to print.

RETURN VALUE

The function can return 4 values:
MM_OK
Everything went smooth.
MM_NOTOK
Complete failure.
MM_NOMSG
Error writing to stderr.
MM_NOCON
Error writing to the console.

ENVIRONMENT

The environment variable MSGVERB ("message verbosity") can be used to suppress parts of the output to stderr. (It does not influence output to the console.) When this variable is defined, is non-NULL, and is a colon-separated list of valid keywords, then only the parts of the message corresponding to these keywords is printed. Valid keywords are "label", "severity", "text", "action" and "tag".

The environment variable SEV_LEVEL can be used to introduce new severity levels. By default, only the five severity levels described above are available. Any other numeric value would make fmtmsg() print nothing. If the user puts SEV_LEVEL with a format like

SEV_LEVEL=[description[:description[:...]]]

in the environment of the process before the first call to fmtmsg(), where each description is of the form

severity-keyword,level,printstring

then fmtmsg() will also accept the indicated values for the level (in addition to the standard levels 0-4), and use the indicated printstring when such a level occurs.

The severity-keyword part is not used by fmtmsg() but it has to be present. The level part is a string representation of a number. The numeric value must be a number greater than 4. This value must be used in the severity parameter of fmtmsg() to select this class. It is not possible to overwrite any of the predefined classes. The printstring is the string printed when a message of this class is processed by fmtmsg().

CONFORMING TO

The functions fmtmsg() and addseverity(3), and environment variables MSGVERB and SEV_LEVEL come from System V. The function fmtmsg() and the environment variable MSGVERB are described in POSIX.1-2001.

NOTES

System V and Unixware man pages tell us that these functions have been replaced by "pfmt() and addsev()" or by "pfmt(), vpfmt(), lfmt(), and vlfmt()", and will be removed later.

EXAMPLE

#include <stdio.h>
#include <fmtmsg.h>

int
main(void)
{
    long class = MM_PRINT | MM_SOFT | MM_OPSYS | MM_RECOVER;
    int err;
    err = fmtmsg(class, "util-linux:mount", MM_ERROR,
                "unknown mount option", "See mount(8).",
                "util-linux:mount:017");
    switch(err) {
    case MM_OK:
        break;
    case MM_NOTOK:
        printf("Nothing printed\n");
        break;
    case MM_NOMSG:
        printf("Nothing printed to stderr\n");
        break;
    case MM_NOCON:
        printf("No console output\n");
        break;
    default:
        printf("Unknown error from fmtmsg()\n");
    }
    exit(EXIT_SUCCESS);
}

The output should be:

  util-linux:mount: ERROR: unknown mount option
  TO FIX: See mount(8).  util-linux:mount:017
and after
  MSGVERB=text:action; export MSGVERB
the output becomes:
  unknown mount option
  TO FIX: See mount(8).

SEE ALSO

addseverity(3), perror(3)


getpwuid_r (3)

 Continue to this page.


creal(3)

CREAL

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

creal, crealf, creall - get real part of a complex number

SYNOPSIS

#include <complex.h>

double creal(double complex z);
float crealf(float complex z);
long double creall(long double complex z);

Link with -lm.

DESCRIPTION

The creal() function returns the real part of the complex number z.

One has z = creal(z) + I * cimag(z).

CONFORMING TO

C99

NOTES

The gcc supports also __real__. That is a GNU extension.

SEE ALSO

cabs(3), cimag(3), complex(7)


wmempcpy (3)

 Continue to this page.


cerfcf (3)

 Continue to this page.


cerfcl (3)

 Continue to this page.


remquo(3)

REMQUO

Section: Linux Programmer's Manual (3)
Updated: 2002-08-10 Return to Main Contents

NAME

remquo, remquof, remquol - remainder and part of quotient

SYNOPSIS

#define _ISOC99_SOURCE

#include <math.h>

double remquo(double x, double y, int *quo);

float remquof(float x, float y, int *quo);

long double remquol(long double x, long double y, int *quo);

DESCRIPTION

These functions compute the remainder and part of the quotient upon division of x by y. A few bits of the quotient are stored via the quo pointer. The remainder is returned as function value.

The value of the remainder is the same as that computed by the remainder(3) function.

The value stored via the quo pointer has the sign of x/y and agrees with the quotient in at least the low order 3 bits.

For example, remquo(29.0,3.0) returns -1.0 and might store 2. Note that the actual quotient might not fit in an integer.

CONFORMING TO

C99

SEE ALSO

fmod(3), logb(3), remainder(3), feature_test_macros(7)


csinf (3)

 Continue to this page.


csinh(3)

CSINH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

csinh, csinhf, csinhl - complex hyperbolic sine

SYNOPSIS

#include <complex.h>

double complex csinh(double complex z);
float complex csinhf(float complex z);
long double complex csinhl(long double complex z);

Link with -lm.

DESCRIPTION

The complex hyperbolic sine function sinh(z) is defined as (exp(z)-exp(-z))/2.

CONFORMING TO

C99

SEE ALSO

cabs(3), ccosh(3), ctanh(3), complex(7)


csinl (3)

 Continue to this page.


ctanf (3)

 Continue to this page.


ctanh(3)

CTANH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

ctanh, ctanhf, ctanhl - complex hyperbolic tangent

SYNOPSIS

#include <complex.h>

double complex ctanh(double complex z);
float complex ctanhf(float complex z);
long double complex ctanhl(long double complex z);

Link with -lm.

DESCRIPTION

The complex hyperbolic tangent function ctanh(z) is defined mathematically as csinh(z) / ccosh(z).

CONFORMING TO

C99

SEE ALSO

cabs(3), ccosh(3), csinh(3), complex(7)


ctanl (3)

 Continue to this page.


localtime_r (3)

 Continue to this page.


csqrt(3)

CSQRT

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

csqrt, csqrtf, csqrtl - complex square root

SYNOPSIS

#include <complex.h>

double complex csqrt(double complex z);
float complex csqrtf(float complex z);
long double complex csqrtl(long double complex z);

Link with -lm.

DESCRIPTION

Calculate the square root of a given complex number, with non-negative real part, and with a branch cut along the negative real axis. (That means that csqrt(-1+eps*I) will be close to I while csqrt(-1-eps*I) will be close to -I, if eps is a small positive real number.)

CONFORMING TO

C99

SEE ALSO

cabs(3), cexp(3), complex(7)


fgetspent_r (3)

 Continue to this page.


addseverity(3)

ADDSEVERITY

Section: Linux Programmer's Manual (3)
Updated: 2002-08-07 Return to Main Contents

NAME

addseverity - introduce new severity classes

SYNOPSIS

#define _SVID_SOURCE

#include <fmtmsg.h>

int addseverity(int severity, const char *s);

DESCRIPTION

This function allows the introduction of new severity classes which can be addressed by the severity parameter of the fmtmsg(3) function. By default that latter function only knows how to print messages for severity 0-4 (with strings (none), HALT, ERROR, WARNING, INFO). This call attaches the given string s to the given value severity. If s is NULL, the severity class with the numeric value severity is removed. It is not possible to overwrite or remove one of the default severity classes. The severity value must be non-negative.

RETURN VALUE

Upon success, the value MM_OK is returned. Upon error, the return value is MM_NOTOK. Possible errors include: out of memory, attempt to remove a nonexistent or default severity class.

CONFORMING TO

This function is not specified in the X/Open Portability Guide although the fmtmsg(3) function is. It is available on System V systems.

NOTES

New severity classes can also be added by setting the environment variable SEV_LEVEL.

SEE ALSO

fmtmsg(3), feature_test_macros(7)


csqrtf (3)

 Continue to this page.


csqrtl (3)

 Continue to this page.


aio_suspend(3)

AIO_SUSPEND

Section: Linux Programmer's Manual (3)
Updated: 2003-11-14 Return to Main Contents

NAME

aio_suspend - wait for asynchronous I/O operation or timeout

SYNOPSIS

#include <aio.h>

int aio_suspend(const struct aiocb * const cblist[],

                int n, const struct timespec *timeout);

DESCRIPTION

The aio_suspend() function suspends the calling process until at least one of the asynchronous I/O requests in the list cblist of length n have completed, a signal is delivered, or timeout is not NULL and the time interval it indicates has passed.

Each item in the list must either be NULL (and then is ignored), or a pointer to a control block on which I/O was initiated using aio_read(3), aio_write(3), or lio_listio(3).

If CLOCK_MONOTONIC is supported, this clock is used to measure the timeout interval.

RETURN VALUE

If this function returns after completion of one of the indicated requests, it returns 0. Otherwise it returns -1 and sets errno appropriately.

ERRORS

EAGAIN
The call was ended by timeout, before any of the indicated operations had completed.
EINTR
The call was ended by signal. (Possibly the completion signal of one of the operations we were waiting for.)

CONFORMING TO

POSIX.1-2001

NOTES

One can achieve polling by using a non-NULL timeout that specifies a zero time interval.

SEE ALSO

aio_cancel(3), aio_error(3), aio_fsync(3), aio_read(3), aio_return(3), aio_write(3)


getgrouplist(3)

GETGROUPLIST

Section: Linux Programmer's Manual (3)
Updated: 2003-11-18 Return to Main Contents

NAME

getgrouplist - list of groups a user belongs to

SYNOPSIS

#include <grp.h>

int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);

DESCRIPTION

The getgrouplist() function scans the group database for all the groups user belongs to. Up to *ngroups group IDs corresponding to these groups are stored in the array groups; the return value from the function is the number of group IDs actually stored. The group group is automatically included in the list of groups returned by getgrouplist().

RETURN VALUE

If *ngroups is smaller than the total number of groups found, then getgrouplist() returns a value of `-1'. In all cases the actual number of groups is stored in *ngroups.

VERSIONS

This function is present since glibc 2.2.4.

CONFORMING TO

This function is non-standard; it appears on most BSDs.

BUGS

The glibc 2.3.2 implementation of this function is broken: it overwrites memory when the actual number of groups is larger than *ngroups.

EXAMPLE

/* This crashes with glibc 2.3.2 */
#include <stdio.h>
#include <stdlib.h>
#include <grp.h>
#include <pwd.h>

int
main(void)
{
    int i, ng = 0;
    char *user = "who";       /* username here */
    gid_t *groups = NULL;
    struct passwd *pw = getpwnam(user);

    if (pw == NULL)
        exit(EXIT_SUCCESS);

    if (getgrouplist(user, pw->pw_gid, NULL, &ng) < 0) {
        groups = (gid_t *) malloc(ng * sizeof (gid_t));
        getgrouplist(user, pw->pw_gid, groups, &ng);
    }

    for(i = 0; i < ng; i++)
        printf("%d\n", groups[i]);

    exit(EXIT_SUCCESS);
}

SEE ALSO

getgroups(2), setgroups(2)


fedisableexcept (3)

 Continue to this page.


fma(3)

FMA

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

fma, fmaf, fmal - floating-point multiply and add

SYNOPSIS

#include <math.h>

double fma(double x, double y, double z);

float fmaf(float x, float y, float z);

long double fmal(long double x, long double y, long double z);

Compile with -std=c99; link with -lm.

DESCRIPTION

The fma() function computes x * y + z. The result is rounded according to the rounding mode determined by the value of FLT_ROUNDS. FLT_ROUNDS indicates the implementation-defined rounding behavior for floating-point addition, and has one of the following values:
-1
The rounding mode is not determinable.
0
Rounding is towards 0.
1
Rounding is towards nearest number.
2
Rounding is towards positive infinity.
3
Rounding is towards negative infinity.

Other values represent machine-dependent, non-standard rounding modes.

CONFORMING TO

C99

SEE ALSO

fenv(3), remainder(3), remquo(3)


drand48_r(3)

DRAND48_R

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

drand48_r, erand48_r, lrand48_r, nrand48_r, mrand48_r, jrand48_r, srand48_r, seed48_r, lcong48_r - generate uniformly distributed pseudo-random numbers reentrantly

SYNOPSIS

#include <stdlib.h>

int drand48_r(struct drand48_data *buffer, double *result);

int erand48_r(unsigned short xsubi[3],

              struct drand48_data *buffer, double *result);

int lrand48_r(struct drand48_data *buffer, long int *result);

int nrand48_r(unsigned short int xsubi[3],

              struct drand48_data *buffer, long int *result);

int mrand48_r(struct drand48_data *buffer,long int *result);

int jrand48_r(unsigned short int xsubi[3],

              struct drand48_data *buffer, long int *result);

int srand48_r(long int seedval, struct drand48_data *buffer);

int seed48_r(unsigned short int seed16v[3],

             struct drand48_data *buffer);

int lcong48_r(unsigned short int param[7],

              struct drand48_data *buffer);

DESCRIPTION

These functions are the reentrant analogs of the functions described in drand48(3). Instead of modifying the global random generator state, they use the supplied data buffer.

Before the first use, this struct must be initialized, for example, by filling it with zeroes, or by calling one of the functions srand48_r(), seed48_r(), or lcong48_r().

RETURN VALUE

The return value is 0.

CONFORMING TO

These functions are GNU extensions and are not portable.

SEE ALSO

drand48(3), rand(3), random(3)


INFINITY(3)

INFINITY

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

INFINITY, NAN, HUGE_VAL, HUGE_VALF, HUGE_VALL - floating point constants

SYNOPSIS

#define _ISOC99_SOURCE

#include <math.h>

INFINITY

NAN

HUGE_VAL

HUGE_VALF

HUGE_VALL

DESCRIPTION

The macro INFINITY expands to a float constant representing positive infinity.

The macro NAN expands to a float constant representing a quiet NaN (when supported). A quiet NaN is a NaN ("not-a-number") that does not raise exceptions when it is used in arithmetic. The opposite is a signaling NaN. See IEC 60559:1989.

The macros HUGE_VAL, HUGE_VALF, HUGE_VALL expand to constants of types double, float and long double, respectively, that represent a large positive value, possibly plus infinity.

CONFORMING TO

C99

AVAILABILITY

On a glibc system, the macro HUGE_VAL is always available. Availability of the NAN macro can be tested using #ifdef NAN, and similarly for INFINITY, HUGE_VALF, HUGE_VALL. They will be defined by <math.h> if _ISOC99_SOURCE or _GNU_SOURCE is defined, or __STDC_VERSION__ is defined and has a value not less than 199901L.

SEE ALSO

fpclassify(3), feature_test_macros(7)


getnetgrent (3)

 Continue to this page.


ldexpf (3)

 Continue to this page.


ldexpl (3)

 Continue to this page.


aio_write(3)

AIO_WRITE

Section: Linux Programmer's Manual (3)
Updated: 2003-11-14 Return to Main Contents

NAME

aio_write - asynchronous write

SYNOPSIS

#include <aio.h>

int aio_write(struct aiocb *aiocbp);

DESCRIPTION

The aio_write() function requests an asynchronous "n = write(fd, buf, count)" with fd, buf, count given by aiocbp->aio_fildes, aiocbp->aio_buf, aiocbp->aio_nbytes, respectively. The return status n can be retrieved upon completion using aio_return(3).

If O_APPEND is not set, the data is written starting at the absolute file offset aiocbp->aio_offset, regardless of the current file position. If O_APPEND is set, the data is written at the end of the file. After this request, the value of the current file position is unspecified.

The "asynchronous" means that this call returns as soon as the request has been enqueued; the write may or may not have completed when the call returns. One tests for completion using aio_error(3).

If _POSIX_PRIORITIZED_IO is defined, and this file supports it, then the asynchronous operation is submitted at a priority equal to that of the calling process minus aiocbp->aio_reqprio.

The field aiocbp->aio_lio_opcode is ignored.

No data is written to a regular file beyond its maximum offset.

RETURN VALUE

On success, 0 is returned. On error the request is not enqueued, -1 is returned, and errno is set appropriately. If an error is first detected later, it will be reported via aio_return(3) (returns status -1) and aio_error(3) (error status whatever one would have gotten in errno, such as EBADF).

ERRORS

EAGAIN
Out of resources.
EBADF
aio_fildes is not a valid file descriptor open for writing.
EFBIG
The file is a regular file, we want to write at least one byte, but the starting position is at or beyond the maximum offset for this file.
EINVAL
One or more of aio_offset, aio_reqprio, aio_nbytes are invalid.
ENOSYS
This function is not supported.

CONFORMING TO

POSIX.1-2001

NOTES

It is a good idea to zero out the control block before use. This control block must not be changed while the write operation is in progress. The buffer area being written out must not be accessed during the operation or undefined results may occur. The memory areas involved must remain valid.

SEE ALSO

aio_cancel(3), aio_error(3), aio_fsync(3), aio_read(3), aio_return(3), aio_suspend(3)


cexp2f (3)

 Continue to this page.


cexp2l (3)

 Continue to this page.


cbc_crypt (3)

 Continue to this page.


putgrent(3)

PUTGRENT

Section: Linux Programmer's Manual (3)
Updated: 2003-09-09 Return to Main Contents

NAME

putgrent - write a group database entry to a file

SYNOPSIS

#define _GNU_SOURCE
#include <grp.h>

int putgrent(const struct group *grp, FILE *fp);

DESCRIPTION

The putgrent() function is the counterpart for fgetgrent(3). The function writes the content of the provided struct group into the file pointed to by fp. The list of group members must be NULL terminated or NULL initialized.

The struct group is defined as follows:

struct group {
    char   *gr_name;      /* group name */
    char   *gr_passwd;    /* group password */
    gid_t   gr_gid;       /* group ID */
    char  **gr_mem;       /* group members */
};

RETURN VALUE

The function returns zero on success, and a non-zero value on error.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

fgetgrent(3), getgrent(3), group(5), feature_test_macros(7)


scalb(3)

SCALB

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

scalb, scalbf, scalbl, scalbn, scalbnf, scalbnl, scalbln, scalblnf, scalblnl - multiply floating-point number by integral power of radix

SYNOPSIS

#include <math.h>

double scalb(double x, double exp);
float scalbf(float x, double exp);
long double scalbl(long double x, double exp);

double scalbn(double x, int exp);
float scalbnf(float x, int exp);
long double scalbnl(long double x, int exp);

double scalbln(double x, long int exp);
float scalblnf(float x, long int exp);
long double scalblnl(long double x, long int exp);

Link with -lm.

DESCRIPTION

These functions multiply their first argument x by FLT_RADIX (probably 2) to the power exp.

If FLT_RADIX equals 2, then scalbn() is equivalent to ldexp(3).

The value of FLT_RADIX is found in <float.h>.

CONFORMING TO

The scalb() function is from 4.3BSD. The scalbn() and scalbln() functions are from C99. All three are in POSIX.1-2001. The scalb() function is marked obsolescent.

SEE ALSO

ldexp(3)


aio_read(3)

AIO_READ

Section: Linux Programmer's Manual (3)
Updated: 2003-11-14 Return to Main Contents

NAME

aio_read - asynchronous read

SYNOPSIS

#include <aio.h>

int aio_read(struct aiocb *aiocbp);

DESCRIPTION

The aio_read() function requests an asynchronous "n = read(fd, buf, count)" with fd, buf, count given by aiocbp->aio_fildes, aiocbp->aio_buf, aiocbp->aio_nbytes, respectively. The return status n can be retrieved upon completion using aio_return(3).

The data is read starting at the absolute file offset aiocbp->aio_offset, regardless of the current file position. After this request, the value of the current file position is unspecified.

The "asynchronous" means that this call returns as soon as the request has been enqueued; the read may or may not have completed when the call returns. One tests for completion using aio_error(3).

If _POSIX_PRIORITIZED_IO is defined, and this file supports it, then the asynchronous operation is submitted at a priority equal to that of the calling process minus aiocbp->aio_reqprio.

The field aiocbp->aio_lio_opcode is ignored.

No data is read from a regular file beyond its maximum offset.

RETURN VALUE

On success, 0 is returned. On error the request is not enqueued, -1 is returned, and errno is set appropriately. If an error is first detected later, it will be reported via aio_return(3) (returns status -1) and aio_error(3) (error status whatever one would have gotten in errno, such as EBADF).

ERRORS

EAGAIN
Out of resources.
EBADF
aio_fildes is not a valid file descriptor open for reading.
EINVAL
One or more of aio_offset, aio_reqprio, aio_nbytes are invalid.
ENOSYS
This function is not supported.
EOVERFLOW
The file is a regular file, we start reading before end-of-file and want at least one byte, but the starting position is past the maximum offset for this file.

CONFORMING TO

POSIX.1-2001

NOTES

It is a good idea to zero out the control block before use. This control block must not be changed while the read operation is in progress. The buffer area being read into must not be accessed during the operation or undefined results may occur. The memory areas involved must remain valid.

SEE ALSO

aio_cancel(3), aio_error(3), aio_fsync(3), aio_return(3), aio_suspend(3), aio_write(3)


dremf (3)

 Continue to this page.


dreml (3)

 Continue to this page.


scalbf (3)

 Continue to this page.


scalbl (3)

 Continue to this page.


scalbn (3)

 Continue to this page.


HUGE_VAL(3)

Status: 403 Forbidden HUGE_VAL(3)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man3/HUGE_VAL.3 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


endaliasent (3)

 Continue to this page.


wordexp(3)

WORDEXP

Section: Linux Programmer's Manual (3)
Updated: 2003-11-11 Return to Main Contents

NAME

wordexp, wordfree - perform word expansion like a posix-shell

SYNOPSIS

#include <wordexp.h>

int wordexp(const char *s, wordexp_t *p, int flags);

void wordfree(wordexp_t *p);

DESCRIPTION

The function wordexp() performs a shell-like expansion of the string s and returns the result in the structure pointed to by p. The data type wordexp_t is a structure that at least has the fields we_wordc, we_wordv, and we_offs. The field we_wordc is a size_t that gives the number of words in the expansion of s. The field we_wordv is a char ** that points to the array of words found. The field we_offs of type size_t is sometimes (depending on flags, see below) used to indicate the number of initial elements in the we_wordv array that should be filled with NULLs.

The function wordfree() frees the allocated memory again. More precisely, it does not free its argument, but it frees the array we_wordv and the strings that points to.

Example

First a small example. The output is approximately that of "ls [a-c]*.c".

#include <stdio.h>
#include <wordexp.h>

int
main(int argc, char **argv)
{
    wordexp_t p;
    char **w;
    int i;

    wordexp("[a-c]*.c", &p, 0);
    w = p.we_wordv;
    for (i=0; i<p.we_wordc; i++)
        printf("%s\n", w[i]);
    wordfree(&p);
    exit(EXIT_SUCCESS);
}

The string argument

Since the expansion is the same as the expansion by the shell (see sh(1)) of the parameters to a command, the string s must not contain characters that would be illegal in shell command parameters. In particular, there must not be any non-escaped newline or |, &, ;, <, >, (, ), {, } characters outside a command substitution or parameter substitution context.

If the argument s contains a word that starts with an unquoted comment character #, then it is unspecified whether that word and all following words are ignored, or the # is treated as a non-comment character.

The expansion

The expansion done consists of the following stages: tilde expansion (replacing ~user by user's home directory), variable substitution (replacing $FOO by the value of the environment variable FOO), command substitution (replacing $(command) or `command` by the output of command), arithmetic expansion, field splitting, wildcard expansion, quote removal.

The result of expansion of special parameters ($@, $*, $#, $?, $-, $$, $!, $0) is unspecified.

Field splitting is done using the environment variable $IFS. If it is not set, the field separators are space, tab and newline.

The output array

The array we_wordv contains the words found, followed by a NULL.

The flags argument

The flag argument is a bitwise inclusive OR of the following values:
WRDE_APPEND
Append the words found to the array resulting from a previous call.
WRDE_DOOFFS
Insert we_offs initial NULLs in the array we_wordv. (These are not counted in the returned we_wordc.)
WRDE_NOCMD
Don't do command substitution.
WRDE_REUSE
The parameter p resulted from a previous call to wordexp(), and wordfree() was not called. Reuse the allocated storage.
WRDE_SHOWERR
Normally during command substitution stderr is redirected to /dev/null. This flag specifies that stderr is not to be redirected.
WRDE_UNDEF
Consider it an error if an undefined shell variable is expanded.

RETURN VALUE

In case of success 0 is returned. In case of error one of the following five values is returned.
WRDE_BADCHAR
Illegal occurrence of newline or one of |, &, ;, <, >, (, ), {, }.
WRDE_BADVAL
An undefined shell variable was referenced, and the WRDE_UNDEF flag told us to consider this an error.
WRDE_CMDSUB
Command substitution occurred, and the WRDE_NOCMD flag told us to consider this an error.
WRDE_NOSPACE
Out of memory.
WRDE_SYNTAX
Shell syntax error, such as unbalanced parentheses or unmatched quotes.

CONFORMING TO

POSIX.1-2001

SEE ALSO

fnmatch(3), glob(3)


sgetspent (3)

 Continue to this page.


sgetspent_r (3)

 Continue to this page.


gethostent_r (3)

 Continue to this page.


setaliasent(3)

SETALIASENT

Section: Linux Programmer's Manual (3)
Updated: 2003-09-09 Return to Main Contents

NAME

setaliasent, endaliasent, getaliasent, getaliasent_r, getaliasbyname, getaliasbyname_r - read an alias entry

SYNOPSIS

#include <aliases.h>

void setaliasent(void);

void endaliasent(void);

struct aliasent *getaliasent(void);

int getaliasent_r(struct aliasent *result,
char *buffer, size_t buflen, struct aliasent **res);

struct aliasent *getaliasbyname(const char *name);

int getaliasbyname_r(const char *name, struct aliasent *result,
char *buffer, size_t buflen, struct aliasent **res);

DESCRIPTION

One of the databases available with the Name Service Switch (NSS) is the aliases database, that contains mail aliases. (To find out which databases are supported, try getent --help.) Six functions are provided to access the aliases database.

The getaliasent() function returns a pointer to a structure containing the group information from the aliases database. The first time it is called it returns the first entry; thereafter, it returns successive entries.

The setaliasent() function rewinds the file pointer to the beginning of the aliases database.

The endaliasent() function closes the aliases database.

getaliasent_r() is the reentrant version of the previous function. The requested structure is stored via the first argument but the programmer needs to fill the other arguments also. Not providing enough space causes the function to fail.

The function getaliasbyname() takes the name argument and searches the aliases database. The entry is returned as a pointer to a struct aliasent.

getaliasbyname_r() is the reentrant version of the previous function. The requested structure is stored via the second argument but the programmer needs to fill the other arguments also. Not providing enough space causes the function to fail.

The struct aliasent is defined in <aliases.h>:

struct aliasent {
    char    *alias_name;              /* alias name */
    size_t   alias_members_len;
    char   **alias_members;          /* alias name list */
    int      alias_local;
};

RETURN VALUE

The functions getaliasent_r() and getaliasbyname_r() return a non-zero value on error.

FILES

The default alias database is the file /etc/aliases. This can be changed in the /etc/nsswitch.conf file.

CONFORMING TO

These routines are glibc-specific. The NeXT has similar routines
#include <aliasdb.h>
void alias_setent(void);
void alias_endent(void);
alias_ent *alias_getent(void);
alias_ent *alias_getbyname(char *name);

EXAMPLE

The following example compiles with gcc example.c -o example. It will dump all names in the alias database.

#include <aliases.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int
main(void)
{
    struct aliasent *al;
    setaliasent();
    for (;;) {
        al = getaliasent();
        if (al == NULL)
            break;
        printf("Name: %s\n", al->alias_name);
    }
    if (errno) {
        perror("reading alias");
        exit(EXIT_FAILURE);
    }
    endaliasent();
    exit(EXIT_SUCCESS);
}

SEE ALSO

getgrent(3), getpwent(3), getspent(3), aliases(5)


sincos(3)

SINCOS

Section: Linux Programmer's Manual (3)
Updated: 2004-10-05 Return to Main Contents

NAME

sincos, sincosf, sincosl - calculate sin and cos simultaneously

SYNOPSIS

#define _GNU_SOURCE
#include <math.h>

void sincos(double x, double *sin, double *cos);

void sincosf(float x, float *sin, float *cos);

void sincosl(long double x, long double *sin, long double *cos);

Link with -lm.

DESCRIPTION

Several applications need sine and cosine of the same angle x. This function computes both at the same time, and stores the results via the given pointers.

CONFORMING TO

This function is a GNU extension.

SEE ALSO

cos(3), sin(3), tan(3), feature_test_macros(7)


ualarm(3)

UALARM

Section: Linux Programmer's Manual (3)
Updated: 2003-07-24 Return to Main Contents

NAME

ualarm - schedule signal after given number of microseconds

SYNOPSIS

#define _XOPEN_SOURCE 500     /* Or: #define _BSD_SOURCE */
#include <unistd.h>

useconds_t ualarm(useconds_t usecs, useconds_t interval);

DESCRIPTION

The ualarm() function causes the signal SIGALRM to be sent to the invoking process after (not less than) usecs microseconds. The delay may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.

Unless caught or ignored, the SIGALRM signal will terminate the process.

If the interval argument is non-zero, further SIGALRM signals will be sent every interval microseconds after the first.

RETURN VALUE

This function returns the number of microseconds remaining for any alarm that was previously set, or 0 if no alarm was pending.

ERRORS

EINTR
Interrupted by a signal.
EINVAL
usecs or interval is not smaller than 1000000. (On systems where that is considered an error.)

CONFORMING TO

4.3BSD, POSIX.1-2001. POSIX.1-2001 marks ualarm() as obsolete. 4.3BSD, SUSv2, and POSIX do not define any errors.

NOTES

The type useconds_t is an unsigned integer type capable of holding integers in the range [0,1000000]. On the original BSD implementation, and in glibc before version 2.1, the arguments to ualarm() were instead typed as unsigned int. Programs will be more portable if they never mention useconds_t explicitly.

The interaction of this function with
other timer functions such as
alarm(2),

sleep(3),

nanosleep(2),

setitimer(2),

timer_create(3),

timer_delete(3),

timer_getoverrun(3),

timer_gettime(3),

timer_settime(3),

usleep(3)

is unspecified.

This function is obsolete. Use setitimer(2) or POSIX interval timers (timer_create(3), etc.) instead.

SEE ALSO

alarm(2), getitimer(2), nanosleep(2), select(2), setitimer(2), usleep(3), feature_test_macros(7), time(7)


strcasestr (3)

 Continue to this page.


getnetgrent_r (3)

 Continue to this page.


aio_cancel(3)

AIO_CANCEL

Section: Linux Programmer's Manual (3)
Updated: 2003-11-14 Return to Main Contents

NAME

aio_cancel - cancel an outstanding asynchronous I/O request

SYNOPSIS

#include <aio.h>

int aio_cancel(int fd, struct aiocb *aiocbp);

DESCRIPTION

The aio_cancel() function attempts to cancel outstanding asynchronous I/O requests for the file descriptor fd. If aiocbp is NULL, all such requests are canceled. Otherwise, only the request described by the control block pointed to by aiocbp is canceled.

Normal asynchronous notification occurs for canceled requests. The request return status is set to -1, and the request error status is set to ECANCELED. The control block of requests that cannot be canceled is not changed.

If aiocbp is not NULL, and fd differs from the file descriptor with which the asynchronous operation was initiated, unspecified results occur.

Which operations are cancellable is implementation-defined.

RETURN VALUE

This function returns AIO_CANCELED if all requests were successfully canceled. It returns AIO_NOTCANCELED when at least one of the requests specified was not canceled because it was in progress. In this case one may check the status of individual requests using aio_error(3). This function returns AIO_ALLDONE when all requests had been completed already before this call. When some error occurs, -1 is returned, and errno is set appropriately.

ERRORS

EBADF
fd is not a valid file descriptor.

CONFORMING TO

POSIX.1-2001

SEE ALSO

aio_error(3), aio_fsync(3), aio_read(3), aio_return(3), aio_suspend(3), aio_write(3)


getaliasbyname (3)

 Continue to this page.


rtime(3)

RTIME

Section: Linux Programmer's Manual (3)
Updated: 2003-04-04 Return to Main Contents

NAME

rtime - get time from a remote machine

SYNOPSIS

#include <rpc/des_crypt.h>

int rtime(struct sockaddr_in *addrp, struct rpc_timeval *timep,
          struct rpc_timeval *timeout);

DESCRIPTION

This function uses the Time Server Protocol as described in RFC 868 to obtain the time from a remote machine.

The Time Server Protocol gives the time in seconds since midnight 1900-01-01, and this function subtracts the appropriate constant in order to convert the result to seconds since midnight 1970-01-01, the Unix epoch.

When timeout is non-NULL, the udp/time socket (port 37) is used. Otherwise, the tcp/time socket (port 37) is used.

RETURN VALUE

On success, 0 is returned, and the obtained 32-bit time value is stored in timep->tv_sec. In case of error -1 is returned, and errno is set appropriately.

ERRORS

All errors for underlying functions (sendto(2), poll(2), recvfrom(2), connect(2), read(2)) can occur. Moreover:
EIO
The number of returned bytes is not 4.
ETIMEDOUT
The waiting time as defined in timeout has expired.

NOTES

Only IPV4 is supported.

Some in.timed versions only support TCP. Try the above example program with use_tcp set to 1.

Libc5 uses the prototype
int rtime(struct sockaddr_in *, struct timeval *, struct timeval *);
and requires <sys/time.h> instead of <rpc/auth_des.h>.

BUGS

rtime() in glibc <= 2.2.5 does not work properly on 64bit machines.

EXAMPLE

This example requires that port 37 is up and open. You may check that the time entry within /etc/inetd.conf is not commented out.
The program connects to a computer called 'linux'. Using 'localhost' does not work. The result is the localtime of the computer 'linux'.

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <rpc/auth_des.h>
#include <netdb.h>

int use_tcp = 0;
char *servername = "linux";

int
main(void)
{
    struct sockaddr_in name;
    struct rpc_timeval time1 = {0,0};
    struct rpc_timeval timeout = {1,0};
    struct hostent *hent;
    int ret;

    memset((char *) &name, 0, sizeof(name));
    sethostent(1);
    hent = gethostbyname(servername);
    memcpy((char *) &name.sin_addr, hent->h_addr, hent->h_length);

    ret = rtime(&name, &time1, use_tcp ? NULL : &timeout);
    if (ret < 0)
        perror("rtime error");
    else
        printf("%s\n", ctime((time_t *) &time1.tv_sec));

    exit(EXIT_SUCCESS);
}

SEE ALSO

netdate(1), ntpdate(1), rdate(1), inetd(8)


sinhf (3)

 Continue to this page.


sinhl (3)

 Continue to this page.


getutid_r (3)

 Continue to this page.


cacosf (3)

 Continue to this page.


cacosh(3)

CACOSH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cacosh, cacoshf, cacoshl - complex arc hyperbolic cosine

SYNOPSIS

#include <complex.h>

double complex cacosh(double complex z);
float complex cacoshf(float complex z);
long double complex cacoshl(long double complex z);

Link with -lm.

DESCRIPTION

The cacosh() function calculates the complex acosh(). If y = cacosh(z), then z = ccosh(y). The imaginary part of y is chosen in the interval [-pi,pi]. The real part of y is chosen non-negative.

One has: cacosh(z) = (0.5) * clog((1 + z) / (1 - z)).

CONFORMING TO

C99

SEE ALSO

acosh(3), cabs(3), cimag(3), complex(7)


cacosl (3)

 Continue to this page.


isunordered (3)

 Continue to this page.


getaliasent_r (3)

 Continue to this page.


fdimf (3)

 Continue to this page.


fdiml (3)

 Continue to this page.


significandf (3)

 Continue to this page.


significandl (3)

 Continue to this page.


isgreaterequal (3)

 Continue to this page.


log2f (3)

 Continue to this page.


log2l (3)

 Continue to this page.


tanhf (3)

 Continue to this page.


tanhl (3)

 Continue to this page.


ecb_crypt (3)

 Continue to this page.


logbf (3)

 Continue to this page.


logbl (3)

 Continue to this page.


login(3)

LOGIN

Section: Linux Programmer's Manual (3)
Updated: 2004-05-06 Return to Main Contents

NAME

login, logout - write utmp and wtmp entries

SYNOPSIS

#include <utmp.h>

void login(const struct utmp *ut);
int logout(const char *ut_line);

Link with -lutil.

DESCRIPTION

The utmp file records who is currently using the system. The wtmp file records all logins and logouts. See utmp(5).

The function login() takes the supplied struct utmp ut, and writes it to both utmp and wtmp file.

The function logout() clears the entry in the utmp file again.

GNU Details

More precisely, login() takes the argument ut struct, fills the field ut->ut_type (if there is such a field) with the value USER_PROCESS, and fills the field ut->ut_pid (if there is such a field) with the process ID of the calling process. Then it tries to fill the field ut->ut_line. It takes the first of stdin, stdout, stderr that is a tty, and stores the corresponding pathname minus a possible leading /dev/ into this field, and then writes the struct to the utmp file. On the other hand, if no tty name was found, this field is filled with "???" and the struct is not written to the utmp file. After this, the struct is written to the wtmp file.

The logout() function searches the utmp file for an entry matching the ut_line argument. If a record is found, it is updated by zeroing out the ut_name and ut_host fields, updating the ut_tv timestamp field and setting ut_type (if there is such a field) to DEAD_PROCESS.

RETURN VALUE

The logout() function returns 1 if the entry was successfully written to the database, or 0 if an error occurred.

FILES

/var/run/utmp
user accounting database, configured through _PATH_UTMP in <paths.h>
/var/log/wtmp
user accounting log file, configured through _PATH_WTMP in <paths.h>

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs.

NOTES

Note that the member ut_user of struct utmp is called ut_name in BSD. Therefore, ut_name is defined as an alias for ut_user in <utmp.h>.

SEE ALSO

getutent(3), utmp(5)


getspent_r (3)

 Continue to this page.


strtoimax(3)

STRTOIMAX

Section: Linux Programmer's Manual (3)
Updated: 2003-11-28 Return to Main Contents

NAME

strtoimax, strtoumax - convert string to integer

SYNOPSIS

#include <inttypes.h>

intmax_t strtoimax(const char *nptr, char **endptr, int base);

uintmax_t strtoumax(const char *nptr, char **endptr, int base);

DESCRIPTION

These functions are just like strtol(3) and strtoul(3), except that they return a value of type intmax_t and uintmax_t, respectively.

RETURN VALUE

On success, the converted value is returned. If nothing was found to convert, zero is returned. On overflow or underflow INTMAX_MAX or INTMAX_MIN or UINTMAX_MAX is returned, and errno is set to ERANGE.

CONFORMING TO

C99, POSIX.1-2001.

SEE ALSO

imaxabs(3), imaxdiv(3), strtol(3), strtoul(3), wcstoimax(3)


erfcf (3)

 Continue to this page.


erfcl (3)

 Continue to this page.


getaliasent (3)

 Continue to this page.


ffsll (3)

 Continue to this page.


endspent (3)

 Continue to this page.


seed48_r (3)

 Continue to this page.


getaliasbyname_r (3)

 Continue to this page.


pow10f (3)

 Continue to this page.


pow10l (3)

 Continue to this page.


fgetgrent_r (3)

 Continue to this page.


finitef (3)

 Continue to this page.


finitel (3)

 Continue to this page.


cacoshf (3)

 Continue to this page.


cacoshl (3)

 Continue to this page.


gethostent (3)

 Continue to this page.


getspent (3)

 Continue to this page.


sqrtf (3)

 Continue to this page.


sqrtl (3)

 Continue to this page.


getspnam(3)

GETSPNAM

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

getspnam, getspnam_r, getspent, getspent_r, setspent, endspent, fgetspent, fgetspent_r, sgetspent, sgetspent_r, putspent, lckpwdf, ulckpwdf - get shadow password file entry

SYNOPSIS

/* General shadow password file API */

#include <shadow.h>

struct spwd *getspnam(const char *name);

struct spwd *getspent(void);

void setspent(void);

void endspent(void);

struct spwd *fgetspent(FILE *fp);

struct spwd *sgetspent(const char *s);

int putspent(struct spwd *p, FILE *fp);

int lckpwdf(void);

int ulckpwdf(void);

/* GNU extension */

#define _SVID_SOURCE    /* or _BSD_SOURCE */

#include <shadow.h>

int getspent_r(struct spwd *spbuf,

        char *buf, size_t buflen, struct spwd **spbufp);

int getspnam_r(const char *name, struct spwd *spbuf,

        char *buf, size_t buflen, struct spwd **spbufp);

int fgetspent_r(FILE *fp, struct spwd *spbuf,

        char *buf, size_t buflen, struct spwd **spbufp);

int sgetspent_r(const char *s, struct spwd *spbuf,

        char *buf, size_t buflen, struct spwd **spbufp);

DESCRIPTION

Long ago it was considered safe to have encrypted passwords openly visible in the password file. When computers got faster and people got more security-conscious, this was no longer acceptable. Julianne Frances Haugh implemented the shadow password suite that keeps the encrypted passwords in the shadow password database (e.g., the local shadow password file /etc/shadow, NIS, and LDAP), readable only by root.

The functions described below resemble those for the traditional password database (e.g., see getpwnam(3) and getpwent(3)).

The getspnam() function returns a pointer to a structure containing the broken-out fields of the record in the shadow password database that matches the user name name.

The getspent() function returns a pointer to the next entry in the shadow password database. The position in the input stream is initialized by setspent(). When done reading, the program may call endspent() so that resources can be deallocated.

The fgetspent() function is similar to getspent() but uses the supplied stream instead of the one implicitly opened by setspent().

The sgetspent() function parses the supplied string s into a struct spwd.

The putspent() function writes the contents of the supplied struct spwd *p as a text line in the shadow password file format to the stream fp. String entries with value NULL and numerical entries with value -1 are written as an empty string.

The lckpwdf() function is intended to protect against multiple simultaneous accesses of the shadow password database. It tries to acquire a lock, and returns 0 on success, or -1 on failure (lock not obtained within 15 seconds). The ulckpwdf() function releases the lock again. Note that there is no protection against direct access of the shadow password file. Only programs that use lckpwdf() will notice the lock.

These were the functions that formed the original shadow API. They are widely available.

Reentrant versions

Analogous to the reentrant functions for the password database, glibc also has reentrant functions for the shadow password database. The getspnam_r() function is like getspnam() but stores the retrieved shadow password structure in the space pointed to by spbuf. This shadow password structure contains pointers to strings, and these strings are stored in the buffer buf of size buflen. A pointer to the result (in case of success) or NULL (in case no entry was found or an error occurred) is stored in *spbufp.

The functions getspent_r(), fgetspent_r(), and sgetspent_r() are similarly analogous to their non-reentrant counterparts.

Some non-glibc systems also have functions with these names, often with different prototypes.

Structure

The shadow password structure is defined in <shadow.h> as follows:

struct spwd {
    char *sp_namp;         /* Login name */
    char *sp_pwdp;         /* Encrypted password */
    long  sp_lstchg;       /* Date of last change */
    long  sp_min;          /* Min #days between changes */
    long  sp_max;          /* Max #days between changes */
    long  sp_warn;         /* #days before pwd expires
                              to warn user to change it */
    long  sp_inact;        /* #days after pwd expires
                              until account is disabled */
    long  sp_expire;       /* #days since 1970-01-01
                              until account is disabled */
    unsigned long sp_flag; /* Reserved */
};

RETURN VALUE

The functions that return a pointer return NULL if no more entries are available or if an error occurs during processing. The functions which have int as the return value return 0 for success and -1 for failure.

For the non-reentrant functions, the return value may point to static area, and may be overwritten by subsequent calls to these functions.

The reentrant functions return zero on success. In case of error, an error number is returned.

ERRORS

ERANGE
Supplied buffer is too small.

FILES

/etc/shadow
local shadow password database file
/etc/.pwd.lock
lock file

The include file <paths.h> defines the constant _PATH_SHADOW to the pathname of the shadow password file.

CONFORMING TO

The shadow password database and its associated API are not specified in POSIX.1-2001. However, many other systems provide a similar API.

SEE ALSO

getgrnam(3), getpwnam(3), getpwnam_r(3), shadow(5), feature_test_macros(7)


scalbln (3)

 Continue to this page.


scalbnf (3)

 Continue to this page.


scalbnl (3)

 Continue to this page.


fmaxf (3)

 Continue to this page.


fmaxl (3)

 Continue to this page.


cabs(3)

CABS

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cabs, cabsf, cabsl - absolute value of a complex number

SYNOPSIS

#include <complex.h>

double cabs(double complex z);
float cabsf(float complex z);
long double cabsl(long double complex z);

Link with -lm.

DESCRIPTION

The cabs() function returns the absolute value of the complex number z. The result is a real number.

CONFORMING TO

C99

NOTES

The function is actually an alias for hypot(a,b) = sqrt(a*a+b*b).

SEE ALSO

abs(3), cimag(3), hypot(3), complex(7)


carg(3)

CARG

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

carg, cargf, cargl - calculate the argument

SYNOPSIS

#include <complex.h>

double carg(double complex z);
float cargf(float complex z);
long double cargl(long double complex z);

Link with -lm.

DESCRIPTION

A complex number can be described by two real coordinates. One may use rectangular coordinates and gets z = x+I*y, where x = creal(z) and y = cimag(z).

Or one may use polar coordinates and gets z = r*cexp(I*a)
where r = cabs(z) is the "radius", the "modulus", the absolute value of z,
and a = carg(z) is the "phase angle", the argument of z.

One has tan(carg(z)) = cimag(z) / creal(z).

RETURN VALUE

The return value is the range of [-pi,pi].

CONFORMING TO

C99

SEE ALSO

cabs(3), complex(7)


ccos(3)

CCOS

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

ccos, ccosf, ccosl - complex cosine function

SYNOPSIS

#include <complex.h>

double complex ccos(double complex z);
float complex ccosf(float complex z);
long double complex ccosl(long double complex z);

Link with -lm.

DESCRIPTION

The complex cosine function ccos(z) is defined as (exp(i*z)+exp(-i*z))/2.

CONFORMING TO

C99

SEE ALSO

cabs(3), csin(3), ctan(3), complex(7)


cerf(3)

CERF

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cerf, cerff, cerfl, cerfc, cerfcf, cerfcl - complex error function

SYNOPSIS

#include <complex.h>

double complex cerf(double complex z);
float complex cerff(float complex z);
long double complex cerfl(long double complex z);

double complex cerfc(double complex z);
float complex cerfcf(float complex z);
long double complex cerfcl(long double complex z);

Link with -lm.

DESCRIPTION

The function cerf() is the complex version of the error function. erf(z) = 2/sqrt(pi) * integral from 0 to z of exp(-t*t) dt. The function cerfc() is defined as cerfc(z) = 1-cerf(z).

CONFORMING TO

The function names are reserved for future use in C99.

AVAILABILITY

Not yet in glibc, as at version 2.4.

SEE ALSO

erf(3), complex(7)


fminf (3)

 Continue to this page.


fminl (3)

 Continue to this page.


cexp(3)

CEXP

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cexp, cexpf, cexpl - complex exponential function

SYNOPSIS

#include <complex.h>

double complex cexp(double complex z);
float complex cexpf(float complex z);
long double complex cexpl(long double complex z);

Link with -lm.

DESCRIPTION

The function calculates e (2.71828..., the base of natural logarithms) raised to the power of z.

One has cexp(I * z) = ccos(z) + I * csin(z).

CONFORMING TO

C99

SEE ALSO

cabs(3), clog(3), cpow(3), complex(7)


xcrypt(3)

XCRYPT

Section: Linux Programmer's Manual (3)
Updated: 2003-04-04 Return to Main Contents

NAME

xencrypt, xdecrypt, passwd2des - RFS password encryption

SYNOPSIS

#include <rpc/des_crypt.h>

void passwd2des(char *passwd, char *key);

int xencrypt(char *secret, char *passwd);

int xdecrypt(char *secret, char *passwd);

DESCRIPTION

The function passwd2des() takes a character string passwd of arbitrary length and fills a character array key of length 8. The array key is suitable for use as DES key. It has odd parity set in bit 0 of each byte. Both other functions described here use this function to turn their argument passwd into a DES key.

The xencrypt() function takes the ASCII character string secret given in hex, which must have a length that is a multiple of 16, encrypts it using the DES key derived from passwd by passwd2des(), and outputs the result again in secret as a hex string of the same length.

The xdecrypt() function performs the converse operation.

RETURN VALUE

The functions xencrypt() and xdecrypt() return 1 on success and 0 on error.

VERSIONS

These routines are present in libc 4.6.27 and later, and in glibc 2.1 and later.

BUGS

The prototypes are missing from the abovementioned include file.

SEE ALSO

cbc_crypt(3)


exp10(3)

EXP10

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

exp10, exp10f, exp10l - base-10 exponential function

SYNOPSIS

#define _GNU_SOURCE

#include <math.h>

double exp10(double x);

float exp10f(float x);

long double exp10l(long double x);

Link with -lm.

DESCRIPTION

The exp10() function returns the value of 10 raised to the power of x.

CONFORMING TO

The function is a GNU extension.

SEE ALSO

cbrt(3), exp(3), exp2(3), sqrt(3), feature_test_macros(7)


gmtime_r (3)

 Continue to this page.


exp2f (3)

 Continue to this page.


exp2l (3)

 Continue to this page.


fmodf (3)

 Continue to this page.


fmodl (3)

 Continue to this page.


clog(3)

CLOG

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

clog, clogf, clogl - natural logarithm of a complex number

SYNOPSIS

#include <complex.h>

double complex clog(double complex z);
float complex clogf(float complex z);
long double complex clogl(long double complex z);

Link with -lm.

DESCRIPTION

The logarithm clog() is the inverse function of the exponential cexp(). Thus, if y = clog(z), then z = cexp(y). The imaginary part of y is chosen in the interval [-pi,pi].

One has clog(z) = log(cabs(z)) + I * carg(z).

Note that z close to zero will cause an overflow.

CONFORMING TO

C99

SEE ALSO

cabs(3), cexp(3), clog10(3), complex(7)


conj(3)

CONJ

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

conj, conjf, conjl - calculate the complex conjugate

SYNOPSIS

#include <complex.h>

double complex conj(double complex z);
float complex conjf(float complex z);
long double complex conjl(long double complex z);

Link with -lm.

DESCRIPTION

The conj() function returns the complex conjugate value of z. That is the value obtained by changing the sign of the imaginary part.

One has cabs(z) = csqrt(z * conj(z)).

CONFORMING TO

C99

SEE ALSO

cabs(3), sqrt(3), complex(7)


cosf (3)

 Continue to this page.


cosl (3)

 Continue to this page.


cpow(3)

CPOW

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cpow, cpowf, cpowl - complex power function

SYNOPSIS

#include <complex.h>

double complex cpow(double complex x, complex double z);
float complex cpowf(float complex x, complex float z);
long double complex cpowl(long double complex x, complex long double z);

Link with -lm.

DESCRIPTION

The function calculates x raised to the power z. (With a branch cut for x along the negative real axis.)

CONFORMING TO

C99

SEE ALSO

cabs(3), pow(3), complex(7)


dladdr (3)

 Continue to this page.


csin(3)

CSIN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

csin, csinf, csinl - complex sine function

SYNOPSIS

#include <complex.h>

double complex csin(double complex z);
float complex csinf(float complex z);
long double complex csinl(long double complex z);

Link with -lm.

DESCRIPTION

The complex sine function csin(z) is defined as (exp(i*z)-exp(-i*z))/(2*i).

CONFORMING TO

C99

SEE ALSO

cabs(3), csin(3), ctan(3), complex(7)


ctan(3)

CTAN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

ctan, ctanf, ctanl - complex tangent function

SYNOPSIS

#include <complex.h>

double complex ctan(double complex z);
float complex ctanf(float complex z);
long double complex ctanl(long double complex z);

Link with -lm.

DESCRIPTION

The complex tangent function ctan(z) is defined mathematically as csin(z) / ccos(z).

CONFORMING TO

C99

SEE ALSO

cabs(3), ccos(3), csin(3), complex(7)


getspnam_r (3)

 Continue to this page.


setspent (3)

 Continue to this page.


HUGE_VALF(3)

Status: 403 Forbidden HUGE_VALF(3)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man3/HUGE_VALF.3 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


HUGE_VALL(3)

Status: 403 Forbidden HUGE_VALL(3)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man3/HUGE_VALL.3 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


modff (3)

 Continue to this page.


modfl (3)

 Continue to this page.


fdim(3)

FDIM

Section: Linux Programmer's Manual (3)
Updated: 2003-07-24 Return to Main Contents

NAME

fdim, fdimf, fdiml - positive difference

SYNOPSIS

#include <math.h>

double fdim(double x, double y);
float fdimf(float x, float y);
long double fdiml(long double x, long double y);

Compile with -std=c99; link with -lm.

DESCRIPTION

These functions return max(x-y,0). If x or y or both are NaN, Nan is returned.

CONFORMING TO

C99

SEE ALSO

fmax(3)


erff (3)

 Continue to this page.


erfl (3)

 Continue to this page.


ffsl (3)

 Continue to this page.


fmaf (3)

 Continue to this page.


fmal (3)

 Continue to this page.


fmax(3)

FMAX

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

fmax, fmaxf, fmaxl - find maximum value

SYNOPSIS

#include <math.h>

double fmax(double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);

Compile with -std=c99; link with -lm.

DESCRIPTION

Find the larger value of x and y.

CONFORMING TO

C99

SEE ALSO

fmin(3)


rand_r (3)

 Continue to this page.


fmin(3)

FMIN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

fmin, fminf, fminl - find minimum value

SYNOPSIS

#include <math.h>

double fmin(double x, double y);
float fminf(float x, float y);
long double fminl(long double x, long double y);

Compile with -std=c99; link with -lm.

DESCRIPTION

Find the lesser value of x and y.

CONFORMING TO

C99

SEE ALSO

fmax(3)


exp2(3)

EXP2

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

exp2, exp2f, exp2l - base-2 exponential function

SYNOPSIS

#include <math.h>

double exp2(double x);

float exp2f(float x);

long double exp2l(long double x);

Compile with -std=c99; link with -lm.

DESCRIPTION

The exp2() function returns the value of 2 raised to the power of x.

CONFORMING TO

SVr4, POSIX.1-2001, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

cbrt(3), cexp2(3), exp(3), exp10(3), sqrt(3)


expf (3)

 Continue to this page.


expl (3)

 Continue to this page.


lseek64(3)

LSEEK64

Section: Linux Programmer's Manual (3)
Updated: 2004-12-11 Return to Main Contents

NAME

lseek64 - reposition 64-bit read/write file offset

SYNOPSIS

#define _LARGEFILE64_SOURCE
#include <sys/types.h>
#include <unistd.h>

off64_t lseek64(int fd, off64_t offset, int whence);

DESCRIPTION

The lseek(2) family of functions reposition the offset of the open file associated with the file descriptor fd to offset bytes relative to the start, current position, or end of the file, when whence has the value SEEK_SET, SEEK_CUR, or SEEK_END, respectively.

For more details, return value, and errors, see lseek(2).

Four interfaces are available:
lseek(2),

lseek64(),

llseek(2),

and the raw system call
_llseek(2).

lseek

Prototype:

off_t lseek(int fd, off_t offset, int whence);

The library routine lseek() uses the type off_t. This is a 32-bit signed type on 32-bit architectures, unless one compiles with

#define _FILE_OFFSET_BITS 64
in which case it is a 64-bit signed type.

lseek64

Prototype:

off64_t lseek64(int fd, off64_t offset, int whence);

The library routine lseek64() uses a 64-bit type even when off_t is a 32-bit type. Its prototype (and the type off64_t) is available only when one compiles with

#define _LARGEFILE64_SOURCE
The function lseek64() is available since glibc 2.1, and is defined to be an alias for llseek().

llseek

Prototype:

loff_t llseek(int fd, loff_t offset, int whence);

The type loff_t is a 64-bit signed type. The library routine llseek() is available in libc5 and glibc and works without special defines. Its prototype was given in <unistd.h> with libc5, but glibc does not provide a prototype. This is bad, since a prototype is needed. Users should add the above prototype, or something equivalent, to their own source. When users complained about data loss caused by a miscompilation of e2fsck(8), glibc 2.1.3 added the link-time warning

"the `llseek' function may be dangerous; use `lseek64' instead."

This makes this function unusable if one desires a warning-free compilation.

_llseek

All the above functions are implemented in terms of this system call. The prototype is:

int _llseek(int fd, off_t offset_hi, off_t offset_lo,
loff_t *result, int whence);

For more details, see llseek(2).

SEE ALSO

llseek(2), lseek(2), feature_test_macros(7)


des_setparity (3)

 Continue to this page.


casinf (3)

 Continue to this page.


casinh(3)

CASINH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

casinh, casinhf, casinhl - complex arc sine hyperbolic

SYNOPSIS

#include <complex.h>

double complex casinh(double complex z);
float complex casinhf(float complex z);
long double complex casinhl(long double complex z);

Link with -lm.

DESCRIPTION

The casinh() function calculates the complex asinh(). If y = casinh(z), then z = csinh(y). The imaginary part of y is chosen in the interval [-pi/2,pi/2].

One has casinh(z) = clog(z + csqrt(z * z + 1)).

CONFORMING TO

C99

SEE ALSO

asinh(3), cabs(3), cimag(3), complex(7)


casinl (3)

 Continue to this page.


clog10f (3)

 Continue to this page.


clog10l (3)

 Continue to this page.


catanf (3)

 Continue to this page.


catanh(3)

CATANH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

catanh, catanhf, catanhl - complex arc tangents hyperbolic

SYNOPSIS

#include <complex.h>

double complex catanh(double complex z);
float complex catanhf(float complex z);
long double complex catanhl(long double complex z);

Link with -lm.

DESCRIPTION

The catanh() function calculates the complex atanh(). If y = catanh(z), then z = ctanh(y). The imaginary part of y is chosen in the interval [-pi/2,pi/2].

One has catanh(z) = 0.5 * clog((1 + z) / (1 - z)).

CONFORMING TO

C99

SEE ALSO

atanh(3), cabs(3), cimag(3), complex(7)


catanl (3)

 Continue to this page.


nrand48_r (3)

 Continue to this page.


strtoumax (3)

 Continue to this page.


asctime_r (3)

 Continue to this page.


va_copy (3)

 Continue to this page.


ulckpwdf (3)

 Continue to this page.


aio_error(3)

AIO_ERROR

Section: Linux Programmer's Manual (3)
Updated: 2003-11-14 Return to Main Contents

NAME

aio_error - get error status of asynchronous I/O operation

SYNOPSIS

#include <aio.h>

int aio_error(const struct aiocb *aiocbp);

DESCRIPTION

The aio_error() function returns the error status for the asynchronous I/O request with control block pointed to by aiocbp.

RETURN VALUE

This function returns EINPROGRESS if the request has not been completed yet. It returns ECANCELED if the request was canceled. It returns 0 if the request completed successfully. Otherwise an error value is returned, the same value that would have been stored in the errno variable in case of a synchronous read, write, fsync, or fdatasync request. On error, the error value is returned.

ERRORS

EINVAL
aiocbp does not point at a control block for an asynchronous I/O request of which the return status (see aio_return(3)) has not been retrieved yet.

CONFORMING TO

POSIX.1-2001

SEE ALSO

aio_cancel(3), aio_fsync(3), aio_read(3), aio_return(3), aio_suspend(3), aio_write(3)


acoshf (3)

 Continue to this page.


acoshl (3)

 Continue to this page.


jrand48_r (3)

 Continue to this page.


wcstoimax(3)

WCSTOIMAX

Section: Linux Programmer's Manual (3)
Updated: 2003-11-01 Return to Main Contents

NAME

wcstoimax, wcstoumax - convert wide-character string to integer

SYNOPSIS

#include <stddef.h>

#include <inttypes.h>

intmax_t wcstoimax(const wchar_t *nptr, wchar_t **endptr, int base);

uintmax_t wcstoumax(const wchar_t *nptr, wchar_t **endptr, int base);

DESCRIPTION

These functions are just like wcstol(3) and wcstoul(3), except that they return a value of type intmax_t and uintmax_t, respectively.

CONFORMING TO

C99.

SEE ALSO

imaxabs(3), imaxdiv(3), strtoimax(3), strtoumax(3), wcstol(3), wcstoul(3)


log2(3)

LOG2

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

log2, log2f, log2l - base-2 logarithmic function

SYNOPSIS

#include <math.h>

double log2(double x);

float log2f(float x);

long double log2l(long double x);

Compile with -std=c99; link with -lm.

DESCRIPTION

The log2() function returns the base 2 logarithm of x.

ERRORS

The log2() function can return the following error:
EDOM
The argument x is negative.
ERANGE
The argument x is zero. The log of zero is not defined (minus infinity).

CONFORMING TO

SVr4, 4.3BSD, C89. The float and long double variants are C99 requirements.

SEE ALSO

cbrt(3), clog2(3), sqrt(3)


logb(3)

LOGB

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

logb, logbf, logbl - get exponent of a floating point value

SYNOPSIS

#include <math.h>

double logb(double x);
float logbf(float x);
long double logbl(long double x);

Link with -lm.

DESCRIPTION

These functions extract the exponent of x and return it as a floating-point value. If FLT_RADIX is two, logb(x) is equal to floor(log2(x)), except that it is probably faster.

If x is de-normalized, logb() returns the exponent x would have if it were normalized.

If x is zero, -HUGE_VAL (resp. -HUGE_VALF, -HUGE_VALL) is returned, and a pole error occurs. If x is infinite, plus infinity is returned. If x is NaN, NaN is returned.

ERRORS

In order to check for errors, set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

If an error occurs and (math_errhandling & MATH_ERRNO) is non-zero, then errno is set to ERANGE. If an error occurs and (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception is raised.

A pole error occurs when x is zero.

CONFORMING TO

C99

SEE ALSO

log(3), ilogb(3)


logf (3)

 Continue to this page.


logl (3)

 Continue to this page.


cimagf (3)

 Continue to this page.


cimagl (3)

 Continue to this page.


fgetpwent_r (3)

 Continue to this page.


isinff (3)

 Continue to this page.


isinfl (3)

 Continue to this page.


acosf (3)

 Continue to this page.


acosl (3)

 Continue to this page.


frexpf (3)

 Continue to this page.


frexpl (3)

 Continue to this page.


remainder(3)

REMAINDER

Section: Linux Programmer's Manual (3)
Updated: 2003-11-18 Return to Main Contents

NAME

drem, dremf, dreml, remainder, remainderf, remainderl - floating-point remainder function

SYNOPSIS

#include <math.h>

/* The C99 versions */
double remainder(double x, double y);
float remainderf(float x, float y);
long double remainderl(long double x, long double y);

/* Obsolete synonyms */
double drem(double x, double y);
float dremf(float x, float y);
long double dreml(long double x, long double y);
Link with -lm.

DESCRIPTION

The remainder() function computes the remainder of dividing x by y. The return value is x - n * y, where n is the value x / y, rounded to the nearest integer. If this quotient is 1/2 (mod 1), it is rounded to the nearest even number (independent of the current rounding mode). If the return value is 0, it has the sign of x.

The drem() function does precisely the same thing.

RETURN VALUE

The remainder() function returns the remainder, unless y is zero, when the function fails and errno is set.

ERRORS

EDOM
The denominator y is zero.

CONFORMING TO

IEC 60559. The functions remainder(), remainderf(), and remainderl() are from C99. The function drem() is from 4.3BSD. The float and long double variants dremf() and dreml() exist on some systems, such as Tru64 and glibc2.

EXAMPLE

The call "remainder(29.0, 3.0)" returns -1.

SEE ALSO

fmod(3), remquo(3)


feenableexcept (3)

 Continue to this page.


lcong48_r (3)

 Continue to this page.


isless (3)

 Continue to this page.


islessgreater (3)

 Continue to this page.


getgrent_r(3)

GETGRENT

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

getgrent_r, fgetgrent_r - get group file entry reentrantly

SYNOPSIS

#define _GNU_SOURCE

#include <grp.h>

int getgrent_r(struct group *gbuf, char *buf,

               size_t buflen, struct group **gbufp);

int fgetgrent_r(FILE *fp, struct group *gbuf, char *buf,

                size_t buflen, struct group **gbufp);

DESCRIPTION

The functions getgrent_r() and fgetgrent_r() are the reentrant versions of getgrent(3) and fgetgrent(3). The former reads the next group entry from the stream initialized by setgrent(3). The latter reads the next group entry from the stream fp given as parameter.

The group structure is defined in <grp.h> as follows:

struct group {
    char    *gr_name;      /* group name */
    char    *gr_passwd;    /* group password */
    gid_t   gr_gid;        /* group ID */
    char    **gr_mem;      /* group members */
};

The non-reentrant functions return a pointer to static storage, where this static storage contains further pointers to group name, password and members. The reentrant functions described here return all of that in caller-provided buffers. First of all there is the buffer gbuf that can hold a struct group. And next the buffer buf of size buflen that can hold additional strings. The result of these functions, the struct group read from the stream, is stored in the provided buffer *gbuf, and a pointer to this struct group is returned in *gbufp.

RETURN VALUE

On success, these functions return 0 and *gbufp is a pointer to the struct group. On error, these functions return an error value and *gbufp is NULL.

ERRORS

ENOENT
No more entries.
ERANGE
Insufficient buffer space supplied. Try again with larger buffer.

CONFORMING TO

These functions are GNU extensions, done in a style resembling the POSIX version of functions like getpwnam_r(3). Other systems use prototype

struct group *
getgrent_r(struct group *grp, char *buf, int buflen);

or, better,

int
getgrent_r(struct group *grp, char *buf, int buflen,
           FILE **gr_fp);

NOTES

The function getgrent_r() is not really reentrant since it shares the reading position in the stream with all other threads.

EXAMPLE

#define _GNU_SOURCE
#include <grp.h>
#include <stdio.h>
#define BUFLEN 4096

int
main(void)
{
    struct group grp, *grpp;
    char buf[BUFLEN];
    int i;

    setgrent();
    while (1) {
        i = getgrent_r(&grp, buf, BUFLEN, &grpp);
        if (i)
            break;
        printf("%s (%d):", grpp->gr_name, grpp->gr_gid);
        for (i = 0; ; i++) {
            if (grpp->gr_mem[i] == NULL)
                break;
            printf(" %s", grpp->gr_mem[i]);
        }
        printf("\n");
    }
    endgrent();
    exit(EXIT_SUCCESS);
}

SEE ALSO

fgetgrent(3), getgrent(3), getgrgid(3), getgrnam(3), putgrent(3), group(5), feature_test_macros(7)


powf (3)

 Continue to this page.


powl (3)

 Continue to this page.


ilogbf (3)

 Continue to this page.


ilogbl (3)

 Continue to this page.


casinhf (3)

 Continue to this page.


casinhl (3)

 Continue to this page.


wordfree (3)

 Continue to this page.


sinf (3)

 Continue to this page.


sinl (3)

 Continue to this page.


ctime_r (3)

 Continue to this page.


tanf (3)

 Continue to this page.


tanl (3)

 Continue to this page.


catanhf (3)

 Continue to this page.


catanhl (3)

 Continue to this page.


log10f (3)

 Continue to this page.


log10l (3)

 Continue to this page.


getmntent_r (3)

 Continue to this page.


scalblnf (3)

 Continue to this page.


scalblnl (3)

 Continue to this page.


log1pf (3)

 Continue to this page.


log1pl (3)

 Continue to this page.


cprojf (3)

 Continue to this page.


cprojl (3)

 Continue to this page.


aio_fsync(3)

AIO_FSYNC

Section: Linux Programmer's Manual (3)
Updated: 2003-11-14 Return to Main Contents

NAME

aio_fsync - asynchronous file synchronization

SYNOPSIS

#include <aio.h>

int aio_fsync(int op, struct aiocb *aiocbp);

DESCRIPTION

The aio_fsync() function does a sync on all outstanding asynchronous I/O operations associated with aiocbp->aio_fildes.

More precisely, if op is O_SYNC, then all currently queued I/O operations shall be completed as if by a call of fsync(2), and if op is O_DSYNC, this call is the asynchronous analog of fdatasync(2). Note that this is a request only --- this call does not wait for I/O completion.

Apart from aio_fildes the only field in the structure pointed to by aiocbp that is used by this call is the aio_sigevent field (a struct sigevent) that indicates the desired type of asynchronous notification at completion. All other fields are ignored.

RETURN VALUE

On success (the sync request was successfully queued) this function returns 0. On error -1 is returned, and errno is set appropriately.

ERRORS

EAGAIN
Out of resources.
EBADF
aio_fildes is not a valid file descriptor open for writing.
EINVAL
No synchronized I/O for this file is supported, or op is not O_SYNC or O_DSYNC.

CONFORMING TO

POSIX.1-2001

SEE ALSO

aio_cancel(3), aio_error(3), aio_read(3), aio_return(3), aio_suspend(3), aio_write(3)


isnormal (3)

 Continue to this page.


wcstoumax (3)

 Continue to this page.


getgrnam_r (3)

 Continue to this page.


xencrypt (3)

 Continue to this page.


dlvsym (3)

 Continue to this page.


ccoshf (3)

 Continue to this page.


ccoshl (3)

 Continue to this page.


logout (3)

 Continue to this page.


remainderf (3)

 Continue to this page.


remainderl (3)

 Continue to this page.


imaxdiv (3)

 Continue to this page.


mrand48_r (3)

 Continue to this page.


clock_settime (3)

 Continue to this page.


isgreater(3)

ISGREATER

Section: Linux Programmer's Manual (3)
Updated: 2002-07-27 Return to Main Contents

NAME

isgreater, isgreaterequal, isless, islessgreater, isunordered - macros to test a relation

SYNOPSIS

#include <math.h>

int isgreater(x,y);

int isgreaterequal(x,y);

int isless(x,y);

int islessequal(x,y);

int islessgreater(x,y);

int isunordered(x,y);

Compile with -std=c99; link with -lm.

DESCRIPTION

The normal relation operations (like less) will fail if one of the operands is NaN. This will cause an exception. To avoid this, C99 defines these macros. The macros are guaranteed to evaluate their operands only once. The operand can be of any real floating-point type.
isgreater()
determines (x) > (y) without an exception if x or y is NaN.
isgreaterequal()
determines (x) >= (y) without an exception if x or y is NaN.
isless()
determines (x) < (y) without an exception if x or y is NaN.
islessequal()
determines (x) <= (y) without an exception if x or y is NaN.
islessgreater()
determines (x) < (y) || (x) > (y) without an exception if x or y is NaN. This macro is not equivalent to x != y because that expression is true if x or y is NaN.
isunordered()
is true if x or y is NaN and false otherwise.

CONFORMING TO

C99

NOTES

Not all hardware supports these functions, and where it doesn't, they will be emulated by macros. This will give you a performance penalty. Don't use these functions if NaN is of no concern for you.

SEE ALSO

fpclassify(3), isnan(3)


getlogin_r (3)

 Continue to this page.


sincosf (3)

 Continue to this page.


sincosl (3)

 Continue to this page.


fgetspent (3)

 Continue to this page.


crealf (3)

 Continue to this page.


creall (3)

 Continue to this page.


asinf (3)

 Continue to this page.


asinl (3)

 Continue to this page.


atanf (3)

 Continue to this page.


atanl (3)

 Continue to this page.


xdecrypt (3)

 Continue to this page.


asinhf (3)

 Continue to this page.


asinhl (3)

 Continue to this page.


getpwent_r(3)

GETPWENT_R

Section: Linux Programmer's Manual (3)
Updated: 2003-11-15 Return to Main Contents

NAME

getpwent_r, fgetpwent_r - get passwd file entry reentrantly

SYNOPSIS

#define _GNU_SOURCE

#include <pwd.h>

int getpwent_r(struct passwd *pwbuf, char *buf,

               size_t buflen, struct passwd **pwbufp);

int fgetpwent_r(FILE *fp, struct passwd *pwbuf, char *buf,

                size_t buflen, struct passwd **pwbufp);

DESCRIPTION

The functions getpwent_r() and fgetpwent_r() are the reentrant versions of getpwent(3) and fgetpwent(3). The former reads the next passwd entry from the stream initialized by setpwent(3). The latter reads the next passwd entry from the stream fp given as parameter.

The passwd structure is defined in <pwd.h> as follows:

struct passwd {
    char    *pw_name;      /* user name */
    char    *pw_passwd;    /* user password */
    uid_t    pw_uid;       /* user ID */
    gid_t    pw_gid;       /* group ID */
    char    *pw_gecos;     /* real name */
    char    *pw_dir;       /* home directory */
    char    *pw_shell;     /* shell program */
};

The non-reentrant functions return a pointer to static storage, where this static storage contains further pointers to user name, password, gecos field, home directory and shell. The reentrant functions described here return all of that in caller-provided buffers. First of all there is the buffer pwbuf that can hold a struct passwd. And next the buffer buf of size buflen that can hold additional strings. The result of these functions, the struct passwd read from the stream, is stored in the provided buffer *pwbuf, and a pointer to this struct passwd is returned in *pwbufp.

RETURN VALUE

On success, these functions return 0 and *pwbufp is a pointer to the struct passwd. On error, these functions return an error value and *pwbufp is NULL.

ERRORS

ENOENT
No more entries.
ERANGE
Insufficient buffer space supplied. Try again with larger buffer.

CONFORMING TO

These functions are GNU extensions, done in a style resembling the POSIX version of functions like getpwnam_r(3). Other systems use prototype

struct passwd *
getpwent_r(struct passwd *pwd, char *buf, int buflen);

or, better,

int
getpwent_r(struct passwd *pwd, char *buf, int buflen,
           FILE **pw_fp);

NOTES

The function getpwent_r() is not really reentrant since it shares the reading position in the stream with all other threads.

EXAMPLE

#define _GNU_SOURCE
#include <pwd.h>
#include <stdio.h>
#define BUFLEN 4096

int
main(void)
{
    struct passwd pw, *pwp;
    char buf[BUFLEN];
    int i;

    setpwent();
    while (1) {
        i = getpwent_r(&pw, buf, BUFLEN, &pwp);
        if (i)
            break;
        printf("%s (%d)\tHOME %s\tSHELL %s\n", pwp->pw_name,
               pwp->pw_uid, pwp->pw_dir, pwp->pw_shell);
    }
    endpwent();
    exit(EXIT_SUCCESS);
}

SEE ALSO

fgetpwent(3), getpw(3), getpwent(3), getpwnam(3), getpwuid(3), putpwent(3), passwd(5), feature_test_macros(7)


getgrgid_r (3)

 Continue to this page.


passwd2des (3)

 Continue to this page.


cabsf (3)

 Continue to this page.


cabsl (3)

 Continue to this page.


cacos(3)

CACOS

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cacos, cacosf, cacosl - complex arc cosine

SYNOPSIS

#include <complex.h>

double complex cacos(double complex z);
float complex cacosf(float complex z);
long double complex cacosl(long double complex z);

Link with -lm.

DESCRIPTION

The cacos() function calculates the complex acos(). If y = cacos(z), then z = ccos(y). The real part of y is chosen in the interval [0,pi].

One has cacos(z) = -i clog(z + csqrt(z * z - 1)).

CONFORMING TO

C99

SEE ALSO

ccos(3), clog(3), complex(7)


atan2f (3)

 Continue to this page.


atan2l (3)

 Continue to this page.


des_crypt(3)

DES_CRYPT

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

des_crypt, ecb_crypt, cbc_crypt, des_setparity, DES_FAILED - fast DES encryption

SYNOPSIS

#include <rpc/des_crypt.h>

int ecb_crypt(char *key, char *data, unsigned datalen,
              unsigned mode);

int cbc_crypt(char *key, char *data, unsigned datalen,
              unsigned mode, char *ivec);

void des_setparity(char *key);

int DES_FAILED(int status);

DESCRIPTION

ecb_crypt() and cbc_crypt() implement the NBS DES (Data Encryption Standard). These routines are faster and more general purpose than crypt(3). They also are able to utilize DES hardware if it is available. ecb_crypt() encrypts in ECB (Electronic Code Book) mode, which encrypts blocks of data independently. cbc_crypt() encrypts in CBC (Cipher Block Chaining) mode, which chains together successive blocks. CBC mode protects against insertions, deletions and substitutions of blocks. Also, regularities in the clear text will not appear in the cipher text.

Here is how to use these routines. The first parameter, key, is the 8-byte encryption key with parity. To set the key's parity, which for DES is in the low bit of each byte, use des_setparity(). The second parameter, data, contains the data to be encrypted or decrypted. The third parameter, datalen, is the length in bytes of data, which must be a multiple of 8. The fourth parameter, mode, is formed by OR'ing together some things. For the encryption direction 'or' in either DES_ENCRYPT or DES_DECRYPT. For software versus hardware encryption, 'or' in either DES_HW or DES_SW. If DES_HW is specified, and there is no hardware, then the encryption is performed in software and the routine returns DESERR_NOHWDEVICE. For cbc_crypt(), the parameter ivec is the 8-byte initialization vector for the chaining. It is updated to the next initialization vector upon return.

RETURN VALUE

DESERR_NONE
No error.
DESERR_NOHWDEVICE
Encryption succeeded, but done in software instead of the requested hardware.
DESERR_HWERROR
An error occurred in the hardware or driver.
DESERR_BADPARAM
Bad parameter to routine.

Given a result status stat, the macro DES_FAILED(stat) is false only for the first two statuses.

VERSIONS

These routines are present in libc 4.6.27 and later, and in glibc 2.1 and later.

CONFORMING TO

4.3BSD. Not in POSIX.1-2001.

SEE ALSO

des(1), crypt(3) and xcrypt(3)


islessequal (3)

 Continue to this page.


atanhf (3)

 Continue to this page.


atanhl (3)

 Continue to this page.


fpclassify(3)

FPCLASSIFY

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

fpclassify, isfinite, isnormal, isnan - floating-point classification macros

SYNOPSIS

#include <math.h>

int fpclassify(x);

int isfinite(x);

int isnormal(x);

int isnan(x);

int isinf(x);

Compile with -std=c99; link with -lm.

DESCRIPTION

Floating point numbers can have special values, such as infinite or NaN. With the macro fpclassify(x) you can find out what type x is. The macro takes any floating-point expression as argument. The result is one of the following values:
FP_NAN
x is "Not a Number".
FP_INFINITE
x is either plus or minus infinity.
FP_ZERO
x is zero.
FP_SUBNORMAL
x is too small to be represented in normalized format.
FP_NORMAL
if nothing of the above is correct then it must be a normal floating-point number.

The other macros provide a short answer to some standard questions.

isfinite(x)
returns a non-zero value if
(fpclassify(x) != FP_NAN && fpclassify(x) != FP_INFINITE)
isnormal(x)
returns a non-zero value if (fpclassify(x) == FP_NORMAL)
isnan(x)
returns a non-zero value if (fpclassify(x) == FP_NAN)
isinf(x)
returns 1 if x is positive infinity, and -1 if x is negative infinity.

CONFORMING TO

C99

NOTES

In glibc 2.01 and earlier, isinf() returns a non-zero value (actually: 1) if x is an infinity (positive or negative). (This is all that C99 requires.)

SEE ALSO

finite(3), INFINITY(3), isgreater(3)


cargf (3)

 Continue to this page.


cargl (3)

 Continue to this page.


casin(3)

CASIN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

casin, casinf, casinl - complex arc sine

SYNOPSIS

#include <complex.h>

double complex casin(double complex z);
float complex casinf(float complex z);
long double complex casinl(long double complex z);

Link with -lm.

DESCRIPTION

The casin() function calculates the complex asin(). If y = casin(z), then z = csin(y). The real part of y is chosen in the interval [-pi/2,pi/2].

One has casin(z) = -i clog(iz + csqrt(1 - z * z)).

CONFORMING TO

C99

SEE ALSO

ccos(3), clog(3), complex(7)


catan(3)

CATAN

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

catan, catanf, catanl - complex arc tangents

SYNOPSIS

#include <complex.h>

double complex catan(double complex z);
float complex catanf(float complex z);
long double complex catanl(long double complex z);

Link with -lm.

DESCRIPTION

The catan() function calculates the complex atan(). If y = catan(z), then z = ctan(y). The real part of y is chosen in the interval [-pi/2,pi/2].

One has catan(z) = 1 / 2i clog((1 + iz) / (1 - iz)).

CONFORMING TO

C99

SEE ALSO

ccos(3), clog(3), complex(7)


clock_gettime (3)

 Continue to this page.


getutent_r (3)

 Continue to this page.


ilogb(3)

ILOGB

Section: Linux Programmer's Manual (3)
Updated: 2004-10-31 Return to Main Contents

NAME

ilogb, ilogbf, ilogbl - get integer exponent of a floating point value

SYNOPSIS

#include <math.h>

int ilogb(double x);
int ilogbf(float x);
int ilogbl(long double x);

Link with -lm.

DESCRIPTION

These functions return the exponent part of their argument as a signed integer. When no error occurs, these functions are equivalent to the corresponding logb(3) functions, cast to (int). An error will occur for zero and infinity and NaN, and possibly for overflow.

ERRORS

In order to check for errors, set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

If an error occurs and (math_errhandling & MATH_ERRNO) is non-zero, then errno is set to EDOM. If an error occurs and (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception is raised.

A domain error occurs when x is zero or infinite (or too large, or too small) or NaN. If x is zero, the constant FP_ILOGB0 is returned. If x is NaN, the constant FP_ILOGBNAN is returned. If x is infinite (or too large), INT_MAX is returned. If x is too small, INT_MIN is returned.

CONFORMING TO

C99

SEE ALSO

log(3), logb(3)


cbrtf (3)

 Continue to this page.


cbrtl (3)

 Continue to this page.


erand48_r (3)

 Continue to this page.


lckpwdf (3)

 Continue to this page.


remquof (3)

 Continue to this page.


remquol (3)

 Continue to this page.


ccosf (3)

 Continue to this page.


ccosh(3)

CCOSH

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

ccosh, ccoshf, ccoshl - complex hyperbolic cosine

SYNOPSIS

#include <complex.h>

double complex ccosh(double complex z);
float complex ccoshf(float complex z);
long double complex ccoshl(long double complex z);

Link with -lm.

DESCRIPTION

The complex hyperbolic cosine function ccosh(z) is defined as (exp(z)+exp(-z))/2.

CONFORMING TO

C99

SEE ALSO

cabs(3), csinh(3), ctanh(3), complex(7)


ccosl (3)

 Continue to this page.


signgam (3)

 Continue to this page.


mempcpy(3)

MEMPCPY

Section: Linux Programmer's Manual (3)
Updated: 2003-11-11 Return to Main Contents

NAME

mempcpy, wmempcpy - copy memory area

SYNOPSIS

#define _GNU_SOURCE

#include <string.h>

void *mempcpy(void *dest, const void *src, size_t n);

#define _GNU_SOURCE

#include <wchar.h>

wchar_t *wmempcpy(wchar_t *dest, const wchar_t *src, size_t n);

DESCRIPTION

The mempcpy() function is nearly identical to the memcpy(3) function. It copies n bytes from the object beginning at src into the object pointed to by dest. But instead of returning the value of dest it returns a pointer to the byte following the last written byte.

This function is useful in situations where a number of objects shall be copied to consecutive memory positions.

The wmempcpy() function is identical but takes wchar_t type arguments and copies n wide characters.

RETURN VALUE

dest + n .

CONFORMING TO

This function is a GNU extension.

EXAMPLE

void *
combine(void *o1, size_t s1, void *o2, size_t s2)
{
     void *result = malloc(s1 + s2);
     if (result != NULL)
          mempcpy(mempcpy(result, o1, s1), o2, s2);
     return result;
}

SEE ALSO

memccpy(3), memcpy(3), memmove(3), wmemcpy(3), feature_test_macros(7)


putspent (3)

 Continue to this page.


cerfc (3)

 Continue to this page.


cerff (3)

 Continue to this page.


cerfl (3)

 Continue to this page.


cexp2(3)

CEXP2

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cexp2, cexp2f, cexp2l - base-2 exponent of a complex number

SYNOPSIS

#include <complex.h>

double complex cexp2(double complex z);
float complex cexp2f(float complex z);
long double complex cexp2l(long double complex z);

Link with -lm.

DESCRIPTION

The function returns 2 raised to the power of z.

CONFORMING TO

These function names are reserved for future use in C99.

AVAILABILITY

Not yet in glibc, as at version 2.4.

SEE ALSO

cabs(3), cexp(3), clog10(3), complex(7)


cexpf (3)

 Continue to this page.


cexpl (3)

 Continue to this page.


cfree(3)

CFREE

Section: Linux Programmer's Manual (3)
Updated: 2003-11-18 Return to Main Contents

NAME

cfree - free allocated memory

SYNOPSIS

#include <stdlib.h>

/* In SunOS 4 */
int cfree(void *ptr);

/* In glibc or FreeBSD libcompat */
void cfree(void *ptr);

/* In SCO OpenServer */
void cfree(char *ptr, unsigned num, unsigned size);

/* In Solaris watchmalloc.so.1 */
void cfree(void *ptr, size_t nelem, size_t elsize);

DESCRIPTION

This function should never be used. Use free(3) instead.

1-arg cfree

In glibc, the function cfree() is a synonym for free(3), "added for compatibility with SunOS".

Other systems have other functions with this name. The declaration is sometimes in <stdlib.h> and sometimes in <malloc.h>.

3-arg cfree

Some SCO and Solaris versions have malloc libraries with a 3-argument cfree(), apparently as an analog to calloc(3).

If you need it while porting something, add

#define cfree(p, n, s) free((p))

to your file.

A frequently asked question is "Can I use free(3) to free memory allocated with calloc(3), or do I need cfree()? Answer: use free(3).

An SCO manual writes: "The cfree routine is provided for compliance to the iBCSe2 standard and simply calls free. The num and size arguments to cfree are not used."

RETURN VALUE

The SunOS version of cfree() (which is a synonym for free(3)) returns 1 on success and 0 on failure. In case of error, errno is set to EINVAL: the value of ptr was not a pointer to a block previously allocated by one of the routines in the malloc(3) family.

CONFORMING TO

The 3-argument version of cfree() as used by SCO conforms to the iBCSe2 standard: Intel386 Binary Compatibility Specification, Edition 2.


significand(3)

SIGNIFICAND

Section: Linux Programmer's Manual (3)
Updated: 2002-08-10 Return to Main Contents

NAME

significand, significandf, significandl - get mantissa of floating point number

SYNOPSIS

#include <math.h>

double significand(double x);
float significandf(float x);
long double significandl(long double x);

Link with -lm.

DESCRIPTION

The significand() function returns the mantissa of x scaled to the range [1,2). It is equivalent to

scalb(x, (double) -ilogb(x))

This function exists mainly for use in certain standardized tests for IEEE 754 conformance.

SEE ALSO

ilogb(3), scalb(3)


exp10f (3)

 Continue to this page.


exp10l (3)

 Continue to this page.


pow10(3)

POW10

Section: Linux Programmer's Manual (3)
Updated: 2004-10-05 Return to Main Contents

NAME

pow10, pow10f, pow10l - base-10 power functions

SYNOPSIS

#define _GNU_SOURCE
#include <math.h>

double pow10(double x);

float pow10f(float x);

long double pow10l(long double x);

Link with -lm.

DESCRIPTION

The pow10() function returns the value of 10 raised to the power x.

CONFORMING TO

This is a GNU extension.

NOTES

These functions are identical to the functions listed under exp10(3).

SEE ALSO

exp10(3), pow(3), feature_test_macros(7)


getpwnam_r (3)

 Continue to this page.


getutline_r (3)

 Continue to this page.


tmpnam_r (3)

 Continue to this page.


hypotf (3)

 Continue to this page.


hypotl (3)

 Continue to this page.


cimag(3)

CIMAG

Section: Linux Programmer's Manual (3)
Updated: 2002-07-28 Return to Main Contents

NAME

cimag, cimagf, cimagl - get imaginary part of a complex number

SYNOPSIS

#include <complex.h>

double cimag(double complex z);
float cimagf(float complex z);
long double cimagl(long double complex z);

Link with -lm.

DESCRIPTION

The cimag() function returns the imaginary part of the complex number z.

One has z = creal(z) + I * cimag(z).

CONFORMING TO

C99

NOTES

gcc also supports __imag__. That is a GNU extension.

SEE ALSO

cabs(3), creal(3), complex(7)


clock_getres(3)

CLOCK_GETRES

Section: Linux Programmer's Manual (3)
Updated: 2003-08-24 Return to Main Contents

NAME

clock_getres, clock_gettime, clock_settime - clock and time functions

SYNOPSIS

#include <time.h>

int clock_getres(clockid_t clk_id, struct timespec *res);
int clock_gettime(clockid_t clk_id, struct timespec *tp);
int clock_settime(clockid_t clk_id, const struct timespec *tp);

DESCRIPTION

The function clock_getres() finds the resolution (precision) of the specified clock clk_id, and, if res is non-NULL, stores it in the struct timespec pointed to by res. The resolution of clocks depends on the implementation and cannot be configured by a particular process. If the time value pointed to by the argument tp of clock_settime() is not a multiple of res, then it is truncated to a multiple of res.

The functions clock_gettime() and clock_settime() retrieve and set the time of the specified clock clk_id.

The res and tp arguments are timespec structs, as specified in <time.h>:

struct timespec {
time_t   tv_sec;        /* seconds */
long     tv_nsec;       /* nanoseconds */
};

The clk_id argument is the identifier of the particular clock on which to act. A clock may be system-wide and hence visible for all processes, or per-process if it measures time only within a single process.

All implementations support the system-wide realtime clock, which is identified by CLOCK_REALTIME. Its time represents seconds and nanoseconds since the Epoch. When its time is changed, timers for a relative interval are unaffected, but timers for an absolute point in time are affected.

More clocks may be implemented. The interpretation of the corresponding time values and the effect on timers is unspecified.

Sufficiently recent versions of GNU libc and the Linux kernel support the following clocks:

CLOCK_REALTIME
System-wide realtime clock. Setting this clock requires appropriate privileges.
CLOCK_MONOTONIC
Clock that cannot be set and represents monotonic time since some unspecified starting point.
CLOCK_PROCESS_CPUTIME_ID
High-resolution per-process timer from the CPU.
CLOCK_THREAD_CPUTIME_ID
Thread-specific CPU-time clock.

RETURN VALUE

clock_gettime(), clock_settime() and clock_getres() return 0 for success, or -1 for failure (in which case errno is set appropriately).

ERRORS

EFAULT
tp points outside the accessible address space.
EINVAL
The clk_id specified is not supported on this system.
EPERM
clock_settime() does not have permission to set the clock indicated.

CONFORMING TO

SUSv2, POSIX.1-2001.

AVAILABILITY

On POSIX systems on which these functions are available, the symbol _POSIX_TIMERS is defined in <unistd.h> to a value greater than 0. The symbols _POSIX_MONOTONIC_CLOCK, _POSIX_CPUTIME, _POSIX_THREAD_CPUTIME indicate that CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID are available. (See also sysconf(3).)

NOTES

Most systems require the program be linked with the librt library to use these functions.

Note for SMP systems

The CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID clocks are realized on many platforms using timers from the CPUs (TSC on i386, AR.ITC on Itanium). These registers may differ between CPUs and as a consequence these clocks may return bogus results if a process is migrated to another CPU.

If the CPUs in an SMP system have different clock sources then there is no way to maintain a correlation between the timer registers since each CPU will run at a slightly different frequency. If that is the case then clock_getcpuclockid(0) will return ENOENT to signify this condition. The two clocks will then only be useful if it can be ensured that a process stays on a certain CPU.

The processors in an SMP system do not start all at exactly the same time and therefore the timer registers are typically running at an offset. Some architectures include code that attempts to limit these offsets on bootup. However, the code cannot guarantee to accurately tune the offsets. Glibc contains no provisions to deal with these offsets (unlike the Linux Kernel). Typically these offsets are small and therefore the effects may be negligible in most cases.

SEE ALSO

date(1), adjtimex(2), gettimeofday(2), settimeofday(2), time(2), ctime(3), ftime(3), sysconf(3)


posix_openpt(3)

POSIX_OPENPT

Section: Linux Programmer's Manual (3)
Updated: 2007-01-08 Return to Main Contents

NAME

posix_openpt - open a pseudo-terminal device

SYNOPSIS

#define _XOPEN_SOURCE 600

#include <stdlib.h>
#include <fcntl.h>

int posix_openpt(int flags);

DESCRIPTION

The posix_openpt() function opens an unused pseudo-terminal master device, returning a file descriptor that can be used to refer to that device.

The flags argument is a bit mask that ORs together zero or more of the following flags:

O_RDWR
Open the device for both reading and writing. It is usual to specify this flag.
O_NOCTTY
Do not make this device the controlling terminal for the process.

RETURN VALUE

On success, posix_openpt() returns a non-negative file descriptor which is the lowest numbered unused descriptor. On failure, -1 is returned, and errno is set to indicate the error.

ERRORS

See open(2).

VERSIONS

Glibc support for posix_openpt() has been provided since version 2.2.1.

CONFORMING TO

posix_openpt() is part of the Unix98 pseudo-terminal support (see pts(4)). This function is specified in POSIX.1-2001.

NOTES

This function is a recent invention in POSIX. Some Unix implementations that support System V (aka Unix 98) pseudo-terminals don't have this function, but it is easy to implement:

int
posix_openpt(int flags)
{
    return open("/dev/ptmx", flags);
}

SEE ALSO

open(2), getpt(3), grantpt(3), ptsname(3), unlockpt(3), pts(4), feature_test_macros(7), pty(7)


sem_unlink(3)

SEM_UNLINK

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_unlink - remove a named semaphore

SYNOPSIS

#include <semaphore.h>

int sem_unlink(const char *name);

DESCRIPTION

sem_unlink() removes the named semaphore referred to by sem. The semaphore name is removed immediately. The semaphore is destroyed once all other processes that have the semaphore open close it.

RETURN VALUE

On success sem_unlink() returns 0; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EACCES
The caller does not have permission to unlink this semaphore.
ENAMETOOLONG
name was too long.
ENOENT
There is no semaphore with the given name.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

sem_getvalue(3), sem_open(3), sem_post(3), sem_wait(3), sem_overview(7)


rexec(3)

REXEC

Section: C Library Functions (3) Return to Main Contents

BSD mandoc

NAME

rexec - return stream to a remote command

LIBRARY

Lb libcompat

SYNOPSIS

Ft int Fn rexec char **ahost int inport char *user char *passwd char *cmd int *fd2p

DESCRIPTION

Bf -symbolic This interface is obsoleted by rcmd(3). Ef

The Fn rexec function looks up the host Fa *ahost using gethostbyname(3), returning -1 if the host does not exist. Otherwise Fa *ahost is set to the standard name of the host. If a username and password are both specified, then these are used to authenticate to the foreign host; otherwise the environment and then the user's .netrc file in his home directory are searched for appropriate information. If all this fails, the user is prompted for the information.

The port Fa inport specifies which well-known DARPA Internet port to use for the connection; the call Fn getservbyname exec tcp (see getservent(3)) will return a pointer to a structure, which contains the necessary port. The protocol for connection is described in detail in rexecd(8).

If the connection succeeds, a socket in the Internet domain of type SOCK_STREAM is returned to the caller, and given to the remote command as stdin and stdout If Fa fd2p is non-zero, then an auxiliary channel to a control process will be setup, and a descriptor for it will be placed in Fa *fd2p . The control process will return diagnostic output from the command (unit 2) on this channel, and will also accept bytes on this channel as being UNIX signal numbers, to be forwarded to the process group of the command. The diagnostic information returned does not include remote authorization failure, as the secondary connection is set up after authorization has been verified. If Fa fd2p is 0, then the stderr (unit 2 of the remote command) will be made the same as the stdout and no provision is made for sending arbitrary signals to the remote process, although you may be able to get its attention by using out-of-band data.

CONFORMING TO

Not in POSIX.1-2001. Present on the BSDs, Solaris, and many other systems. The Fn rexec function appeared in BSD 4.2

BUGS

The Fn rexec function sends the unencrypted password across the network.

The underlying service is considered a big security hole and therefore not enabled on many sites, see rexecd(8) for explanations.

SEE ALSO

rcmd(3), rexecd(8)


adjtime(3)

ADJTIME

Section: Linux Programmer's Manual (3)
Updated: 2006-05-01 Return to Main Contents

NAME

adjtime - correct the time to synchronize the system clock

SYNOPSIS

#define _BSD_SOURCE

int adjtime(const struct timeval *delta, struct timeval *olddelta);

DESCRIPTION

The adjtime() function gradually adjusts the system clock (as returned by gettimeofday(2)). The amount of time by which the clock is to be adjusted is specified in the structure pointed to by delta. This structure has the following form:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

If the adjustment in delta is positive, then the system clock is speeded up by some small percentage (i.e., by adding a small amount of time to the clock value in each second) until the adjustment has been completed. If the adjustment in delta is negative, then the clock is slowed down in a similar fashion.

If a clock adjustment from an earlier adjtime() call is already in progress at the time of a later adjtime() call, and delta is not NULL for the later call, then the earlier adjustment is stopped, but any already completed part of that adjustment is not undone.

If olddelta is not NULL, then the buffer that it points to is used to return the amount of time remaining from any previous adjustment that has not yet been completed.

RETURN VALUE

On success, adjtime() returns 0. On failure, -1 is returned, and errno is set to indicate the error.

ERRORS

EINVAL
The adjustment in delta is outside the permitted range.
EPERM
The caller does not have sufficient privilege to adjust the time. Under Linux the CAP_SYS_TIME capability is required.

CONFORMING TO

4.3BSD, System V.

NOTES

The adjustment that adjtime() makes to the clock is carried out in such a manner that the clock is always monotonically increasing. Using adjtime() to adjust the time prevents the problems that can be caused for certain applications (e.g., make(1)) by abrupt positive or negative jumps in the system time.

adjtime() is intended to be used to make small adjustments to the system time. Most systems impose a limit on the adjustment that can be specified in delta. In the glibc implementation, delta must be less than or equal to (INT_MAX / 1000000 - 2) and greater than or equal to (INT_MIN / 1000000 + 2) (respectively 2145 and -2145 seconds on x86).

BUGS

Currently, if delta is specified as NULL, no valid information about the outstanding clock adjustment is returned in olddelta. (In this circumstance, adjtime() should return the outstanding clock adjustment, without changing it.) This is the result of a kernel limitation.

SEE ALSO

adjtimex(2), gettimeofday(2), feature_test_macros(7), time(7)


sigisemptyset (3)

 Continue to this page.


sysv_signal(3)

SYSV_SIGNAL

Section: Linux Programmer's Manual (3)
Updated: 2007-05-04 Return to Main Contents

NAME

sysv_signal - signal handling with System V semantics

SYNOPSIS

#define _GNU_SOURCE
#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t sysv_signal(int signum, sighandler_t handler);

DESCRIPTION

The sysv_signal() function takes the same arguments, and performs the same task, as signal(2).

However sysv_signal() provides the System V unreliable signal semantics, that is: a) the disposition of the signal is reset to the default when the handler is invoked; b) delivery of further instances of the signal is not blocked while the signal handler is executing; and c) if the handler interrupts (certain) blocking system calls, then the system call is not automatically restarted.

RETURN VALUE

The sysv_signal() function returns the previous value of the signal handler, or SIG_ERR on error.

ERRORS

As for signal(2).

CONFORMING TO

This function is non-standard.

NOTES

Use of sysv_signal() should be avoided; use sigaction(2) instead.

On older Linux systems, sysv_signal() and signal(2) were equivalent. But on newer systems, signal(2) provides reliable signal semantics; see signal(2) for details.

The use of sighandler_t is a GNU extension; this type is only defined if the _GNU_SOURCE feature test macro is defined.

SEE ALSO

sigaction(2), signal(2), bsd_signal(3), feature_test_macros(7), signal(7)


mq_open(3)

MQ_OPEN

Section: Linux Programmer's Manual (3)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_open - open a message queue

SYNOPSIS

#include <mqueue.h>

mqd_t mq_open(const char *name, int oflag);
mqd_t mq_open(const char *name, int oflag, mode_t mode,
              struct mq_attr *attr);

DESCRIPTION

mq_open() creates a new POSIX message queue or opens an existing queue. The queue is identified by name. For details of the construction of name, see mq_overview(7).

The oflag argument specifies flags that control the operation of the call. Exactly one of the following must be specified in oflag:

O_RDONLY
Open the queue to receive messages only.
O_WRONLY
Open the queue to send messages only.
O_RDWR
Open the queue to both send and receive messages.

Zero or more of the following flags can additionally be ORed in oflag:

O_NONBLOCK
Open the queue in non-blocking mode. In circumstances where mq_receive(3) and mq_send(3) would normally block, these functions instead fail with the error EAGAIN.
O_CREAT
Create the message queue if it does not exist. The owner (user ID) of the message queue is set to the effective user ID of the calling process. The group ownership (group ID) is set to the effective group ID of the calling process.
O_EXCL
If O_CREAT was specified in oflag, and a queue with the given name already exists, then fail with the error EEXIST.

If O_CREAT is specified in oflag, then two additional arguments must be supplied. The mode argument specifies the permissions to be placed on the new queue, as for open(2). The permissions settings are masked against the process umask. The attr argument specifies attributes for the queue. See mq_getattr(3) for details. If attr is NULL, then the queue is created with implementation-defined default attributes.

RETURN VALUE

On success, mq_open() returns a message queue descriptor for use by other message queue functions. On error, mq_open() returns (mqd_t) -1, with errno set to indicate the error.

ERRORS

EACCES
The queue exists, but the caller does not have permission to open it in the specified mode.
EINVAL
O_CREAT was specified in oflag, and attr was not NULL, but attr->mq_maxmsg or attr->mq_msqsize was invalid. Both of these fields must be greater than zero. In a process that is unprivileged (does not have the CAP_SYS_RESOURCE capability), attr->mq_maxmsg must be less than or equal to the msg_max limit, and attr->mq_msgsize must be less than or equal to the msgsize_max limit. In addition, even in a privileged process, attr->mq_maxmsg cannot exceed the HARD_MAX limit. (See mq_overview(7) for details of these limits.)
EEXIST
Both O_CREAT and O_EXCL were specified in oflag, but a queue with this name already exists.
EMFILE
The process already has the maximum number of files and message queues open.
ENAMETOOLONG
name was too long.
ENFILE
The system limit on the total number of open files and message queues has been reached.
ENOENT
The O_CREAT flag was not specified in oflag, and no queue with this name exists.
ENOMEM
Insufficient memory.
ENOSPC
Insufficient space for the creation of a new message queue. This probably occurred because the queues_max limit was encountered; see mq_overview(7).

CONFORMING TO

POSIX.1-2001.

BUGS

In kernels before 2.6.14, the process umask was not applied to the permissions specified in mode.

SEE ALSO

mq_close(3), mq_getattr(3), mq_notify(3), mq_receive(3), mq_send(3), mq_unlink(3), mq_overview(7)


tdestroy (3)

 Continue to this page.


getsubopt(3)

GETSUBOPT

Section: Linux Programmer's Manual (3)
Updated: 2007-05-05 Return to Main Contents

NAME

getsubopt - parse suboption arguments from a string

SYNOPSIS

#define _XOPEN_SOURCE 500
#include <stdlib.h>

int getsubopt(char **optionp, char *const *tokens, char valuep);

DESCRIPTION

getsubopt() parses the list of comma-separated suboptions provided in optionp. (Such a suboption list is typically produced when getopt(3) is used to parse a command line; see for example the -o option of mount(8).) Each suboption may include an associated value, which is separated from the suboption name by an equal sign. The following is an example of the kind of string that might be passed in optionp:

ro,name=xyz

The tokens argument is a pointer to a NULL-terminated list of the tokens that getsubopt() will look for in optionp. The tokens should be distinct, null-terminated strings containing at least one character, with no embedded equal signs or commas.

Each call to getsubopt() returns information about the next unprocessed suboption in optionp. The first equal sign in a suboption (if any) is interpreted as a separator between the name and the value of that suboption. The value extends to the next comma, or (for the last suboption) to the end of the string. If the name of the suboption matches a known name from tokens, and a value string was found, getsubopt() sets *valuep to the address of that string. The first comma in optionp is overwritten with a null byte, so *valuep is precisely the "value string" for that suboption.

If the suboption is recognized, but no value string was found, *valuep is set to NULL.

When getsubopt() returns, optionp points to the next suboption, or to the null character at the end of the string if the last suboption was just processed.

RETURN VALUE

If the first suboption in optionp is recognized, getsubopt() returns the index of the matching suboption element in tokens . Otherwise, -1 is returned and *valuep is the entire name[=value] string.

Since *optionp is changed, the first suboption before the call to getsubopt() is not (necessarily) the same as the first suboption after getsubopt().

CONFORMING TO

POSIX.1-2001.

NOTES

Since getsubopt() overwrites any commas it finds in the string *optionp, that string must be writable; it cannot be a string constant.

EXAMPLE

The following program excepts suboptions following a "-o" option.

#define _XOPEN_SOURCE 500
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    enum {
        RO_OPT = 0,
        RW_OPT,
        NAME_OPT
    };
    char *const token[] = {
        [RO_OPT]   = "ro",
        [RW_OPT]   = "rw",
        [NAME_OPT] = "name",
        NULL
    };
    char *subopts;
    char *value;
    int opt;

    int readonly = 0;
    int readwrite = 0;
    char *name = NULL;
    int errfnd = 0;

    while ((opt = getopt(argc, argv, "o:")) != -1) {
        switch(opt) {
        case 'o':
            subopts = optarg;
            while (*subopts != '\0' && !errfnd) {

            switch (getsubopt(&subopts, token, &value)) {
                case RO_OPT:
                    readonly = 1;
                    break;

                case RW_OPT:
                    readwrite = 1;
                    break;

                case NAME_OPT:
                    if (value == NULL) {
                        fprintf(stderr, "Missing value for "
                                "suboption '%s'\n", token[NAME_OPT]);
                        errfnd = 1;
                        continue;
                    }

                    name = value;
                    break;

                default:
                    fprintf(stderr, "No match found "
                            "for token: /%s/\n", value);
                    errfnd = 1;
                    break;
                }
            }
            if (readwrite && readonly) {
                fprintf(stderr, "Only one of '%s' and '%s' can be "
                        "specified\n", token[RO_OPT], token[RW_OPT]);
                errfnd = 1;
            }
            break;

        default:
            errfnd = 1;
        }
    }

    if (errfnd || argc == 1) {
        fprintf(stderr, "\nUsage: %s -o <suboptstring>\n", argv[0]);
        fprintf(stderr, "suboptions are 'ro', 'rw', "
                "and 'name=<value>'\n");
        exit(EXIT_FAILURE);
    }

    /* Remainder of program... */

    exit(EXIT_SUCCESS);
}

SEE ALSO

getopt(3), feature_test_macros(7)


mq_send(3)

MQ_SEND

Section: Linux Programmer's Manual (3)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_send, mq_timedsend - send a message to a message queue

SYNOPSIS

#include <mqueue.h>

mqd_t mq_send(mqd_t mqdes, const char *msg_ptr,
              size_t msg_len, unsigned msg_prio);

#define _XOPEN_SOURCE 600
#include <time.h>
#include <mqueue.h>

mqd_t mq_timedsend(mqd_t mqdes, const char *msg_ptr,
              size_t msg_len, unsigned msg_prio,
              const struct timespec *abs_timeout);

DESCRIPTION

mq_send() adds the message pointed to by msg_ptr to the message queue referred to by the descriptor mqdes. The msg_len argument specifies the length of the message pointed to by msg_ptr; this length must be less than or equal to the queue's mq_msgsize attribute. Zero-length messages are allowed.

The msg_prio argument is a non-negative integer that specifies the priority of this message. Messages are placed on the queue in decreasing order of priority, with newer messages of the same priority being placed after older messages with the same priority.

If the message queue is already full (i.e., the number of messages on the queue equals the queue's mq_maxmsg attribute), then, by default, mq_send() blocks until sufficient space becomes available to allow the message to be queued, or until the call is interrupted by a signal handler. If the O_NONBLOCK flag is enabled for the message queue description, then the call instead fails immediately with the error EAGAIN.

mq_timedsend() behaves just like mq_send(), except that if the queue is full and the O_NONBLOCK flag is not enabled for the message queue description, then abs_timeout points to a structure which specifies a ceiling on the time for which the call will block. This ceiling is an absolute timeout in seconds and nanoseconds since the Epoch (midnight on the morning of 1 January 1970), specified in the following structure:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};
If the message queue is full, and the timeout has already expired by the time of the call, mq_timedsend() returns immediately.

RETURN VALUE

On success, mq_send() and mq_timedsend() return zero; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EAGAIN
The queue was empty, and the O_NONBLOCK flag was set for the message queue description referred to by mqdes.
EBADF
The descriptor specified in mqdes was invalid.
EMSGSIZE
msg_len was greater than the mq_msgsize attribute of the message queue.
EINTR
The call was interrupted by a signal handler.
EINVAL
The call would have blocked, and abs_timeout was invalid, either because tv_sec was less than zero, or because tv_nsec was less than zero or greater than 1000 million.
ETIMEDOUT
The call timed out before a message could be transferred.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_unlink(3), feature_test_macros(7), mq_overview(7)


sem_close(3)

SEM_CLOSE

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_close - close a named semaphore

SYNOPSIS

#include <semaphore.h>

int sem_close(sem_t *sem);

DESCRIPTION

sem_close() closes the named semaphore referred to by sem, allowing any resources that the system has allocated to the calling process for this semaphore to be freed.

RETURN VALUE

On success sem_close() returns 0; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EINVAL
sem is not a valid semaphore.

CONFORMING TO

POSIX.1-2001.

NOTES

All open named semaphores are automatically closed on process termination, or upon execve(2).

SEE ALSO

sem_getvalue(3), sem_open(3), sem_post(3), sem_unlink(3), sem_wait(3), sem_overview(7)


sigset(3)

SIGSET

Section: Linux Programmer's Manual (3)
Updated: 2005-12-01 Return to Main Contents

NAME

sigset, sighold, sigrelse, sigignore - System V signal API

SYNOPSIS

#define _XOPEN_SOURCE 500
#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t sigset(int sig, sighandler_t disp);

int sighold(int sig);

int sigrelse(int sig);

int sigignore(int sig);

DESCRIPTION

These functions are provided in glibc as a compatibility interface for programs that make use of the historical System V signal API. This API is obsolete: new applications should use the POSIX signal API (sigaction(2), sigprocmask(2), etc.)

The sigset() function modifies the disposition of the signal sig. The disp argument can be the address of a signal handler function, or one of the following constants:

SIG_DFL
Reset the disposition of sig to the default.
SIG_IGN
Ignore sig.
SIG_HOLD
Add sig to the process's signal mask, but leave the disposition of sig unchanged.

If disp specifies the address of a signal handler, then sig is added to the process's signal mask during execution of the handler.

If disp was specified as a value other than SIG_HOLD, then sig is removed from the process's signal mask.

The dispositions for SIGKILL and SIGSTOP cannot be changed.

The sighold() function adds sig to the calling process's signal mask.

The sigrelse() function removes sig from the calling process's signal mask.

The sigignore() function sets the disposition of sig to SIG_IGN.

RETURN VALUE

On success, sigset() returns SIG_HOLD if sig was blocked before the call, or the signal's previous disposition if it was not blocked before the call. On error, sigset() returns -1, with errno set to indicate the error.

The sighold(), sigrelse(), and sigignore() functions return 0 on success; on error, these functions return -1 and set errno to indicate the error.

ERRORS

For sigset() see the ERRORS under sigaction(2) and sigprocmask(2).

For sighold() and sigrelse() see the ERRORS under sigprocmask(2).

For sigignore(), see the errors under sigaction(2).

CONFORMING TO

SVr4, POSIX.1-2001. These functions are obsolete: do not use them in new programs.

NOTES

These functions appeared in glibc version 2.1.

The sighandler_t type is a GNU extension; it is only used on this page to make the sigset() prototype more easily readable.

The sigset() function provides reliable signal handling semantics (as when calling sigaction(2) with sa_mask equal to 0).

On System V, the signal() function provides unreliable semantics (as when calling sigaction(2) with sa_mask equal to SA_RESETHAND | SA_NODEFER). On BSD, signal() provides reliable semantics. POSIX.1-2001 leaves these aspects of signal() unspecified. See signal(2) for further details.

In order to wait for a signal, BSD and System V both provided a function named sigpause(), but this function has a different argument on the two systems. See sigpause(3) for details.

BUGS

In versions of glibc before 2.2, sigset() did not unblock sig if disp was specified as a value other than SIG_HOLD.

In all versions of glibc up to and including 2.3.5, sigset() does not correctly return the previous disposition of the signal in two cases. First, if disp is specified as SIG_HOLD, then a successful sigset() always returns SIG_HOLD. Instead, it should return the previous disposition of the signal (unless the signal was blocked, in which case SIG_HOLD should be returned). Second, if the signal is currently blocked, then the return value of a successful sigset() should be SIG_HOLD. Instead, the previous disposition of the signal is returned.

SEE ALSO

kill(2), pause(2), sigaction(2), signal(2), sigprocmask(2), raise(3), sigpause(3), sigvec(3), feature_test_macros(7), signal(7)


sigvec(3)

SIGVEC

Section: Linux Programmer's Manual (3)
Updated: 2005-12-01 Return to Main Contents

NAME

sigvec, sigblock, sigsetmask, siggetmask, sigmask - BSD signal API

SYNOPSIS

#define _BSD_SOURCE
#include <signal.h>

int sigvec(int sig, struct sigvec *vec, struct sigvec *ovec);

int sigmask(int signum);

int sigblock(int mask);

int sigsetmask(int mask);

int siggetmask(void);

DESCRIPTION

These functions are provided in glibc as a compatibility interface for programs that make use of the historical BSD signal API. This API is obsolete: new applications should use the POSIX signal API (sigaction(2), sigprocmask(2), etc.)

The sigvec() function sets and/or gets the disposition of the signal sig (like the POSIX sigaction(2)). If vec is not NULL, it points to a sigvec structure that defines the new disposition for sig. If ovec is not NULL, it points to a sigvec structure that is used to return the previous disposition of sig. To obtain the current disposition of sig without changing it, specify NULL for vec, and a non-NULL pointer for ovec.

The dispositions for SIGKILL and SIGSTOP cannot be changed.

The sigvec structure has the following form:

struct sigvec {
    void (*sv_handler)();  /* Signal disposition */
    int    sv_mask;        /* Signals to be blocked in handler */
    int    sv_flags;       /* Flags */
};
The sv_handler field specifies the disposition of the signal, and is either: the address of a signal handler function; or SIG_DFL meaning the default disposition applies for the signal; or SIG_IGN meaning that the signal is ignored.

If sv_handler specifies the address of a signal handler, then sv_mask specifies a mask of signals that are to be blocked while the handler is executing. In addition, the signal for which the handler is invoked is also blocked by default. Attempts to block SIGKILL or SIGSTOP are silently ignored.

If sv_handler specifies the address of a signal handler, then the sv_flags field specifies flags controlling what happens when the handler is called. This field may contain zero or more of the following flags:

SV_INTERRUPT
If the signal handler interrupts a blocking system call, then upon return from the handler the system call will not be restarted: instead it will fail with the error EINTR. If this flag is not specified, then system calls are restarted by default.
SV_RESETHAND
Reset the disposition of the signal to the default before calling the signal handler. If this flag is not specified, then the handler remains established until explicitly removed by a later call to sigvec() or until the process performs an execve(2).
SV_ONSTACK
Handle the signal on the alternate signal stack (historically established under BSD using the obsolete sigstack() function; the POSIX replacement is sigaltstack(2)).

The sigmask() function constructs and returns a "signal mask" for signum. For example, we can initialize the vec.sv_mask field given to sigvec() using code such as the following:

    vec.sv_mask = sigmask(SIGQUIT) | sigpause(SIGABRT);
                /* Block SIGQUIT and SIGABRT during
                   handler execution */

The sigblock() function adds the signals in mask to the process's signal mask (like POSIX sigprocmask(SIG_BLOCK)), and returns the process's previous signal mask. Attempts to block SIGKILL or SIGSTOP are silently ignored.

The sigsetmask() function sets the process's signal mask to the value given in mask (like POSIX sigprocmask(SIG_SETMASK)), and returns the process's previous signal mask.

The siggetmask() function returns the process's current signal mask. This call is equivalent to sigblock(0).

RETURN VALUE

The sigvec() function returns 0 on success; on error, it returns -1 and sets errno to indicate the error.

The sigblock() and sigsetmask() functions return the previous signal mask.

The sigmask() function returns the signal mask for signum.

ERRORS

See the ERRORS under sigaction(2) and sigprocmask(2).

CONFORMING TO

All of these functions were in 4.3BSD, except siggetmask(), whose origin is unclear. These functions are obsolete: do not use them in new programs.

NOTES

On 4.3BSD, the signal() function provided reliable semantics (as when calling sigvec() with vec.sv_mask equal to 0). On System V, signal() provides unreliable semantics. POSIX.1-2001 leaves these aspects of signal() unspecified. See signal(2) for further details.

In order to wait for a signal, BSD and System V both provided a function named sigpause(), but this function has a different argument on the two systems. See sigpause(3) for details.

SEE ALSO

kill(2), pause(2), sigaction(2), signal(2), sigprocmask(2), raise(3), sigpause(3), sigset(3), feature_test_macros(7), signal(7)


sem_init(3)

SEM_INIT

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_init - initialize an unnamed semaphore

SYNOPSIS

#include <semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned int value);

DESCRIPTION

sem_init() initializes the unnamed semaphore at the address pointed to by sem. The value argument specifies the initial value for the semaphore.

The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes.

If pshared has the value 0, then the semaphore is shared between the threads of a process, and should be located at some address that is visible to all threads (e.g., a global variable, or a variable allocated dynamically on the heap).

If pshared is non-zero, then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)). (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.) Any process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), etc.

Initializing a semaphore that has already been initialized results in undefined behavior.

RETURN VALUE

sem_init() returns 0 on success; on error, -1 is returned, and errno is set to indicate the error.

ERRORS

EINVAL
value exceeds SEM_VALUE_MAX.
ENOSYS
pshared is non-zero, but the system does not support process-shared semaphores (see sem_overview(7)).

CONFORMING TO

POSIX.1-2001.

NOTES

Bizarrely, POSIX.1-2001 does not specify the value that should be returned by a successful call to sem_init(). However, virtually every implementation returns zero in this case.

SEE ALSO

sem_destroy(3), sem_post(3), sem_wait(3), sem_overview(7)


strchrnul (3)

 Continue to this page.


shm_unlink (3)

 Continue to this page.


open_memstream (3)

 Continue to this page.


mkfifoat(3)

MKFIFOAT

Section: Linux Programmer's Manual (3)
Updated: 2006-04-06 Return to Main Contents

NAME

mkfifoat - make a FIFO (named pipe) relative to a directory file descriptor

SYNOPSIS

#define _ATFILE_SOURCE
#include <sys/stat.h>

int mkfifoat(int dirfd, const char *pathname, mode_t mode);

DESCRIPTION

The mkfifoat() system call operates in exactly the same way as mkfifo(3), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by mkfifo(3) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like mkfifo(3)).

If pathname is absolute, then dirfd is ignored.

RETURN VALUE

On success, mkfifoat() returns 0. On error, -1 is returned and errno is set to indicate the error.

ERRORS

The same errors that occur for mkfifo(3) can also occur for mkfifoat(). The following additional errors can occur for mkfifoat():
EBADF
dirfd is not a valid file descriptor.
ENOTDIR
pathname is a relative path and dirfd is a file descriptor referring to a file other than a directory.

VERSIONS

mkfifoat() was added to glibc in version 2.4. It is implemented using mknod(2), available on Linux since kernel 2.6.16.

CONFORMING TO

This function is non-standard but is proposed for inclusion in a future revision of POSIX.1.

NOTES

See openat(2) for an explanation of the need for mkfifoat().

SEE ALSO

openat(2), mkfifo(3), path_resolution(7)


sigpause(3)

SIGPAUSE

Section: Linux Programmer's Manual (3)
Updated: 2005-12-01 Return to Main Contents

NAME

sigpause - atomically release blocked signals and wait for interrupt

SYNOPSIS

#include <signal.h>

int sigpause(int sigmask);  /* BSD */

int sigpause(int sig);      /* System V / Unix95 */

DESCRIPTION

Don't use this function. Use sigsuspend(2) instead.

The function sigpause() is designed to wait for some signal. It changes the process's signal mask (set of blocked signals), and then waits for a signal to arrive. Upon arrival of a signal, the original signal mask is restored.

RETURN VALUE

If sigpause() returns, it was interrupted by a signal and the return value is -1 with errno set to EINTR.

NOTES

History

The classical BSD version of this function appeared in 4.2BSD. It sets the process's signal mask to sigmask. Unix95 standardized the incompatible System V version of this function, which removes only the specified signal sig from the process' signal mask. The unfortunate situation with two incompatible functions with the same name was solved by the sigsuspend(2) function, that takes a sigset_t * parameter (instead of an int).

Linux Notes

On Linux, this routine is a system call only on the Sparc (sparc64) architecture.

Libc4 and libc5 only know about the BSD version.

Glibc uses the BSD version if the _BSD_SOURCE feature test macro is defined and none of _POSIX_SOURCE, _POSIX_C_SOURCE, _XOPEN_SOURCE, _GNU_SOURCE, or _SVID_SOURCE is defined. The System V version is used if _XOPEN_SOURCE is defined.

SEE ALSO

kill(2), sigaction(2), sigprocmask(2), sigsuspend(2), sigblock(3), sigvec(3), feature_test_macros(7)


sem_open(3)

SEM_OPEN

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_open - initialize and open a named semaphore

SYNOPSIS

#include <semaphore.h>

sem_t *sem_open(const char *name, int oflag);
sem_t *sem_open(const char *name, int oflag,
                mode_t mode, unsigned int value);

DESCRIPTION

sem_open() creates a new POSIX semaphore or opens an existing semaphore. The semaphore is identified by name. For details of the construction of name, see sem_overview(7).

The oflag argument specifies flags that control the operation of the call. If O_CREAT is specified in oflag, then the semaphore is created if it does not already exist. The owner (user ID) of the semaphore is set to the effective user ID of the calling process. The group ownership (group ID) is set to the effective group ID of the calling process. If both O_CREAT and O_EXCL are specified in oflag, then an error is returned if a semaphore with the given name already exists.

If O_CREAT is specified in oflag, then two additional arguments must be supplied. The mode argument specifies the permissions to be placed on the new semaphore, as for open(2). The permissions settings are masked against the process umask. Both read and write permission should be granted to each class of user that will access the semaphore. The value argument specifies the initial value for the new semaphore. If O_CREAT is specified, and a semaphore with the given name already exists, then mode and value are ignored.

RETURN VALUE

On success, sem_open() returns the address of the new semaphore; this address is used when calling other semaphore-related functions. On error, sem_open() returns SEM_FAILED, with errno set to indicate the error.

ERRORS

EACCES
The semaphore exists, but the caller does not have permission to open it.
EEXIST
Both O_CREAT and O_EXCL were specified in oflag, but a semaphore with this name already exists.
EINVAL
value was greater than SEM_VALUE_MAX.
EMFILE
The process already has the maximum number of files and open.
ENAMETOOLONG
name was too long.
ENFILE
The system limit on the total number of open files has been reached.
ENOENT
The O_CREAT flag was not specified in oflag, and no semaphore with this name exists.
ENOMEM
Insufficient memory.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

sem_close(3), sem_getvalue(3), sem_post(3), sem_unlink(3), sem_wait(3), sem_overview(7)


sigsetmask (3)

 Continue to this page.


FD_ZERO (3)

 Continue to this page.


sem_post(3)

SEM_POST

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_post - unlock a semaphore

SYNOPSIS

#include <semaphore.h>

int sem_post(sem_t *sem);

DESCRIPTION

sem_post() increments (unlocks) the semaphore pointed to by sem. If the semaphore's value consequently becomes greater than zero, then another process or thread blocked in a sem_wait(3) call will be woken up and proceed to lock the semaphore.

RETURN VALUE

sem_post() returns 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.

ERRORS

EINVAL
sem is not a valid semaphore.

CONFORMING TO

POSIX.1-2001.

NOTES

sem_post() is async-signal-safe: it may be safely called within a signal handler.

SEE ALSO

sem_getvalue(3), sem_wait(3), sem_overview(7)


CPU_ZERO (3)

 Continue to this page.


sem_trywait (3)

 Continue to this page.


sigorset (3)

 Continue to this page.


rpmatch(3)

RPMATCH

Section: Linux Programmer's Manual (3)
Updated: 2006-05-17 Return to Main Contents

NAME

rpmatch - determine if the answer to a question is affirmative or negative

SYNOPSIS

#define _SVID_SOURCE
#include <stdlib.h>

int rpmatch(const char *response);

DESCRIPTION

rpmatch() handles a user response to yes or no questions, with support for internationalization.

response should be a null-terminated string containing a user-supplied response, perhaps obtained with fgets(3) or getline(3).

The user's language preference is taken into account per the environment variables LANG, LC_MESSAGES, and LC_ALL, if the program has called setlocale(3) to effect their changes.

Regardless of the locale, responses matching ^[Yy] are always accepted as affirmative, and those matching ^[Nn] are always accepted as negative.

RETURN VALUE

After examining response, rpmatch() returns 0 for a recognized negative response ("no"), 1 for a recognized positive response ("yes"), and -1 when the value of response is unrecognized.

ERRORS

A return value of -1 may indicate either an invalid input, or some other error. It is incorrect to only test if the return value is nonzero.

rpmatch() can fail for any of the reasons that regcomp(3) or regexec(3) can fail; the cause of the error is not available from errno or anywhere else, but indicates a failure of the regex engine (but this case is indistinguishable from that of an unrecognized value of response).

CONFORMING TO

rpmatch() is not required by any standard, but is available on a few other systems.

BUGS

The rpmatch() implementation looks at only the first character of response. As a consequence, "nyes" returns 0, and "ynever; not in a million years" returns 1. It would be preferable to accept input strings much more strictly, for example (using the extended regular expression notation described in regex(7)): ^([yY]|yes|YES)$ and ^([nN]|no|NO)$.

EXAMPLE

The following program displays the results when rpmatch() is applied to the string given in the program's command-line argument.

#define _SVID_SOURCE
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
    if (argc != 2 || strcmp(argv[1], "--help") == 0) {
        fprintf(stderr, "%s response\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    setlocale(LC_ALL, "");
    printf("rpmatch() returns: %d\n", rpmatch(argv[1]));
    exit(EXIT_SUCCESS);
}

SEE ALSO

regcomp(3), fgets(3), getline(3), nl_langinfo(3), setlocale(3), feature_test_macros(7)


eaccess (3)

 Continue to this page.


sem_wait(3)

SEM_WAIT

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_wait, sem_timedwait, sem_trywait - lock a semaphore

SYNOPSIS

#include <semaphore.h>

int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);

#define _XOPEN_SOURCE 600
#include <semaphore.h>

int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

DESCRIPTION

sem_wait() decrements (locks) the semaphore pointed to by sem. If the semaphore's value is greater than zero, then the decrement proceeds, and the function returns, immediately. If the semaphore currently has the value zero, then the call blocks until either it becomes possible to perform the decrement (i.e., the semaphore value rises above zero), or a signal handler interrupts the call.

sem_trywait() is the same as sem_wait(), except that if the decrement cannot be immediately performed, then call returns an error (errno set to EAGAIN) instead of blocking.

sem_timedwait() is the same as sem_wait(), except that abs_timeout specifies a limit on the amount of time that the call should block if the decrement cannot be immediately performed. The abs_timeout argument points to a structure that specifies an absolute timeout in seconds and nanoseconds since the Epoch (00:00:00, 1 January 1970). This structure is defined as follows:

struct timespec {
    time_t tv_sec;      /* Seconds */
    long   tv_nsec;     /* Nanoseconds [0 .. 999999999] */
};

If the timeout has already expired by the time of the call, and the semaphore could not be locked immediately, then sem_timedwait() fails with a timeout error (errno set to ETIMEDOUT).

If the operation can be performed immediately, then sem_timedwait() never fails with a timeout error, regardless of the value of abs_timeout. Furthermore, the validity of abs_timeout is not checked in this case.

RETURN VALUE

All of these functions return 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.

ERRORS

EINTR
The call was interrupted by a signal handler.
EINVAL
sem is not a valid semaphore.

The following additional error can occur for sem_trywait():

EAGAIN
The operation could not be performed without blocking (i.e., the semaphore currently has the value zero).

The following additional errors can occur for sem_timedwait():

EINVAL
The value of abs_timeout.tv_nsecs is less than 0, or greater than or equal to 1000 million.
ETIMEDOUT
The call timed out before the semaphore could be locked.

CONFORMING TO

POSIX.1-2001.

NOTES

A signal handler always interrupts a blocked call to one of these functions, regardless of the use of the sigaction(2) SA_RESTART flag.

EXAMPLE

The (somewhat trivial) program shown below operates on an unnamed semaphore. The program expects two command-line arguments. The first argument specifies a seconds value that is used to set an alarm timer to generate a SIGALRM signal. This handler performs a sem_post(3) to increment the semaphore that is being waited on in main() using sem_timedwait(). The second command-line argument specifies the length of the timeout, in seconds, for sem_timedwait(). The following shows what happens on two different runs of the program:

$ ./a.out 2 3
About to call sem_timedwait()
sem_post() from handler
sem_getvalue() from handler; value = 1
sem_timedwait() succeeded
$ ./a.out 2 1
About to call sem_timedwait()
sem_timedwait() timed out

The source code of the program is as follows:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>

#define die(msg) { perror(msg); exit(EXIT_FAILURE); }

sem_t sem;

static void
handler(int sig)
{
    int sval;

    printf("sem_post() from handler\n");
    if (sem_post(&sem) == -1)
        die("sem_post");

    if (sem_getvalue(&sem, &sval) == -1)
        die("sem_getvalue");
    printf("sem_getvalue() from handler; value = %d\n", sval);
} /* handler */

int
main(int argc, char *argv[])
{
    struct sigaction sa;
    struct timespec ts;
    int s;

    assert(argc == 3);  /* Usage: ./a.out alarm-secs wait-secs */

    if (sem_init(&sem, 0, 0) == -1)
        die("sem_init");

    /* Establish SIGALRM handler; set alarm timer using argv[1] */

    sa.sa_handler = handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGALRM, &sa, NULL) == -1)
        die("sigaction");

    alarm(atoi(argv[1]));

    /* Calculate relative interval as current time plus
       number of seconds given argv[2] */

    if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
        die("clock_gettime");
    ts.tv_sec += atoi(argv[2]);

    printf("main() about to call sem_timedwait()\n");
    while ((s = sem_timedwait(&sem, &ts)) == -1 && errno == EINTR)
        continue;       /* Restart when interrupted by handler */

    /* Check what happened */

    if (s == -1) {
        if (errno == ETIMEDOUT)
            printf("sem_timedwait() timed out\n");
        else
            die("sem_timedwait");
    } else
        printf("sem_timedwait() succeeded\n");

    exit(EXIT_SUCCESS);
}

SEE ALSO

sem_getvalue(3), sem_post(3), feature_test_macros(7), sem_overview(7)


siggetmask (3)

 Continue to this page.


sigblock (3)

 Continue to this page.


sem_destroy(3)

SEM_DESTROY

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_destroy - destroy an unnamed semaphore

SYNOPSIS

#include <semaphore.h>

int sem_destroy(sem_t *sem);

DESCRIPTION

sem_destroy() destroys the unnamed semaphore at the address pointed to by sem.

Only a semaphore that has been initialized by sem_init(3) should be destroyed using sem_destroy().

Destroying a semaphore that other processes or threads are currently blocked on (in sem_wait(3)) produces undefined behavior.

Using a semaphore that has been destroyed produces undefined results, until the semaphore has been reinitialized using sem_init(3).

RETURN VALUE

sem_destroy() returns 0 on success; on error, -1 is returned, and errno is set to indicate the error.

ERRORS

EINVAL
sem is not a valid semaphore.

CONFORMING TO

POSIX.1-2001.

NOTES

An unnamed semaphore should be destroyed with sem_destroy() before the memory in which it is located is deallocated. Failure to do this can result in resource leaks on some implementations.

SEE ALSO

sem_init(3), sem_post(3), sem_wait(3), sem_overview(7)


offsetof(3)

OFFSETOF

Section: Linux Programmer's Manual (3)
Updated: 2006-05-23 Return to Main Contents

NAME

offsetof - offset of a structure member

SYNOPSIS

#include <stddef.h>

size_t offsetof(type, member);

DESCRIPTION

The macro offsetof() returns the offset of the field member from the start of the structure type.

This macro is useful because the sizes of the fields that compose a structure can vary across implementations, and compilers may insert different numbers of padding bytes between fields. Consequently, an element's offset is not necessarily given by the sum of the sizes of the previous elements.

A compiler error will result if member is not aligned to a byte boundary (i.e., it is a bit field).

RETURN VALUE

offsetof() returns the offset of the given element within the given type, in units of bytes.

CONFORMING TO

C89, C99, POSIX.1-2001.

EXAMPLE

On a Linux/x86 system, when compiled using the default gcc(1) options, the program below produces the following output:

$ ./a.out
offsets: i=0; c=4; d=8 a=16
sizeof(struct s)=16

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    struct s {
        int i;
        char c;
        double d;
        char a[];
    };

    /* Output is compiler dependent */

    printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
            (long) offsetof(struct s, i),
            (long) offsetof(struct s, c),
            (long) offsetof(struct s, d),
            (long) offsetof(struct s, a));
    printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));

    exit(EXIT_SUCCESS);
}


error(3)

ERROR

Section: Linux Programmer's Manual (3)
Updated: 2006-04-25 Return to Main Contents

NAME

error, error_at_line, error_message_count, error_on_per_line, error_print_progname - glibc error reporting functions

SYNOPSIS

#include <error.h>

void error(int status, int errnum, const char *format, ...);

void error_at_line(int status, int errnum, const char *filename,
                   unsigned int linenum, const char *format, ...);

extern unsigned int error_message_count;

extern int error_one_per_line;

extern void (* error_print_progname) (void);

DESCRIPTION

error() is a general error reporting function. It flushes stdout, and then outputs to stderr the program name, a colon and a space, the message specified by the printf(3)-style format string format, and, if errnum is non-zero, a second colon and a space followed by the string given by perror(errnum). Any arguments required for format should follow format in the argument list. The output is terminated by a newline character.

The program name printed by error() is the value of the global variable program_invocation_name(3). program_invocation_name initially has the same value as main()'s argv[0]. The value of this variable can be modified to change the output of error().

If status has a non-zero value, then error() calls exit(3) to terminate the program using the given value as the exit status.

The error_at_line() function is exactly the same as error(), except for the addition of the arguments filename and linenum. The output produced is as for error(), except that after the program name are written: a colon, the value of filename, a colon, and the value of linenum. The preprocessor values __LINE__ and __FILE__ may be useful when calling error_at_line(), but other values can also be used. For example, these arguments could refer to a location in an input file.

If the global variable error_one_per_line is set non-zero, a sequence of error_at_line() calls with the same value of filename and linenum will result in only one message (the first) being output.

The global variable error_message_count counts the number of messages that have been output by error() and error_at_line().

If the global variable error_print_progname is assigned the address of a function (i.e., is not NULL), then that function is called instead of prefixing the message with the program name and colon. The function should print a suitable string to stderr.

CONFORMING TO

These functions and variables are GNU extensions, and should not be used in programs intended to be portable.

SEE ALSO

err(3), errno(3), exit(3), perror(3), program_invocation_name(3), strerror(3)


fexecve(3)

FEXECVE

Section: Linux Programmer's Manual (3)
Updated: 2006-03-06 Return to Main Contents

NAME

fexecve - execute program specified via file descriptor

SYNOPSIS

#include <sys/time.h>

int fexecve(int fd, char *const argv[], char *const envp[]);

DESCRIPTION

fexecve() performs the same task as execve(2), with the difference that the file to be executed is specified via a file descriptor, fd, rather than via a pathname.

RETURN VALUE

A successful call to fexecve() never returns. On error, the function returns, with a result value of -1 is returned, and errno is set appropriately.

ERRORS

Errors are as for execve(2), with the following additions:
EINVAL
fd is not a valid file descriptor, or argv is NULL, or envp is NULL.
ENOSYS
The /proc file system could not be accessed.

VERSIONS

fexecve() is implemented since glibc 2.3.2.

CONFORMING TO

This function is Linux specific. It is under consideration for inclusion in a future version of POSIX.1.

SEE ALSO

execve(2)


program_invocation_name(3)

PROGRAM_INVOCATION_NAME

Section: Linux Programmer's Manual (3)
Updated: 2006-04-29 Return to Main Contents

NAME

program_invocation_name, program_invocation_short_name - obtain name used to invoke calling program

SYNOPSIS

#define _GNU_SOURCE
#include <errno.h>

extern char *program_invocation_name;
extern char *program_invocation_short_name;

DESCRIPTION

program_invocation_name contains the name that was used to invoke the calling program. This is the same as the value of argv[0] in main(), with the difference that the scope of program_invocation_name is global.

program_invocation_short_name contains the basename component of name that was used to invoke the calling program. That is, it is the same value as program_invocation_name, with all text up to and including the final slash (/), if any, removed.

These variables are automatically initialized by the glibc run-time startup code.

CONFORMING TO

These variables are GNU extensions, and should not be used in programs intended to be portable.

NOTES

The Linux-specific /proc/[number]/cmdline file provides access to similar information.

SEE ALSO

proc(5), feature_test_macros(7)


sigignore (3)

 Continue to this page.


FD_CLR (3)

 Continue to this page.


CPU_CLR (3)

 Continue to this page.


sem_getvalue(3)

SEM_GETVALUE

Section: Linux Programmer's Manual (3)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_getvalue - get the value of a semaphore

SYNOPSIS

#include <semaphore.h>

int sem_getvalue(sem_t *sem, int *sval);

DESCRIPTION

sem_getvalue() places the current value of the semaphore pointed to sem into the integer pointed to by sval.

If one or more processes or threads are blocked waiting to lock the semaphore with sem_wait(3), POSIX.1-2001 permits two possibilities for the value returned in sval: either 0 is returned; or a negative number whose absolute value is the count of the number of processes and threads currently blocked in sem_wait(3). Linux adopts the former behavior.

RETURN VALUE

sem_getvalue() returns 0 on success; on error, -1 is returned and errno is set to indicate the error.

ERRORS

EINVAL
sem is not a valid semaphore.

CONFORMING TO

POSIX.1-2001.

NOTES

The value of the semaphore may already have changed by the time sem_getvalue() returns.

SEE ALSO

sem_post(3), sem_wait(3), sem_overview(7)


canonicalize_file_name(3)

CANONICALIZE_FILE_NAME

Section: Linux Programmer's Manual (3)
Updated: 2005-07-14 Return to Main Contents

NAME

canonicalize_file_name - return the canonicalized filename

SYNOPSIS

#define _GNU_SOURCE
#include <stdlib.h>

char *canonicalize_file_name(const char *path);

DESCRIPTION

The call canonicalize_file_name(path) is equivalent to the call realpath(path, NULL).

CONFORMING TO

The function is a GNU extension.

SEE ALSO

realpath(3), feature_test_macros(7)


FD_SET (3)

 Continue to this page.


CPU_SET (3)

 Continue to this page.


posix_fallocate(3)

POSIX_FALLOCATE

Section: Linux Programmer's Manual (3)
Updated: 2006-03-01 Return to Main Contents

NAME

posix_fallocate - allocate file space

SYNOPSIS

#define _XOPEN_SOURCE 600
#include <stdlib.h>

int posix_fallocate(int fd, off_t offset, off_t len);

DESCRIPTION

The function posix_fallocate() ensures that disk space is allocated for the file referred to by the descriptor fd for the bytes in the range starting at offset and continuing for len bytes. After a successful call to posix_fallocate(), subsequent writes to bytes in the specified range are guaranteed not to fail because of lack of disk space.

If the size of the file is less than offset+len, then the file is increased to this size; otherwise the file size is left unchanged.

RETURN VALUE

posix_fallocate() returns zero on success, or an error number on failure. Note that errno is not set.

ERRORS

EBADF
fd is not a valid file descriptor, or is not opened for writing.
EFBIG
offset+len exceeds the maximum file size.
EINVAL
offset or len was less than 0.
ENODEV
fd does not refer to a regular file.
ENOSPC
There is not enough space left on the device containing the file referred to by fd.
ESPIPE
fd refers to a pipe of file descriptor.

VERSIONS

posix_fallocate() is available since glibc 2.1.94.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

lseek(2), posix_fadvise(2), feature_test_macros(7)


futimes(3)

FUTIMES

Section: Linux Programmer's Manual (3)
Updated: 2006-03-06 Return to Main Contents

NAME

futimes - change access and/or modification times of an open file

SYNOPSIS

#include <sys/time.h>

int futimes(int fd, const struct timeval tv[2]);

DESCRIPTION

futimes() changes the access and modification times of a file in the same way as utimes(2), with the difference that the file whose timestamps are to be changed is specified via a file descriptor, fd, rather than via a pathname.

RETURN VALUE

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS

Errors are as for utimes(2), with the following additions:
EBADF
fd is not a valid file descriptor.
ENOSYS
The /proc file system could not be accessed.

VERSIONS

futimes() is available since glibc 2.3.

CONFORMING TO

4.2BSD. Other than Linux, this function is only available on the BSDs.

SEE ALSO

futimesat(2), utime(2)


sigandset (3)

 Continue to this page.


sigrelse (3)

 Continue to this page.


bsd_signal(3)

BSD_SIGNAL

Section: Linux Programmer's Manual (3)
Updated: 2007-05-04 Return to Main Contents

NAME

bsd_signal - signal handling with BSD semantics

SYNOPSIS

#define _XOPEN_SOURCE
#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t bsd_signal(int signum, sighandler_t handler);

DESCRIPTION

The bsd_signal() function takes the same arguments, and performs the same task, as signal(2).

The difference between the two is that bsd_signal() is guaranteed to provide reliable signal semantics, that is: a) the disposition of the signal is not reset to the default when the handler is invoked; b) delivery of further instances of the signal is blocked while the signal handler is executing; and c) if the handler interrupts a blocking system call, then the system call is automatically restarted. A portable application cannot rely on signal(2) to provide these guarantees.

RETURN VALUE

The bsd_signal() function returns the previous value of the signal handler, or SIG_ERR on error.

ERRORS

As for signal(2).

CONFORMING TO

4.2BSD, POSIX.1-2001.

NOTES

Use of bsd_signal() should be avoided; use sigaction(2) instead.

On modern Linux systems, bsd_signal() and signal(2) are equivalent. But on older systems, signal(2) provided unreliable signal semantics; see signal(2) for details.

The use of sighandler_t is a GNU extension; this type is only defined if the _GNU_SOURCE feature test macro is defined.

SEE ALSO

sigaction(2), signal(2), sysv_signal(3), feature_test_macros(7), signal(7)


error_message_count (3)

 Continue to this page.


sockatmark(3)

SOCKATMARK

Section: Linux Programmer's Manual (3)
Updated: 2006-04-24 Return to Main Contents

NAME

sockatmark - determine whether socket is at out-of-band mark

SYNOPSIS

#include <sys/socket.h>

int sockatmark(int fd);

DESCRIPTION

sockatmark() returns a value indicating whether or not the socket referred to by the file descriptor fd is at the out-of-band mark. If the socket is at the mark, then 1 is returned; if the socket is not at the mark, 0 is returned. This function does not remove the out-of-band mark.

RETURN VALUE

A successful call to sockatmark() returns 1 if the socket is at the out-of-band mark, or 0 if it is not. On error, -1 is returned and errno is set to indicate the error.

ERRORS

EBADF
fd is not a valid file descriptor.
EINVAL
fd is not a file descriptor to which sockatmark() can be applied.

VERSIONS

sockatmark() was added to glibc in version 2.2.4.

CONFORMING TO

POSIX.1-2001

NOTES

If sockatmark() returns 1, then the out-of-band data can be read using the MSG_OOB flag of recv(2).

Out-of-band data is only supported on some stream socket protocols.

sockatmark() can safely be called from a handler for the SIGURG signal.

sockatmark() is implemented using the SIOCATMARK ioctl(2) operation.

BUGS

Prior to glibc 2.4, sockatmark() did not work.

EXAMPLE

The following code can be used after receipt of a SIGURG signal to read (and discard) all data up to the mark, and then read the byte of data at the mark:

    char buf[BUF_LEN];
    char oobdata;
    int atmark, s;

    for (;;) {
        atmark = sockatmark(fd);
        if (atmark == -1) {
            perror("sockatmark");
            break;
        }

        if (atmark)
            break;

        s = read(fd, buf, BUF_LEN) <= 0);
        if (s == -1)
            perror("read");
        if (s <= 0)
            break;
    }

    if (atmark == 1) {
        if (recv(fd, &oobdata, 1, MSG_OOB) == -1) {
            perror("recv");
            ...
        }
    }

SEE ALSO

fcntl(2), recv(2), send(2), tcp(7)


mq_receive(3)

MQ_RECEIVE

Section: Linux Programmer's Manual (3)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_receive, mq_timedreceive - receive a message from a message queue

SYNOPSIS

#include <mqueue.h>

ssize_t mq_receive(mqd_t mqdes, char *msg_ptr,
                   size_t msg_len, unsigned *msg_prio);

#define _XOPEN_SOURCE 600
#include <time.h>
#include <mqueue.h>

ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr,
                   size_t msg_len, unsigned *msg_prio,
                   const struct timespec *abs_timeout);

DESCRIPTION

mq_receive() removes the oldest message with the highest priority from the message queue referred to by the descriptor mqdes, and places it in the buffer pointed to by msg_ptr. The msg_len argument specifies the size of the buffer pointed to by msg_ptr; this must be greater than the mq_msgsize attribute of the queue (see mq_getattr(3)). If prio is not NULL, then the buffer to which it points is used to return the priority associated with the received message.

If the queue is empty, then, by default, mq_receive() blocks until a message becomes available, or the call is interrupted by a signal handler. If the O_NONBLOCK flag is enabled for the message queue description, then the call instead fails immediately with the error EAGAIN.

mq_timedreceive() behaves just like mq_receive(), except that if the queue is empty and the O_NONBLOCK flag is not enabled for the message queue description, then abs_timeout points to a structure which specifies a ceiling on the time for which the call will block. This ceiling is an absolute timeout in seconds and nanoseconds since the Epoch (midnight on the morning of 1 January 1970), specified in the following structure:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};
If no message is available, and the timeout has already expired by the time of the call, mq_timedreceive() returns immediately.

RETURN VALUE

On success, mq_receive() and mq_timedreceive() return the number of bytes in the received message; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EAGAIN
The queue was empty, and the O_NONBLOCK flag was set for the message queue description referred to by mqdes.
EBADF
The descriptor specified in mqdes was invalid.
EMSGSIZE
msg_len was less than the mq_msgsize attribute of the message queue.
EINTR
The call was interrupted by a signal handler.
EINVAL
The call would have blocked, and abs_timeout was invalid, either because tv_sec was less than zero, or because tv_nsec was less than zero or greater than 1000 million.
ETIMEDOUT
The call timed out before a message could be transferred.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_send(3), mq_unlink(3), feature_test_macros(7), mq_overview(7)


mq_setattr (3)

 Continue to this page.


mq_close(3)

MQ_CLOSE

Section: Linux Programmer's Manual (3)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_close - close a message queue descriptor

SYNOPSIS

#include <mqueue.h>

mqd_t mq_close(mqd_t mqdes);

DESCRIPTION

mq_close() closes the message queue descriptor mqdes.

If the calling process has attached a notification request to this message queue via mqdes, then this request is removed, and another process can now attach a notification request.

RETURN VALUE

On success mq_close() returns 0; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EBADF
The descriptor specified in mqdes is invalid.

CONFORMING TO

POSIX.1-2001.

NOTES

All open message queues are automatically closed on process termination, or upon execve(2).

SEE ALSO

mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), mq_overview(7)


sem_timedwait (3)

 Continue to this page.


fmemopen(3)

FMEMOPEN

Section: Linux Programmer's Manual (3)
Updated: 2005-12-08 Return to Main Contents

NAME

fmemopen, open_memstream - open memory as stream

SYNOPSIS

#define _GNU_SOURCE
#include <stdio.h>

FILE *fmemopen(void *buf, size_t size, const char *mode);

FILE *open_memstream(char **ptr, size_t *sizeloc)

DESCRIPTION

The fmemopen() function opens a stream that permits the access specified by mode. The stream allows I/O to be performed on the string or memory buffer pointed to by buf. This buffer must be at least size bytes long.

The argument mode is the same as for fopen(3). If mode specifies an append mode, then the initial file position is set to location of the first null byte ('\0') in the buffer; otherwise the initial file position is set to the start of the buffer.

When a stream that has been opened for writing is flushed (fflush(3)) or closed (fclose(3)), a null byte is written at the end of the buffer if there is space. The caller should ensure that an extra byte is available in the buffer (and that size counts that byte) to allow for this.

Attempts to write more than size bytes to the buffer result in an error. (By default, such errors will only be visible when the stdio buffer is flushed. Disabling buffering with setbuf(fp, NULL) may be useful to detect errors at the time of an output operation. Alternatively, the caller can explicitly set buf as the stdio stream buffer, at the same time informing stdio of the buffer's size, using setbuffer(fp, buf, size).)

In a stream opened for reading, null bytes ('\0') in the buffer do not cause read operations to return an end-of-file indication. A read from the buffer will only indicate end-of-file when the file pointer advances size bytes past the start of the buffer.

If buf is specified as NULL, then fmemopen() dynamically allocates a buffer size bytes long. This is useful for an application that wants to write data to a temporary buffer and then read it back again. The buffer is automatically freed when the stream is closed. Note that the caller has no way to obtain a pointer to the temporary buffer allocated by this call (but see open_memstream() below).

The open_memstream() opens a stream for writing to a buffer. The buffer is dynamically allocated (as with malloc(3)), and automatically grows as required. After closing the stream, the caller should free(3) this buffer.

When the stream is closed (fclose(3)) or flushed (fflush(3)), the locations pointed to by ptr and sizeloc are updated to contain, respectively, a pointer to the buffer and the current size of the buffer. These values remain valid only as long as the caller performs no further output on the stream. If further output is performed, then the stream must again be flushed before trying to access these variables.

A null byte is maintained at the end of the buffer. This byte is not included in the size value stored at sizeloc.

RETURN VALUE

Upon successful completion fmemopen() and open_memstream() return a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

CONFORMING TO

These functions are GNU extensions.

EXAMPLE

The program below uses fmemopen() to open an input buffer, and open_memstream() to open a dynamically sized output buffer. The program scans its input string (taken from the program's first command-line argument) reading integers, and writes the squares of these integers to the output buffer. An example of the output produced by this program is the following:

$ ./a.out "1 23 43"
size=11; ptr=1 529 1849

#define _GNU_SOURCE
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define die(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)

int
main(int argc, char *argv[])
{
    FILE *out, *in;
    int v, s;
    size_t size;
    char *ptr;

    assert(argc == 2);

    in = fmemopen(argv[1], strlen(argv[1]), "r");
    if (in == NULL)
        die("fmemopen");

    out = open_memstream(&ptr, &size);
    if (out == NULL)
        die("fmemopen");

    for (;;) {
        s = fscanf(in, "%d", &v);
        if (s <= 0)
            break;

        s = fprintf(out, "%d ", v * v);
        if (s == -1)
            die("fprintf");
    }
    fclose(in);
    fclose(out);
    printf("size=%ld; ptr=%s\n", (long) size, ptr);
    free(ptr);
    exit(EXIT_SUCCESS);
}

SEE ALSO

fopen(3), feature_test_macros(7)


mq_timedreceive (3)

 Continue to this page.


error_print_progname (3)

 Continue to this page.


mq_getattr(3)

MQ_GETATTR

Section: Linux Programmer's Manual (3)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_getattr, mq_setattr - get/set message queue attributes

SYNOPSIS

#include <mqueue.h>

mqd_t mq_getattr(mqd_t mqdes, struct mq_attr *attr);
mqd_t mq_setattr(mqd_t mqdes, struct mq_attr *newattr,
                 struct mq_attr *oldattr);

DESCRIPTION

mq_getattr() and mq_setattr() respectively retrieve and modify attributes of the message queue referred to by the descriptor mqdes.

mq_getattr() returns an mq_attr structure in the buffer pointed by attr. This structure is defined as:

struct mq_attr {
    long mq_flags;       /* Flags: 0 or O_NONBLOCK */
    long mq_maxmsg;      /* Max. # of messages on queue */
    long mq_msgsize;     /* Max. message size (bytes) */
    long mq_curmsgs;     /* # of messages currently in queue */
};

The mq_flags field contains flags associated with the open message queue description. This field is initialized when the queue is created by mq_open(3). The only flag that can appear in this field is O_NONBLOCK.

The mq_maxmsg and mq_msgsize fields are set when the message queue is created by mq_open(3). The mq_maxmsg field is an upper limit on the number of messages that may be placed on the queue using mq_send(3). The mq_msgsize field is an upper limit on the size of messages that may be placed on the queue. Both of these fields must have a value greater than zero. Two /proc files that place ceilings on the values for these fields are described in mq_open(3).

The mq_curmsgs field returns the number of messages currently held in the queue.

mq_setattr() sets message queue attributes using information supplied in the mq_attr structure pointed to by newattr. The only attribute that can be modified is the setting of the O_NONBLOCK flag in mq_flags. The other fields in newattr are ignored. If the oldattr field is not NULL, then the buffer that it points to is used to return an mq_attr structure that contains the same information that is returned by mq_getattr().

RETURN VALUE

On success mq_getattr() and mq_setattr() return 0; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EBADF
The descriptor specified in mqdes is invalid.
EINVAL
newattr->mq_flags contained set bits other than O_NONBLOCK.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

mq_close(3), mq_notify(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), mq_overview(7)


mq_notify(3)

MQ_NOTIFY

Section: Linux Programmer's Manual (3)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_notify - register for notification when a message is available

SYNOPSIS

#include <mqueue.h>

mqd_t mq_notify(mqd_t mqdes, const struct sigevent *notification);

DESCRIPTION

mq_notify() allows the calling process to register or unregister for delivery of an asynchronous notification when a new message arrives on the empty message queue referred to by the descriptor mqdes.

The notification argument is a pointer to a sigevent structure that is defined something like the following:

union sigval {                /* Data passed with notification */
    int     sival_int;        /* Integer value */
    void   *sival_ptr;        /* Pointer value */
};

struct sigevent {
    int    sigev_notify;      /* Notification method */
    int    sigev_signo;       /* Notification signal */
    union sigval sigev_value; /* Data passed with notification */
    void (*sigev_notify_function) (union sigval);
                              /* Function for thread notification */
    void  *sigev_notify_attributes;
                              /* Thread function attributes */
};

If notification is a non-NULL pointer, then mq_notify() registers the calling process to receive message notification. The sigev_notify field of the sigevent to which notification points specifies how notification is to be performed. This field has one of the following values:

SIGEV_NONE
A "null" notification: the calling process is registered as the target for notification, but when a message arrives, no notification is sent.
SIGEV_SIGNAL
Notify the process by sending the signal specified in sigev_signo. If the signal is caught with a signal handler that was registered using the sigaction(2) SA_SIGINFO flag, then the following fields are set in the siginfo_t structure that is passed as the second argument of the handler: si_code is set to SI_MESGQ; si_signo is set to the signal number; si_value is set to the value specified in notification->sigev_value; si_pid is set to the PID of the process that sent the message; and si_uid is set to the real user ID of the sending process. The same information is available if the signal is accepted using sigwaitinfo(2).
SIGEV_THREAD
Deliver notification by invoking notification->sigev_thread_function as the start function of a new thread. The function is invoked with notification->sigev_value as its sole argument. If notification->sigev_notify_attributes is not NULL, then it should point to a pthread_attr_t structure that defines attributes for the thread.

Only one process can be registered to receive notification from a message queue.

If notification is NULL, and the calling process is currently registered to receive notifications for this message queue, then the registration is removed; another process can then register to receive a message notification for this queue.

Message notification only occurs when a new message arrives and the queue was previously empty. If the queue was not empty at the time mq_notify() was called, then a notification will only occur after the queue is emptied and a new message arrives.

If another process or thread is waiting to read a message from an empty queue using mq_receive(3), then any message notification registration is ignored: the message is delivered to the process or thread calling mq_receive(3), and the message notification registration remains in effect.

Notification occurs once: after a notification is delivered, the notification registration is removed, and another process can register for message notification. If the notified process wishes to receive the next notification, it can use mq_notify() to request a further notification. This should be done before emptying all unread messages from the queue. (Placing the queue in non-blocking mode is useful for emptying the queue of messages without blocking once it is empty.)

RETURN VALUE

On success mq_notify() returns 0; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EBADF
The descriptor specified in mqdes is invalid.
EBUSY
Another process has already registered to receive notification for this message queue.
EINVAL
notification->sigev_notify is not one of the permitted values; or notification->sigev_notify is SIGEV_SIGNAL and notification->sigev_signo is not a valid signal number.
ENOMEM
Insufficient memory.

CONFORMING TO

POSIX.1-2001.

EXAMPLE

The following program registers a notification request for the message queue named in its command-line argument. Notification is performed by creating a thread. The thread executes a function which reads one message from the queue and then terminates the process.

#include <pthread.h>
#include <mqueue.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define die(msg) { perror(msg); exit(EXIT_FAILURE); }

static void                     /* Thread start function */
tfunc(union sigval sv)
{
    struct mq_attr attr;
    ssize_t nr;
    void *buf;
    mqd_t mqdes = *((mqd_t *) sv.sival_ptr);

    /* Determine max. msg size; allocate buffer to receive msg */

    if (mq_getattr(mqdes, &attr) == -1) die("mq_getattr");
    buf = malloc(attr.mq_msgsize);
    if (buf == NULL) die("malloc");

    nr = mq_receive(mqdes, buf, attr.mq_msgsize, NULL);
    if (nr == -1) die("mq_receive");

    printf("Read %ld bytes from MQ\n", (long) nr);
    free(buf);
    exit(EXIT_SUCCESS);         /* Terminate the process */
}

int
main(int argc, char *argv[])
{
    mqd_t mqdes;
    struct sigevent not;

    assert(argc == 2);

    mqdes = mq_open(argv[1], O_RDONLY);
    if (mqdes == (mqd_t) -1) die("mq_open");

    not.sigev_notify = SIGEV_THREAD;
    not.sigev_notify_function = tfunc;
    not.sigev_notify_attributes = NULL;
    not.sigev_value.sival_ptr = &mqdes;   /* Arg. to thread func. */
    if (mq_notify(mqdes, &not) == -1) die("mq_notify");

    pause();    /* Process will be terminated by thread function */
}

SEE ALSO

mq_close(3), mq_getattr(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), mq_overview(7)


FD_ISSET (3)

 Continue to this page.


mq_unlink(3)

MQ_UNLINK

Section: Linux Programmer's Manual (3)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_unlink - remove a message queue

SYNOPSIS

#include <mqueue.h>

mqd_t mq_unlink(const char *name);

DESCRIPTION

mq_unlink() removes the specified message queue name. The message queue name is removed immediately. The queue itself is destroyed once any other processes that have the queue open close their descriptors referring to the queue.

RETURN VALUE

On success mq_unlink() returns 0; on error, -1 is returned, with errno set to indicate the error.

ERRORS

EACCES
The caller does not have permission to unlink this message queue.
ENAMETOOLONG
name was too long.
ENOENT
There is no message queue with the given name.

CONFORMING TO

POSIX.1-2001.

SEE ALSO

mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_send(3), mq_overview(7)


euidaccess(3)

EUIDACCESS

Section: Linux Programmer's Manual (3)
Updated: 2007-05-18 Return to Main Contents

NAME

euidaccess, eaccess - check effective user's permissions for a file

SYNOPSIS

#include <unistd.h>

int euidaccess(const char *pathname, int mode);
int eaccess(const char *pathname, int mode);

DESCRIPTION

Like access(2), euidaccess() checks permissions and existence of the file identified by its argument pathname. However, whereas access(2), performs checks using the real user and group identifiers of the process, euidaccess() uses the effective identifiers.

mode is a mask consisting of one or more of R_OK, W_OK, X_OK and F_OK, with the same meanings as for access(2).

eaccess() is a synonym for euidaccess(), provided for compatibility with some other systems.

RETURN VALUE

On success (all requested permissions granted), zero is returned. On error (at least one bit in mode asked for a permission that is denied, or some other error occurred), -1 is returned, and errno is set appropriately.

ERRORS

As for access(2).

CONFORMING TO

These functions are non-standard. Some other systems have an eaccess() function.

NOTES

Glibc Notes

The eaccess() function was added to glibc in version 2.4.

SEE ALSO

access(2), chmod(2), chown(2), faccessat(2), open(2), setgid(2), setuid(2), stat(2), credentials(7), path_resolution(7)


sighold (3)

 Continue to this page.


mq_timedsend (3)

 Continue to this page.


error_on_per_line (3)

 Continue to this page.


sigmask (3)

 Continue to this page.


error_at_line (3)

 Continue to this page.


program_invocation_short_name (3)

 Continue to this page.


mmap64 (3)

 Continue to this page.


CPU_ISSET (3)

 Continue to this page.


getwchar(3p)

GETWCHAR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getwchar - get a wide character from a stdin stream

SYNOPSIS

#include <wchar.h>

wint_t getwchar(void);

DESCRIPTION

The getwchar() function shall be equivalent to getwc(stdin).

RETURN VALUE

Refer to fgetwc() .

ERRORS

Refer to fgetwc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the wint_t value returned by getwchar() is stored into a variable of type wchar_t and then compared against the wint_t macro WEOF, the result may be incorrect. Only the wint_t type is guaranteed to be able to represent any wide character and WEOF.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fgetwc() , getwc() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fgetc(3p)

FGETC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fgetc - get a byte from a stream

SYNOPSIS

#include <stdio.h>

int fgetc(FILE *stream);

DESCRIPTION

If the end-of-file indicator for the input stream pointed to by stream is not set and a next byte is present, the fgetc() function shall obtain the next byte as an unsigned char converted to an int, from the input stream pointed to by stream, and advance the associated file position indicator for the stream (if defined). Since fgetc() operates on bytes, reading a character consisting of multiple bytes (or "a multi-byte character") may require multiple calls to fgetc().

The fgetc() function may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fgetwc(), fgetws(), fread(), fscanf(), getc(), getchar(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc() or ungetwc().

RETURN VALUE

Upon successful completion, fgetc() shall return the next byte from the input stream pointed to by stream. If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgetc() shall return EOF. If a read error occurs, the error indicator for the stream shall be set, fgetc() shall return EOF, and shall set errno to indicate the error.

ERRORS

The fgetc() function shall fail if data needs to be read and:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying stream and the process would be delayed in the fgetc() operation.
EBADF
The file descriptor underlying stream is not a valid file descriptor open for reading.
EINTR
The read operation was terminated due to the receipt of a signal, and no data was transferred.
EIO
A physical I/O error has occurred, or the process is in a background process group attempting to read from its controlling terminal, and either the process is ignoring or blocking the SIGTTIN signal or the process group is orphaned. This error may also be generated for implementation-defined reasons.
EOVERFLOW
The file is a regular file and an attempt was made to read at or beyond the offset maximum associated with the corresponding stream.

The fgetc() function may fail if:

ENOMEM
Insufficient storage space is available.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the integer value returned by fgetc() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined.

The ferror() or feof() functions must be used to distinguish between an error condition and an end-of-file condition.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feof() , ferror() , fopen() , getchar() , getc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fgets(3p)

FGETS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fgets - get a string from a stream

SYNOPSIS

#include <stdio.h>

char *fgets(char *restrict s, int n, FILE *restrict stream);

DESCRIPTION

The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.

The fgets() function may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fgetwc(), fgetws(), fread(), fscanf(), getc(), getchar(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc() or ungetwc().

RETURN VALUE

Upon successful completion, fgets() shall return s. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer. If a read error occurs, the error indicator for the stream shall be set, fgets() shall return a null pointer, and shall set errno to indicate the error.

ERRORS

Refer to fgetc() .

The following sections are informative.

EXAMPLES

Reading Input

The following example uses fgets() to read each line of input. {LINE_MAX}, which defines the maximum size of the input line, is defined in the <limits.h> header.

#include <stdio.h>
...
char line[LINE_MAX];
...
while (fgets(line, LINE_MAX, fp) != NULL) {
...
}
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , fread() , gets() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


erfcf (3p)

 Continue to this page.


strncpy(3p)

STRNCPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strncpy - copy part of a string

SYNOPSIS

#include <string.h>

char *strncpy(char *restrict s1, const char *restrict s2, size_t n);

DESCRIPTION

The strncpy() function shall copy not more than n bytes (bytes that follow a null byte are not copied) from the array pointed to by s2 to the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

If the array pointed to by s2 is a string that is shorter than n bytes, null bytes shall be appended to the copy in the array pointed to by s1, until n bytes in all are written.

RETURN VALUE

The strncpy() function shall return s1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Character movement is performed differently in different implementations. Thus, overlapping moves may yield surprises.

If there is no null byte in the first n bytes of the array pointed to by s2, the result is not null-terminated.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strcpy() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


erfcl (3p)

 Continue to this page.


clog(3p)

CLOG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

clog, clogf, clogl - complex natural logarithm functions

SYNOPSIS

#include <complex.h>

double complex clog(double complex z);
float complex clogf(float complex z);
long double complex clogl(long double complex z);

DESCRIPTION

These functions shall compute the complex natural (base e) logarithm of z, with a branch cut along the negative real axis.

RETURN VALUE

These functions shall return the complex natural logarithm value, in the range of a strip mathematically unbounded along the real axis and in the interval [-ipi, +ipi] along the imaginary axis.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cexp() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_getpgroup(3p)

POSIX_SPAWNATTR_GETPGROUP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawnattr_getpgroup, posix_spawnattr_setpgroup - get and set the spawn-pgroup attribute of a spawn attributes object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

int posix_spawnattr_getpgroup(const posix_spawnattr_t *restrict attr,
pid_t *restrict pgroup);
int posix_spawnattr_setpgroup(posix_spawnattr_t *attr, pid_t pgroup);

DESCRIPTION

The posix_spawnattr_getpgroup() function shall obtain the value of the spawn-pgroup attribute from the attributes object referenced by attr.

The posix_spawnattr_setpgroup() function shall set the spawn-pgroup attribute in an initialized attributes object referenced by attr.

The spawn-pgroup attribute represents the process group to be joined by the new process image in a spawn operation (if POSIX_SPAWN_SETPGROUP is set in the spawn-flags attribute). The default value of this attribute shall be zero.

RETURN VALUE

Upon successful completion, posix_spawnattr_getpgroup() shall return zero and store the value of the spawn-pgroup attribute of attr into the object referenced by the pgroup parameter; otherwise, an error number shall be returned to indicate the error.

Upon successful completion, posix_spawnattr_setpgroup() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The posix_spawnattr_setpgroup() function may fail if:

EINVAL
The value of the attribute being set is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnattr_destroy() , posix_spawnattr_init()
, posix_spawnattr_getsigdefault() , posix_spawnattr_getflags()
, posix_spawnattr_getschedparam() , posix_spawnattr_getschedpolicy()
, posix_spawnattr_getsigmask() , posix_spawnattr_setsigdefault()
, posix_spawnattr_setflags() , posix_spawnattr_setschedparam()
, posix_spawnattr_setschedpolicy() , posix_spawnattr_setsigmask()
, posix_spawnp() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


csinf (3p)

 Continue to this page.


_Exit (3p)

 Continue to this page.


csinh(3p)

CSINH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

csinh, csinhf, csinhl - complex hyperbolic sine functions

SYNOPSIS

#include <complex.h>

double complex csinh(double complex z);
float complex csinhf(float complex z);
long double complex csinhl(long double complex z);

DESCRIPTION

These functions shall compute the complex hyperbolic sine of z.

RETURN VALUE

These functions shall return the complex hyperbolic sine value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

casinh() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


csinl (3p)

 Continue to this page.


fsync(3p)

FSYNC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fsync - synchronize changes to a file

SYNOPSIS

#include <unistd.h>

int fsync(int fildes);

DESCRIPTION

The fsync() function shall request that all data for the open file descriptor named by fildes is to be transferred to the storage device associated with the file described by fildes in an implementation-defined manner. The fsync() function shall not return until the system has completed that action or until an error is detected.

If _POSIX_SYNCHRONIZED_IO is defined, the fsync() function shall force all currently queued I/O operations associated with the file indicated by file descriptor fildes to the synchronized I/O completion state. All I/O operations shall be completed as defined for synchronized I/O file integrity completion.

RETURN VALUE

Upon successful completion, fsync() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error. If the fsync() function fails, outstanding I/O operations are not guaranteed to have been completed.

ERRORS

The fsync() function shall fail if:

EBADF
The fildes argument is not a valid descriptor.
EINTR
The fsync() function was interrupted by a signal.
EINVAL
The fildes argument does not refer to a file on which this operation is possible.
EIO
An I/O error occurred while reading from or writing to the file system.

In the event that any of the queued I/O operations fail, fsync() shall return the error conditions defined for read() and write().

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The fsync() function should be used by programs which require modifications to a file to be completed before continuing; for example, a program which contains a simple transaction facility might use it to ensure that all modifications to a file or files caused by a transaction are recorded.

RATIONALE

The fsync() function is intended to force a physical write of data from the buffer cache, and to assure that after a system crash or other failure that all data up to the time of the fsync() call is recorded on the disk. Since the concepts of "buffer cache", "system crash", "physical write", and "non-volatile storage" are not defined here, the wording has to be more abstract.

If _POSIX_SYNCHRONIZED_IO is not defined, the wording relies heavily on the conformance document to tell the user what can be expected from the system. It is explicitly intended that a null implementation is permitted. This could be valid in the case where the system cannot assure non-volatile storage under any circumstances or when the system is highly fault-tolerant and the functionality is not required. In the middle ground between these extremes, fsync() might or might not actually cause data to be written where it is safe from a power failure. The conformance document should identify at least that one configuration exists (and how to obtain that configuration) where this can be assured for at least some files that the user can select to use for critical data. It is not intended that an exhaustive list is required, but rather sufficient information is provided so that if critical data needs to be saved, the user can determine how the system is to be configured to allow the data to be written to non-volatile storage.

It is reasonable to assert that the key aspects of fsync() are unreasonable to test in a test suite. That does not make the function any less valuable, just more difficult to test. A formal conformance test should probably force a system crash (power shutdown) during the test for this condition, but it needs to be done in such a way that automated testing does not require this to be done except when a formal record of the results is being made. It would also not be unreasonable to omit testing for fsync(), allowing it to be treated as a quality-of-implementation issue.

FUTURE DIRECTIONS

None.

SEE ALSO

sync() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fesetexceptflag (3p)

 Continue to this page.


setregid(3p)

SETREGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setregid - set real and effective group IDs

SYNOPSIS

#include <unistd.h>

int setregid(gid_t rgid, gid_t egid);

DESCRIPTION

The setregid() function shall set the real and effective group IDs of the calling process.

If rgid is -1, the real group ID shall not be changed; if egid is -1, the effective group ID shall not be changed.

The real and effective group IDs may be set to different values in the same call.

Only a process with appropriate privileges can set the real group ID and the effective group ID to any valid value.

A non-privileged process can set either the real group ID to the saved set-group-ID from one of the exec family of functions, or the effective group ID to the saved set-group-ID or the real group ID.

Any supplementary group IDs of the calling process remain unchanged.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error, and neither of the group IDs are changed.

ERRORS

The setregid() function shall fail if:

EINVAL
The value of the rgid or egid argument is invalid or out-of-range.
EPERM
The process does not have appropriate privileges and a change other than changing the real group ID to the saved set-group-ID, or changing the effective group ID to the real group ID or the saved set-group-ID, was requested.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If a set-group-ID process sets its effective group ID to its real group ID, it can still set its effective group ID back to the saved set-group-ID.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getegid() , geteuid() , getgid() , getuid() , setegid() , seteuid() , setgid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlock_trywrlock (3p)

 Continue to this page.


aio_error(3p)

AIO_ERROR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio_error - retrieve errors status for an asynchronous I/O operation (REALTIME)

SYNOPSIS

#include <aio.h>

int aio_error(const struct aiocb *aiocbp);

DESCRIPTION

The aio_error() function shall return the error status associated with the aiocb structure referenced by the aiocbp argument. The error status for an asynchronous I/O operation is the errno value that would be set by the corresponding read(), write(), fdatasync(), or fsync() operation. If the operation has not yet completed, then the error status shall be equal to [EINPROGRESS].

RETURN VALUE

If the asynchronous I/O operation has completed successfully, then 0 shall be returned. If the asynchronous operation has completed unsuccessfully, then the error status, as described for read(), write(), fdatasync(), and fsync(), shall be returned. If the asynchronous I/O operation has not yet completed, then [EINPROGRESS] shall be returned.

ERRORS

The aio_error() function may fail if:

EINVAL
The aiocbp argument does not refer to an asynchronous operation whose return status has not yet been retrieved.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The aio_error() function is part of the Asynchronous Input and Output option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_cancel() , aio_fsync() , aio_read() , aio_return() , aio_write() , close() , exec() , exit() , fork() , lio_listio() , lseek() , read() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


uname(3p)

UNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

uname - get the name of the current system

SYNOPSIS

#include <sys/utsname.h>

int uname(struct utsname *name);

DESCRIPTION

The uname() function shall store information identifying the current system in the structure pointed to by name.

The uname() function uses the utsname structure defined in <sys/utsname.h>.

The uname() function shall return a string naming the current system in the character array sysname. Similarly, nodename shall contain the name of this node within an implementation-defined communications network. The arrays release and version shall further identify the operating system. The array machine shall contain a name that identifies the hardware that the system is running on.

The format of each member is implementation-defined.

RETURN VALUE

Upon successful completion, a non-negative value shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The inclusion of the nodename member in this structure does not imply that it is sufficient information for interfacing to communications networks.

RATIONALE

The values of the structure members are not constrained to have any relation to the version of this volume of IEEE Std 1003.1-2001 implemented in the operating system. An application should instead depend on _POSIX_VERSION and related constants defined in <unistd.h>.

This volume of IEEE Std 1003.1-2001 does not define the sizes of the members of the structure and permits them to be of different sizes, although most implementations define them all to be the same size: eight bytes plus one byte for the string terminator. That size for nodename is not enough for use with many networks.

The uname() function originated in System III, System V, and related implementations, and it does not exist in Version 7 or 4.3 BSD. The values it returns are set at system compile time in those historical implementations.

4.3 BSD has gethostname() and gethostid(), which return a symbolic name and a numeric value, respectively. There are related sethostname() and sethostid() functions that are used to set the values the other two functions return. The former functions are included in this specification, the latter are not.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <sys/utsname.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


expm1(3p)

EXPM1

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

expm1, expm1f, expm1l - compute exponential functions

SYNOPSIS

#include <math.h>

double expm1(double x);
float expm1f(float x);
long double expm1l(long double x);

DESCRIPTION

These functions shall compute e**x-1.0.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions return e**x-1.0.

If the correct value would cause overflow, a range error shall occur and expm1(), expm1f(), and expm1l() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.

If x is NaN, a NaN shall be returned.

If x is ±0, ±0 shall be returned.

If x is -Inf, -1 shall be returned.

If x is +Inf, x shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The value of expm1(x) may be more accurate than exp(x)-1.0 for small values of x.

The expm1() and log1p() functions are useful for financial calculations of ((1+x)**n-1)/x, namely:

expm1(n * log1p(x))/x

when x is very small (for example, when calculating small daily interest rates). These functions also simplify writing accurate inverse hyperbolic functions.

For IEEE Std 754-1985 double, 709.8 < x implies expm1( x) has overflowed.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exp() , feclearexcept() , fetestexcept() , ilogb() , log1p() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setlogmask (3p)

 Continue to this page.


posix_spawn_file_actions_init(3p)

POSIX_SPAWN_FILE_ACTIONS_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawn_file_actions_destroy, posix_spawn_file_actions_init - destroy and initialize spawn file actions object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *
file_actions);
int posix_spawn_file_actions_init(posix_spawn_file_actions_t *
file_actions);

DESCRIPTION

The posix_spawn_file_actions_destroy() function shall destroy the object referenced by file_actions; the object becomes, in effect, uninitialized. An implementation may cause posix_spawn_file_actions_destroy() to set the object referenced by file_actions to an invalid value. A destroyed spawn file actions object can be reinitialized using posix_spawn_file_actions_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

The posix_spawn_file_actions_init() function shall initialize the object referenced by file_actions to contain no file actions for posix_spawn() or posix_spawnp() to perform.

A spawn file actions object is as defined in posix_spawn_file_actions_addclose() .

The effect of initializing an already initialized spawn file actions object is undefined.

RETURN VALUE

Upon successful completion, these functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The posix_spawn_file_actions_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the spawn file actions object.

The posix_spawn_file_actions_destroy() function may fail if:

EINVAL
The value specified by file_actions is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

Refer to the RATIONALE in posix_spawn_file_actions_addclose() .

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnp() , the Base Definitions volume of IEEE Std 1003.1-2001, <spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_cond_init(3p)

PTHREAD_COND_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_cond_destroy, pthread_cond_init - destroy and initialize condition variables

SYNOPSIS

#include <pthread.h>

int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

DESCRIPTION

The pthread_cond_destroy() function shall destroy the given condition variable specified by cond; the object becomes, in effect, uninitialized. An implementation may cause pthread_cond_destroy() to set the object referenced by cond to an invalid value. A destroyed condition variable object can be reinitialized using pthread_cond_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

It shall be safe to destroy an initialized condition variable upon which no threads are currently blocked. Attempting to destroy a condition variable upon which other threads are currently blocked results in undefined behavior.

The pthread_cond_init() function shall initialize the condition variable referenced by cond with attributes referenced by attr. If attr is NULL, the default condition variable attributes shall be used; the effect is the same as passing the address of a default condition variable attributes object. Upon successful initialization, the state of the condition variable shall become initialized.

Only cond itself may be used for performing synchronization. The result of referring to copies of cond in calls to pthread_cond_wait(), pthread_cond_timedwait(), pthread_cond_signal(), pthread_cond_broadcast(), and pthread_cond_destroy() is undefined.

Attempting to initialize an already initialized condition variable results in undefined behavior.

In cases where default condition variable attributes are appropriate, the macro PTHREAD_COND_INITIALIZER can be used to initialize condition variables that are statically allocated. The effect shall be equivalent to dynamic initialization by a call to pthread_cond_init() with parameter attr specified as NULL, except that no error checks are performed.

RETURN VALUE

If successful, the pthread_cond_destroy() and pthread_cond_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

The [EBUSY] and [EINVAL] error checks, if implemented, shall act as if they were performed immediately at the beginning of processing for the function and caused an error return prior to modifying the state of the condition variable specified by cond.

ERRORS

The pthread_cond_destroy() function may fail if:

EBUSY
The implementation has detected an attempt to destroy the object referenced by cond while it is referenced (for example, while being used in a pthread_cond_wait() or pthread_cond_timedwait()) by another thread.
EINVAL
The value specified by cond is invalid.

The pthread_cond_init() function shall fail if:

EAGAIN
The system lacked the necessary resources (other than memory) to initialize another condition variable.
ENOMEM
Insufficient memory exists to initialize the condition variable.

The pthread_cond_init() function may fail if:

EBUSY
The implementation has detected an attempt to reinitialize the object referenced by cond, a previously initialized, but not yet destroyed, condition variable.
EINVAL
The value specified by attr is invalid.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

A condition variable can be destroyed immediately after all the threads that are blocked on it are awakened. For example, consider the following code:

struct list {
    pthread_mutex_t lm;
    ...
}

struct elt {
    key k;
    int busy;
    pthread_cond_t notbusy;
    ...
}

/* Find a list element and reserve it. */
struct elt *
list_find(struct list *lp, key k)
{
    struct elt *ep;

    pthread_mutex_lock(&lp->lm);
    while ((ep = find_elt(l, k) != NULL) && ep->busy)
        pthread_cond_wait(&ep->notbusy, &lp->lm);
    if (ep != NULL)
        ep->busy = 1;
    pthread_mutex_unlock(&lp->lm);
    return(ep);
}

delete_elt(struct list *lp, struct elt *ep)
{
    pthread_mutex_lock(&lp->lm);
    assert(ep->busy);
    ... remove ep from list ...
    ep->busy = 0;  /* Paranoid. */
(A) pthread_cond_broadcast(&ep->notbusy);
    pthread_mutex_unlock(&lp->lm);
(B) pthread_cond_destroy(&rp->notbusy);
    free(ep);
}

In this example, the condition variable and its list element may be freed (line B) immediately after all threads waiting for it are awakened (line A), since the mutex and the code ensure that no other thread can touch the element to be deleted.

APPLICATION USAGE

None.

RATIONALE

See pthread_mutex_init() ; a similar rationale applies to condition variables.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_broadcast() , pthread_cond_signal() , pthread_cond_timedwait() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mlock(3p)

MLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mlock, munlock - lock or unlock a range of process address space (REALTIME)

SYNOPSIS

#include <sys/mman.h>

int mlock(const void *addr, size_t len);
int munlock(const void *addr, size_t len);

DESCRIPTION

The mlock() function shall cause those whole pages containing any part of the address space of the process starting at address addr and continuing for len bytes to be memory-resident until unlocked or until the process exits or execs another process image. The implementation may require that addr be a multiple of {PAGESIZE}.

The munlock() function shall unlock those whole pages containing any part of the address space of the process starting at address addr and continuing for len bytes, regardless of how many times mlock() has been called by the process for any of the pages in the specified range. The implementation may require that addr be a multiple of {PAGESIZE}.

If any of the pages in the range specified to a call to munlock() are also mapped into the address spaces of other processes, any locks established on those pages by another process are unaffected by the call of this process to munlock(). If any of the pages in the range specified by a call to munlock() are also mapped into other portions of the address space of the calling process outside the range specified, any locks established on those pages via the other mappings are also unaffected by this call.

Upon successful return from mlock(), pages in the specified range shall be locked and memory-resident. Upon successful return from munlock(), pages in the specified range shall be unlocked with respect to the address space of the process. Memory residency of unlocked pages is unspecified.

The appropriate privilege is required to lock process memory with mlock().

RETURN VALUE

Upon successful completion, the mlock() and munlock() functions shall return a value of zero. Otherwise, no change is made to any locks in the address space of the process, and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The mlock() and munlock() functions shall fail if:

ENOMEM
Some or all of the address range specified by the addr and len arguments does not correspond to valid mapped pages in the address space of the process.

The mlock() function shall fail if:

EAGAIN
Some or all of the memory identified by the operation could not be locked when the call was made.

The mlock() and munlock() functions may fail if:

EINVAL
The addr argument is not a multiple of {PAGESIZE}.

The mlock() function may fail if:

ENOMEM
Locking the pages mapped by the specified range would exceed an implementation-defined limit on the amount of memory that the process may lock.
EPERM
The calling process does not have the appropriate privilege to perform the requested operation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , exit() , fork() , mlockall() , munmap() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswlower(3p)

ISWLOWER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswlower - test for a lowercase letter wide-character code

SYNOPSIS

#include <wctype.h>

int iswlower(wint_t wc);

DESCRIPTION

The iswlower() function shall test whether wc is a wide-character code representing a character of class lower in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswlower() function shall return non-zero if wc is a lowercase letter wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


signgam (3p)

 Continue to this page.


pthread_mutex_init(3p)

PTHREAD_MUTEX_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutex_destroy, pthread_mutex_init - destroy and initialize a mutex

SYNOPSIS

#include <pthread.h>

int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

DESCRIPTION

The pthread_mutex_destroy() function shall destroy the mutex object referenced by mutex; the mutex object becomes, in effect, uninitialized. An implementation may cause pthread_mutex_destroy() to set the object referenced by mutex to an invalid value. A destroyed mutex object can be reinitialized using pthread_mutex_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

It shall be safe to destroy an initialized mutex that is unlocked. Attempting to destroy a locked mutex results in undefined behavior.

The pthread_mutex_init() function shall initialize the mutex referenced by mutex with attributes specified by attr. If attr is NULL, the default mutex attributes are used; the effect shall be the same as passing the address of a default mutex attributes object. Upon successful initialization, the state of the mutex becomes initialized and unlocked.

Only mutex itself may be used for performing synchronization. The result of referring to copies of mutex in calls to pthread_mutex_lock(), pthread_mutex_trylock(), pthread_mutex_unlock(), and pthread_mutex_destroy() is undefined.

Attempting to initialize an already initialized mutex results in undefined behavior.

In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated. The effect shall be equivalent to dynamic initialization by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.

RETURN VALUE

If successful, the pthread_mutex_destroy() and pthread_mutex_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

The [EBUSY] and [EINVAL] error checks, if implemented, act as if they were performed immediately at the beginning of processing for the function and shall cause an error return prior to modifying the state of the mutex specified by mutex.

ERRORS

The pthread_mutex_destroy() function may fail if:

EBUSY
The implementation has detected an attempt to destroy the object referenced by mutex while it is locked or referenced (for example, while being used in a pthread_cond_timedwait() or pthread_cond_wait()) by another thread.
EINVAL
The value specified by mutex is invalid.

The pthread_mutex_init() function shall fail if:

EAGAIN
The system lacked the necessary resources (other than memory) to initialize another mutex.
ENOMEM
Insufficient memory exists to initialize the mutex.
EPERM
The caller does not have the privilege to perform the operation.

The pthread_mutex_init() function may fail if:

EBUSY
The implementation has detected an attempt to reinitialize the object referenced by mutex, a previously initialized, but not yet destroyed, mutex.
EINVAL
The value specified by attr is invalid.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Alternate Implementations Possible

This volume of IEEE Std 1003.1-2001 supports several alternative implementations of mutexes. An implementation may store the lock directly in the object of type pthread_mutex_t. Alternatively, an implementation may store the lock in the heap and merely store a pointer, handle, or unique ID in the mutex object. Either implementation has advantages or may be required on certain hardware configurations. So that portable code can be written that is invariant to this choice, this volume of IEEE Std 1003.1-2001 does not define assignment or equality for this type, and it uses the term "initialize" to reinforce the (more restrictive) notion that the lock may actually reside in the mutex object itself.

Note that this precludes an over-specification of the type of the mutex or condition variable and motivates the opaqueness of the type.

An implementation is permitted, but not required, to have pthread_mutex_destroy() store an illegal value into the mutex. This may help detect erroneous programs that try to lock (or otherwise reference) a mutex that has already been destroyed.

Tradeoff Between Error Checks and Performance Supported

Many of the error checks were made optional in order to let implementations trade off performance versus degree of error checking according to the needs of their specific applications and execution environment. As a general rule, errors or conditions caused by the system (such as insufficient memory) always need to be reported, but errors due to an erroneously coded application (such as failing to provide adequate synchronization to prevent a mutex from being deleted while in use) are made optional.

A wide range of implementations is thus made possible. For example, an implementation intended for application debugging may implement all of the error checks, but an implementation running a single, provably correct application under very tight performance constraints in an embedded computer might implement minimal checks. An implementation might even be provided in two versions, similar to the options that compilers provide: a full-checking, but slower version; and a limited-checking, but faster version. To forbid this optionality would be a disservice to users.

By carefully limiting the use of "undefined behavior" only to things that an erroneous (badly coded) application might do, and by defining that resource-not-available errors are mandatory, this volume of IEEE Std 1003.1-2001 ensures that a fully-conforming application is portable across the full range of implementations, while not forcing all implementations to add overhead to check for numerous things that a correct program never does.

Why No Limits are Defined

Defining symbols for the maximum number of mutexes and condition variables was considered but rejected because the number of these objects may change dynamically. Furthermore, many implementations place these objects into application memory; thus, there is no explicit maximum.

Static Initializers for Mutexes and Condition Variables

Providing for static initialization of statically allocated synchronization objects allows modules with private static synchronization variables to avoid runtime initialization tests and overhead. Furthermore, it simplifies the coding of self-initializing modules. Such modules are common in C libraries, where for various reasons the design calls for self-initialization instead of requiring an explicit module initialization function to be called. An example use of static initialization follows.

Without static initialization, a self-initializing routine foo() might look as follows:

static pthread_once_t foo_once = PTHREAD_ONCE_INIT;
static pthread_mutex_t foo_mutex;

void foo_init()
{
    pthread_mutex_init(&foo_mutex, NULL);
}

void foo()
{
    pthread_once(&foo_once, foo_init);
    pthread_mutex_lock(&foo_mutex);
   /* Do work. */
    pthread_mutex_unlock(&foo_mutex);
}

With static initialization, the same routine could be coded as follows:

static pthread_mutex_t foo_mutex = PTHREAD_MUTEX_INITIALIZER;

void foo()
{
    pthread_mutex_lock(&foo_mutex);
   /* Do work. */
    pthread_mutex_unlock(&foo_mutex);
}

Note that the static initialization both eliminates the need for the initialization test inside pthread_once() and the fetch of &foo_mutex to learn the address to be passed to pthread_mutex_lock() or pthread_mutex_unlock().

Thus, the C code written to initialize static objects is simpler on all systems and is also faster on a large class of systems; those where the (entire) synchronization object can be stored in application memory.

Yet the locking performance question is likely to be raised for machines that require mutexes to be allocated out of special memory. Such machines actually have to have mutexes and possibly condition variables contain pointers to the actual hardware locks. For static initialization to work on such machines, pthread_mutex_lock() also has to test whether or not the pointer to the actual lock has been allocated. If it has not, pthread_mutex_lock() has to initialize it before use. The reservation of such resources can be made when the program is loaded, and hence return codes have not been added to mutex locking and condition variable waiting to indicate failure to complete initialization.

This runtime test in pthread_mutex_lock() would at first seem to be extra work; an extra test is required to see whether the pointer has been initialized. On most machines this would actually be implemented as a fetch of the pointer, testing the pointer against zero, and then using the pointer if it has already been initialized. While the test might seem to add extra work, the extra effort of testing a register is usually negligible since no extra memory references are actually done. As more and more machines provide caches, the real expenses are memory references, not instructions executed.

Alternatively, depending on the machine architecture, there are often ways to eliminate all overhead in the most important case: on the lock operations that occur after the lock has been initialized. This can be done by shifting more overhead to the less frequent operation: initialization. Since out-of-line mutex allocation also means that an address has to be dereferenced to find the actual lock, one technique that is widely applicable is to have static initialization store a bogus value for that address; in particular, an address that causes a machine fault to occur. When such a fault occurs upon the first attempt to lock such a mutex, validity checks can be done, and then the correct address for the actual lock can be filled in. Subsequent lock operations incur no extra overhead since they do not "fault". This is merely one technique that can be used to support static initialization, while not adversely affecting the performance of lock acquisition. No doubt there are other techniques that are highly machine-dependent.

The locking overhead for machines doing out-of-line mutex allocation is thus similar for modules being implicitly initialized, where it is improved for those doing mutex allocation entirely inline. The inline case is thus made much faster, and the out-of-line case is not significantly worse.

Besides the issue of locking performance for such machines, a concern is raised that it is possible that threads would serialize contending for initialization locks when attempting to finish initializing statically allocated mutexes. (Such finishing would typically involve taking an internal lock, allocating a structure, storing a pointer to the structure in the mutex, and releasing the internal lock.) First, many implementations would reduce such serialization by hashing on the mutex address. Second, such serialization can only occur a bounded number of times. In particular, it can happen at most as many times as there are statically allocated synchronization objects. Dynamically allocated objects would still be initialized via pthread_mutex_init() or pthread_cond_init().

Finally, if none of the above optimization techniques for out-of-line allocation yields sufficient performance for an application on some implementation, the application can avoid static initialization altogether by explicitly initializing all synchronization objects with the corresponding pthread_*_init() functions, which are supported by all implementations. An implementation can also document the tradeoffs and advise which initialization technique is more efficient for that particular implementation.

Destroying Mutexes

A mutex can be destroyed immediately after it is unlocked. For example, consider the following code:

struct obj {
pthread_mutex_t om;
    int refcnt;
    ...
};

obj_done(struct obj *op)
{
    pthread_mutex_lock(&op->om);
    if (--op->refcnt == 0) {
        pthread_mutex_unlock(&op->om);
(A)     pthread_mutex_destroy(&op->om);
(B)     free(op);
    } else
(C)     pthread_mutex_unlock(&op->om);
}

In this case obj is reference counted and obj_done() is called whenever a reference to the object is dropped. Implementations are required to allow an object to be destroyed and freed and potentially unmapped (for example, lines A and B) immediately after the object is unlocked (line C).

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_mutex_getprioceiling() , pthread_mutex_lock() , pthread_mutex_timedlock() , pthread_mutexattr_getpshared() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fchown(3p)

FCHOWN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fchown - change owner and group of a file

SYNOPSIS

#include <unistd.h>

int fchown(int fildes, uid_t owner, gid_t group);

DESCRIPTION

The fchown() function shall be equivalent to chown() except that the file whose owner and group are changed is specified by the file descriptor fildes.

RETURN VALUE

Upon successful completion, fchown() shall return 0. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The fchown() function shall fail if:

EBADF
The fildes argument is not an open file descriptor.
EPERM
The effective user ID does not match the owner of the file or the process does not have appropriate privilege and _POSIX_CHOWN_RESTRICTED indicates that such privilege is required.
EROFS
The file referred to by fildes resides on a read-only file system.

The fchown() function may fail if:

EINVAL
The owner or group ID is not a value supported by the implementation. The fildes argument refers to a pipe or socket or an fattach()-ed STREAM and the implementation disallows execution of fchown() on a pipe.
EIO
A physical I/O error has occurred.
EINTR
The fchown() function was interrupted by a signal which was caught.

The following sections are informative.

EXAMPLES

Changing the Current Owner of a File

The following example shows how to change the owner of a file named /home/cnd/mod1 to "jones" and the group to "cnd".

The numeric value for the user ID is obtained by extracting the user ID from the user database entry associated with "jones". Similarly, the numeric value for the group ID is obtained by extracting the group ID from the group database entry associated with "cnd". This example assumes the calling program has appropriate privileges.

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>

struct passwd *pwd;
struct group  *grp;
int            fildes;
...
fildes = open("/home/cnd/mod1", O_RDWR);
pwd = getpwnam("jones");
grp = getgrnam("cnd");
fchown(fildes, pwd->pw_uid, grp->gr_gid);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

chown() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


regcomp(3p)

REGCOMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

regcomp, regerror, regexec, regfree - regular expression matching

SYNOPSIS

#include <regex.h>

int regcomp(regex_t *restrict preg, const char *restrict pattern,
int cflags);
size_t regerror(int errcode, const regex_t *restrict preg,
char *restrict errbuf, size_t errbuf_size);
int regexec(const regex_t *restrict preg, const char *restrict string,
size_t nmatch, regmatch_t pmatch[restrict], int eflags);
void regfree(regex_t *preg);

DESCRIPTION

These functions interpret basic and extended regular expressions as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 9, Regular Expressions.

The regex_t structure is defined in <regex.h> and contains at least the following member:
Member Type | Member Name | Description
size_t | re_nsub | Number of parenthesized subexpressions.

The regmatch_t structure is defined in <regex.h> and contains at least the following members:
Member Type | Member Name | Description
regoff_t | rm_so | Byte offset from start of string to start of substring.
regoff_t | rm_eo | Byte offset from start of string of the first character after the end of substring.

The regcomp() function shall compile the regular expression contained in the string pointed to by the pattern argument and place the results in the structure pointed to by preg. The cflags argument is the bitwise-inclusive OR of zero or more of the following flags, which are defined in the <regex.h> header:

REG_EXTENDED
Use Extended Regular Expressions.
REG_ICASE
Ignore case in match. (See the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 9, Regular Expressions.)
REG_NOSUB
Report only success/fail in regexec().
REG_NEWLINE
Change the handling of <newline>s, as described in the text.

The default regular expression type for pattern is a Basic Regular Expression. The application can specify Extended Regular Expressions using the REG_EXTENDED cflags flag.

If the REG_NOSUB flag was not set in cflags, then regcomp() shall set re_nsub to the number of parenthesized subexpressions (delimited by "\(\)" in basic regular expressions or "()" in extended regular expressions) found in pattern.

The regexec() function compares the null-terminated string specified by string with the compiled regular expression preg initialized by a previous call to regcomp(). If it finds a match, regexec() shall return 0; otherwise, it shall return non-zero indicating either no match or an error. The eflags argument is the bitwise-inclusive OR of zero or more of the following flags, which are defined in the <regex.h> header:

REG_NOTBOL
The first character of the string pointed to by string is not the beginning of the line. Therefore, the circumflex character ( '^' ), when taken as a special character, shall not match the beginning of string.
REG_NOTEOL
The last character of the string pointed to by string is not the end of the line. Therefore, the dollar sign ( '$' ), when taken as a special character, shall not match the end of string.

If nmatch is 0 or REG_NOSUB was set in the cflags argument to regcomp(), then regexec() shall ignore the pmatch argument. Otherwise, the application shall ensure that the pmatch argument points to an array with at least nmatch elements, and regexec() shall fill in the elements of that array with offsets of the substrings of string that correspond to the parenthesized subexpressions of pattern: pmatch[ i]. rm_so shall be the byte offset of the beginning and pmatch[ i]. rm_eo shall be one greater than the byte offset of the end of substring i. (Subexpression i begins at the ith matched open parenthesis, counting from 1.) Offsets in pmatch[0] identify the substring that corresponds to the entire regular expression. Unused elements of pmatch up to pmatch[ nmatch-1] shall be filled with -1. If there are more than nmatch subexpressions in pattern ( pattern itself counts as a subexpression), then regexec() shall still do the match, but shall record only the first nmatch substrings.

When matching a basic or extended regular expression, any given parenthesized subexpression of pattern might participate in the match of several different substrings of string, or it might not match any substring even though the pattern as a whole did match. The following rules shall be used to determine which substrings to report in pmatch when matching regular expressions:

1.
If subexpression i in a regular expression is not contained within another subexpression, and it participated in the match several times, then the byte offsets in pmatch[ i] shall delimit the last such match.

2.
If subexpression i is not contained within another subexpression, and it did not participate in an otherwise successful match, the byte offsets in pmatch[ i] shall be -1. A subexpression does not participate in the match when: '*' or "\{\}" appears immediately after the subexpression in a basic regular expression, or '*' , '?' , or "{}" appears immediately after the subexpression in an extended regular expression, and the subexpression did not match (matched 0 times)

or: '|' is used in an extended regular expression to select this subexpression or another, and the other subexpression matched.

3.
If subexpression i is contained within another subexpression j, and i is not contained within any other subexpression that is contained within j, and a match of subexpression j is reported in pmatch[ j], then the match or non-match of subexpression i reported in pmatch[ i] shall be as described in 1. and 2. above, but within the substring reported in pmatch[ j] rather than the whole string. The offsets in pmatch[ i] are still relative to the start of string.

4.
If subexpression i is contained in subexpression j, and the byte offsets in pmatch[ j] are -1, then the pointers in pmatch[ i] shall also be -1.

5.
If subexpression i matched a zero-length string, then both byte offsets in pmatch[ i] shall be the byte offset of the character or null terminator immediately following the zero-length string.

If, when regexec() is called, the locale is different from when the regular expression was compiled, the result is undefined.

If REG_NEWLINE is not set in cflags, then a <newline> in pattern or string shall be treated as an ordinary character. If REG_NEWLINE is set, then <newline> shall be treated as an ordinary character except as follows:

1.
A <newline> in string shall not be matched by a period outside a bracket expression or by any form of a non-matching list (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 9, Regular Expressions).

2.
A circumflex ( '^' ) in pattern, when used to specify expression anchoring (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3.8, BRE Expression Anchoring), shall match the zero-length string immediately after a <newline> in string, regardless of the setting of REG_NOTBOL.

3.
A dollar sign ( '$' ) in pattern, when used to specify expression anchoring, shall match the zero-length string immediately before a <newline> in string, regardless of the setting of REG_NOTEOL.

The regfree() function frees any memory allocated by regcomp() associated with preg.

The following constants are defined as error return values:

REG_NOMATCH
regexec() failed to match.
REG_BADPAT
Invalid regular expression.
REG_ECOLLATE
Invalid collating element referenced.
REG_ECTYPE
Invalid character class type referenced.
REG_EESCAPE
Trailing '\' in pattern.
REG_ESUBREG
Number in "\digit" invalid or in error.
REG_EBRACK
"[]" imbalance.
REG_EPAREN
"\(\)" or "()" imbalance.
REG_EBRACE
"\{\}" imbalance.
REG_BADBR
Content of "\{\}" invalid: not a number, number too large, more than two numbers, first larger than second.
REG_ERANGE
Invalid endpoint in range expression.
REG_ESPACE
Out of memory.
REG_BADRPT
'?' , '*' , or '+' not preceded by valid regular expression.

The regerror() function provides a mapping from error codes returned by regcomp() and regexec() to unspecified printable strings. It generates a string corresponding to the value of the errcode argument, which the application shall ensure is the last non-zero value returned by regcomp() or regexec() with the given value of preg. If errcode is not such a value, the content of the generated string is unspecified.

If preg is a null pointer, but errcode is a value returned by a previous call to regexec() or regcomp(), the regerror() still generates an error string corresponding to the value of errcode, but it might not be as detailed under some implementations.

If the errbuf_size argument is not 0, regerror() shall place the generated string into the buffer of size errbuf_size bytes pointed to by errbuf. If the string (including the terminating null) cannot fit in the buffer, regerror() shall truncate the string and null-terminate the result.

If errbuf_size is 0, regerror() shall ignore the errbuf argument, and return the size of the buffer needed to hold the generated string.

If the preg argument to regexec() or regfree() is not a compiled regular expression returned by regcomp(), the result is undefined. A preg is no longer treated as a compiled regular expression after it is given to regfree().

RETURN VALUE

Upon successful completion, the regcomp() function shall return 0. Otherwise, it shall return an integer value indicating an error as described in <regex.h>, and the content of preg is undefined. If a code is returned, the interpretation shall be as given in <regex.h>.

If regcomp() detects an invalid RE, it may return REG_BADPAT, or it may return one of the error codes that more precisely describes the error.

Upon successful completion, the regexec() function shall return 0. Otherwise, it shall return REG_NOMATCH to indicate no match.

Upon successful completion, the regerror() function shall return the number of bytes needed to hold the entire generated string, including the null termination. If the return value is greater than errbuf_size, the string returned in the buffer pointed to by errbuf has been truncated.

The regfree() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

#include <regex.h>

/*
 * Match string against the extended regular expression in
 * pattern, treating errors as no match.
 *
 * Return 1 for match, 0 for no match.
 */

int
match(const char *string, char *pattern)
{
    int    status;
    regex_t    re;

    if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
        return(0);      /* Report error. */
    }
    status = regexec(&re, string, (size_t) 0, NULL, 0);
    regfree(&re);
    if (status != 0) {
        return(0);      /* Report error. */
    }
    return(1);
}

The following demonstrates how the REG_NOTBOL flag could be used with regexec() to find all substrings in a line that match a pattern supplied by a user. (For simplicity of the example, very little error checking is done.)

(void) regcomp (&re, pattern, 0);
/* This call to regexec() finds the first match on the line. */
error = regexec (&re, &buffer[0], 1, &pm, 0);
while (error == 0) {  /* While matches found. */
    /* Substring found between pm.rm_so and pm.rm_eo. */
    /* This call to regexec() finds the next match. */
    error = regexec (&re, buffer + pm.rm_eo, 1, &pm, REG_NOTBOL);
}

APPLICATION USAGE

An application could use:

regerror(code,preg,(char *)NULL,(size_t)0)

to find out how big a buffer is needed for the generated string, malloc() a buffer to hold the string, and then call regerror() again to get the string. Alternatively, it could allocate a fixed, static buffer that is big enough to hold most strings, and then use malloc() to allocate a larger buffer if it finds that this is too small.

To match a pattern as described in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13, Pattern Matching Notation, use the fnmatch() function.

RATIONALE

The regexec() function must fill in all nmatch elements of pmatch, where nmatch and pmatch are supplied by the application, even if some elements of pmatch do not correspond to subexpressions in pattern. The application writer should note that there is probably no reason for using a value of nmatch that is larger than preg-> re_nsub+1.

The REG_NEWLINE flag supports a use of RE matching that is needed in some applications like text editors. In such applications, the user supplies an RE asking the application to find a line that matches the given expression. An anchor in such an RE anchors at the beginning or end of any line. Such an application can pass a sequence of <newline>-separated lines to regexec() as a single long string and specify REG_NEWLINE to regcomp() to get the desired behavior. The application must ensure that there are no explicit <newline>s in pattern if it wants to ensure that any match occurs entirely within a single line.

The REG_NEWLINE flag affects the behavior of regexec(), but it is in the cflags parameter to regcomp() to allow flexibility of implementation. Some implementations will want to generate the same compiled RE in regcomp() regardless of the setting of REG_NEWLINE and have regexec() handle anchors differently based on the setting of the flag. Other implementations will generate different compiled REs based on the REG_NEWLINE.

The REG_ICASE flag supports the operations taken by the grep -i option and the historical implementations of ex and vi. Including this flag will make it easier for application code to be written that does the same thing as these utilities.

The substrings reported in pmatch[] are defined using offsets from the start of the string rather than pointers. Since this is a new interface, there should be no impact on historical implementations or applications, and offsets should be just as easy to use as pointers. The change to offsets was made to facilitate future extensions in which the string to be searched is presented to regexec() in blocks, allowing a string to be searched that is not all in memory at once.

The type regoff_t is used for the elements of pmatch[] to ensure that the application can represent either the largest possible array in memory (important for an application conforming to the Shell and Utilities volume of IEEE Std 1003.1-2001) or the largest possible file (important for an application using the extension where a file is searched in chunks).

The standard developers rejected the inclusion of a regsub() function that would be used to do substitutions for a matched RE. While such a routine would be useful to some applications, its utility would be much more limited than the matching function described here. Both RE parsing and substitution are possible to implement without support other than that required by the ISO C standard, but matching is much more complex than substituting. The only difficult part of substitution, given the information supplied by regexec(), is finding the next character in a string when there can be multi-byte characters. That is a much larger issue, and one that needs a more general solution.

The errno variable has not been used for error returns to avoid filling the errno name space for this feature.

The interface is defined so that the matched substrings rm_sp and rm_ep are in a separate regmatch_t structure instead of in regex_t. This allows a single compiled RE to be used simultaneously in several contexts; in main() and a signal handler, perhaps, or in multiple threads of lightweight processes. (The preg argument to regexec() is declared with type const, so the implementation is not permitted to use the structure to store intermediate results.) It also allows an application to request an arbitrary number of substrings from an RE. The number of subexpressions in the RE is reported in re_nsub in preg. With this change to regexec(), consideration was given to dropping the REG_NOSUB flag since the user can now specify this with a zero nmatch argument to regexec(). However, keeping REG_NOSUB allows an implementation to use a different (perhaps more efficient) algorithm if it knows in regcomp() that no subexpressions need be reported. The implementation is only required to fill in pmatch if nmatch is not zero and if REG_NOSUB is not specified. Note that the size_t type, as defined in the ISO C standard, is unsigned, so the description of regexec() does not need to address negative values of nmatch.

REG_NOTBOL was added to allow an application to do repeated searches for the same pattern in a line. If the pattern contains a circumflex character that should match the beginning of a line, then the pattern should only match when matched against the beginning of the line. Without the REG_NOTBOL flag, the application could rewrite the expression for subsequent matches, but in the general case this would require parsing the expression. The need for REG_NOTEOL is not as clear; it was added for symmetry.

The addition of the regerror() function addresses the historical need for conforming application programs to have access to error information more than "Function failed to compile/match your RE for unknown reasons".

This interface provides for two different methods of dealing with error conditions. The specific error codes (REG_EBRACE, for example), defined in <regex.h>, allow an application to recover from an error if it is so able. Many applications, especially those that use patterns supplied by a user, will not try to deal with specific error cases, but will just use regerror() to obtain a human-readable error message to present to the user.

The regerror() function uses a scheme similar to confstr() to deal with the problem of allocating memory to hold the generated string. The scheme used by strerror() in the ISO C standard was considered unacceptable since it creates difficulties for multi-threaded applications.

The preg argument is provided to regerror() to allow an implementation to generate a more descriptive message than would be possible with errcode alone. An implementation might, for example, save the character offset of the offending character of the pattern in a field of preg, and then include that in the generated message string. The implementation may also ignore preg.

A REG_FILENAME flag was considered, but omitted. This flag caused regexec() to match patterns as described in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13, Pattern Matching Notation instead of REs. This service is now provided by the fnmatch() function.

Notice that there is a difference in philosophy between the ISO POSIX-2:1993 standard and IEEE Std 1003.1-2001 in how to handle a "bad" regular expression. The ISO POSIX-2:1993 standard says that many bad constructs "produce undefined results", or that "the interpretation is undefined". IEEE Std 1003.1-2001, however, says that the interpretation of such REs is unspecified. The term "undefined" means that the action by the application is an error, of similar severity to passing a bad pointer to a function.

The regcomp() and regexec() functions are required to accept any null-terminated string as the pattern argument. If the meaning of the string is "undefined", the behavior of the function is "unspecified". IEEE Std 1003.1-2001 does not specify how the functions will interpret the pattern; they might return error codes, or they might do pattern matching in some completely unexpected way, but they should not do something like abort the process.

FUTURE DIRECTIONS

None.

SEE ALSO

fnmatch() , glob() , Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13, Pattern Matching Notation, Base Definitions volume of IEEE Std 1003.1-2001, Chapter 9, Regular Expressions, <regex.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cfsetospeed(3p)

CFSETOSPEED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cfsetospeed - set output baud rate

SYNOPSIS

#include <termios.h>

int cfsetospeed(struct termios *termios_p, speed_t speed);

DESCRIPTION

The cfsetospeed() function shall set the output baud rate stored in the structure pointed to by termios_p to speed.

There shall be no effect on the baud rates set in the hardware until a subsequent successful call to tcsetattr() with the same termios structure. Similarly, errors resulting from attempts to set baud rates not supported by the terminal device need not be detected until the tcsetattr() function is called.

RETURN VALUE

Upon successful completion, cfsetospeed() shall return 0; otherwise, it shall return -1 and errno may be set to indicate the error.

ERRORS

The cfsetospeed() function may fail if:

EINVAL
The speed value is not a valid baud rate.
EINVAL
The value of speed is outside the range of possible speed values as specified in <termios.h>.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to cfgetispeed() .

FUTURE DIRECTIONS

None.

SEE ALSO

cfgetispeed() , cfgetospeed() , cfsetispeed() , tcsetattr() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_barrierattr_getpshared(3p)

PTHREAD_BARRIERATTR_GETPSHARED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_barrierattr_getpshared, pthread_barrierattr_setpshared - get and set the process-shared attribute of the barrier attributes object (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_barrierattr_getpshared(const pthread_barrierattr_t *
restrict attr, int *restrict pshared);
int pthread_barrierattr_setpshared(pthread_barrierattr_t *attr,
int pshared);

DESCRIPTION

The pthread_barrierattr_getpshared() function shall obtain the value of the process-shared attribute from the attributes object referenced by attr. The pthread_barrierattr_setpshared() function shall set the process-shared attribute in an initialized attributes object referenced by attr.

The process-shared attribute is set to PTHREAD_PROCESS_SHARED to permit a barrier to be operated upon by any thread that has access to the memory where the barrier is allocated. If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the barrier shall only be operated upon by threads created within the same process as the thread that initialized the barrier; if threads of different processes attempt to operate on such a barrier, the behavior is undefined. The default value of the attribute shall be PTHREAD_PROCESS_PRIVATE. Both constants PTHREAD_PROCESS_SHARED and PTHREAD_PROCESS_PRIVATE are defined in <pthread.h>.

Additional attributes, their default values, and the names of the associated functions to get and set those attribute values are implementation-defined.

RETURN VALUE

If successful, the pthread_barrierattr_getpshared() function shall return zero and store the value of the process-shared attribute of attr into the object referenced by the pshared parameter. Otherwise, an error number shall be returned to indicate the error.

If successful, the pthread_barrierattr_setpshared() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_barrierattr_setpshared() function may fail if:

EINVAL
The new value specified for the process-shared attribute is not one of the legal values PTHREAD_PROCESS_SHARED or PTHREAD_PROCESS_PRIVATE.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_barrierattr_getpshared() and pthread_barrierattr_setpshared() functions are part of the Barriers option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_barrier_destroy() , pthread_barrierattr_destroy() , pthread_barrierattr_init() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


putc(3p)

PUTC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

putc - put a byte on a stream

SYNOPSIS

#include <stdio.h>

int putc(int c, FILE *stream);

DESCRIPTION

The putc() function shall be equivalent to fputc(), except that if it is implemented as a macro it may evaluate stream more than once, so the argument should never be an expression with side effects.

RETURN VALUE

Refer to fputc() .

ERRORS

Refer to fputc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Since it may be implemented as a macro, putc() may treat a stream argument with side effects incorrectly. In particular, putc(c,*f++) does not necessarily work correctly. Therefore, use of this function is not recommended in such situations; fputc() should be used instead.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fputc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iconv_open(3p)

ICONV_OPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iconv_open - codeset conversion allocation function

SYNOPSIS

#include <iconv.h>

iconv_t iconv_open(const char *tocode, const char *fromcode);

DESCRIPTION

The iconv_open() function shall return a conversion descriptor that describes a conversion from the codeset specified by the string pointed to by the fromcode argument to the codeset specified by the string pointed to by the tocode argument. For state-dependent encodings, the conversion descriptor shall be in a codeset-dependent initial shift state, ready for immediate use with iconv().

Settings of fromcode and tocode and their permitted combinations are implementation-defined.

A conversion descriptor shall remain valid until it is closed by iconv_close() or an implicit close.

If a file descriptor is used to implement conversion descriptors, the FD_CLOEXEC flag shall be set; see <fcntl.h>.

RETURN VALUE

Upon successful completion, iconv_open() shall return a conversion descriptor for use on subsequent calls to iconv(). Otherwise, iconv_open() shall return (iconv_t)-1 and set errno to indicate the error.

ERRORS

The iconv_open() function may fail if:

EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
Too many files are currently open in the system.
ENOMEM
Insufficient storage space is available.
EINVAL
The conversion specified by fromcode and tocode is not supported by the implementation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Some implementations of iconv_open() use malloc() to allocate space for internal buffer areas. The iconv_open() function may fail if there is insufficient storage space to accommodate these buffers.

Conforming applications must assume that conversion descriptors are not valid after a call to one of the exec functions.

Application developers should consult the system documentation to determine the supported codesets and their naming schemes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iconv() , iconv_close() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <iconv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


writev(3p)

WRITEV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

writev - write a vector

SYNOPSIS

#include <sys/uio.h>

ssize_t writev(int fildes, const struct iovec *iov, int iovcnt);

DESCRIPTION

The writev() function shall be equivalent to write(), except as described below. The writev() function shall gather output data from the iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt-1]. The iovcnt argument is valid if greater than 0 and less than or equal to {IOV_MAX}, as defined in <limits.h>.

Each iovec entry specifies the base address and length of an area in memory from which data should be written. The writev() function shall always write a complete area before proceeding to the next.

If fildes refers to a regular file and all of the iov_len members in the array pointed to by iov are 0, writev() shall return 0 and have no other effect. For other file types, the behavior is unspecified.

If the sum of the iov_len values is greater than {SSIZE_MAX}, the operation shall fail and no data shall be transferred.

RETURN VALUE

Upon successful completion, writev() shall return the number of bytes actually written. Otherwise, it shall return a value of -1, the file-pointer shall remain unchanged, and errno shall be set to indicate an error.

ERRORS

Refer to write() .

In addition, the writev() function shall fail if:

EINVAL
The sum of the iov_len values in the iov array would overflow an ssize_t.

The writev() function may fail and set errno to:

EINVAL
The iovcnt argument was less than or equal to 0, or greater than {IOV_MAX}.

The following sections are informative.

EXAMPLES

Writing Data from an Array

The following example writes data from the buffers specified by members of the iov array to the file associated with the file descriptor fd.

#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
...
ssize_t bytes_written;
int fd;
char *buf0 = "short string\n";
char *buf1 = "This is a longer string\n";
char *buf2 = "This is the longest string in this example\n";
int iovcnt;
struct iovec iov[3];

iov[0].iov_base = buf0;
iov[0].iov_len = strlen(buf0);
iov[1].iov_base = buf1;
iov[1].iov_len = strlen(buf1);
iov[2].iov_base = buf2;
iov[2].iov_len = strlen(buf2);
...
iovcnt = sizeof(iov) / sizeof(struct iovec);

bytes_written = writev(fd, iov, iovcnt);
...

APPLICATION USAGE

None.

RATIONALE

Refer to write() .

FUTURE DIRECTIONS

None.

SEE ALSO

readv() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <sys/uio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


timer_create(3p)

TIMER_CREATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

timer_create - create a per-process timer (REALTIME)

SYNOPSIS

#include <signal.h>
#include <time.h>

int timer_create(clockid_t clockid, struct sigevent *restrict evp,
timer_t *restrict timerid);

DESCRIPTION

The timer_create() function shall create a per-process timer using the specified clock, clock_id, as the timing base. The timer_create() function shall return, in the location referenced by timerid, a timer ID of type timer_t used to identify the timer in timer requests. This timer ID shall be unique within the calling process until the timer is deleted. The particular clock, clock_id, is defined in <time.h>. The timer whose ID is returned shall be in a disarmed state upon return from timer_create().

The evp argument, if non-NULL, points to a sigevent structure. This structure, allocated by the application, defines the asynchronous notification to occur as specified in Signal Generation and Delivery when the timer expires. If the evp argument is NULL, the effect is as if the evp argument pointed to a sigevent structure with the sigev_notify member having the value SIGEV_SIGNAL, the sigev_signo having a default signal number, and the sigev_value member having the value of the timer ID.

Each implementation shall define a set of clocks that can be used as timing bases for per-process timers. All implementations shall support a clock_id of CLOCK_REALTIME. If the Monotonic Clock option is supported, implementations shall support a clock_id of CLOCK_MONOTONIC.

Per-process timers shall not be inherited by a child process across a fork() and shall be disarmed and deleted by an exec.

If _POSIX_CPUTIME is defined, implementations shall support clock_id values representing the CPU-time clock of the calling process.

If _POSIX_THREAD_CPUTIME is defined, implementations shall support clock_id values representing the CPU-time clock of the calling thread.

It is implementation-defined whether a timer_create() function will succeed if the value defined by clock_id corresponds to the CPU-time clock of a process or thread different from the process or thread invoking the function.

RETURN VALUE

If the call succeeds, timer_create() shall return zero and update the location referenced by timerid to a timer_t, which can be passed to the per-process timer calls. If an error occurs, the function shall return a value of -1 and set errno to indicate the error. The value of timerid is undefined if an error occurs.

ERRORS

The timer_create() function shall fail if:

EAGAIN
The system lacks sufficient signal queuing resources to honor the request.
EAGAIN
The calling process has already created all of the timers it is allowed by this implementation.
EINVAL
The specified clock ID is not defined.
ENOTSUP
The implementation does not support the creation of a timer attached to the CPU-time clock that is specified by clock_id and associated with a process or thread different from the process or thread invoking timer_create().

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Periodic Timer Overrun and Resource Allocation

The specified timer facilities may deliver realtime signals (that is, queued signals) on implementations that support this option. Since realtime applications cannot afford to lose notifications of asynchronous events, like timer expirations or asynchronous I/O completions, it must be possible to ensure that sufficient resources exist to deliver the signal when the event occurs. In general, this is not a difficulty because there is a one-to-one correspondence between a request and a subsequent signal generation. If the request cannot allocate the signal delivery resources, it can fail the call with an [EAGAIN] error.

Periodic timers are a special case. A single request can generate an unspecified number of signals. This is not a problem if the requesting process can service the signals as fast as they are generated, thus making the signal delivery resources available for delivery of subsequent periodic timer expiration signals. But, in general, this cannot be assured-processing of periodic timer signals may "overrun''; that is, subsequent periodic timer expirations may occur before the currently pending signal has been delivered.

Also, for signals, according to the POSIX.1-1990 standard, if subsequent occurrences of a pending signal are generated, it is implementation-defined whether a signal is delivered for each occurrence. This is not adequate for some realtime applications. So a mechanism is required to allow applications to detect how many timer expirations were delayed without requiring an indefinite amount of system resources to store the delayed expirations.

The specified facilities provide for an overrun count. The overrun count is defined as the number of extra timer expirations that occurred between the time a timer expiration signal is generated and the time the signal is delivered. The signal-catching function, if it is concerned with overruns, can retrieve this count on entry. With this method, a periodic timer only needs one "signal queuing resource" that can be allocated at the time of the timer_create() function call.

A function is defined to retrieve the overrun count so that an application need not allocate static storage to contain the count, and an implementation need not update this storage asynchronously on timer expirations. But, for some high-frequency periodic applications, the overhead of an additional system call on each timer expiration may be prohibitive. The functions, as defined, permit an implementation to maintain the overrun count in user space, associated with the timerid. The timer_getoverrun() function can then be implemented as a macro that uses the timerid argument (which may just be a pointer to a user space structure containing the counter) to locate the overrun count with no system call overhead. Other implementations, less concerned with this class of applications, can avoid the asynchronous update of user space by maintaining the count in a system structure at the cost of the extra system call to obtain it.

Timer Expiration Signal Parameters

The Realtime Signals Extension option supports an application-specific datum that is delivered to the extended signal handler. This value is explicitly specified by the application, along with the signal number to be delivered, in a sigevent structure. The type of the application-defined value can be either an integer constant or a pointer. This explicit specification of the value, as opposed to always sending the timer ID, was selected based on existing practice.

It is common practice for realtime applications (on non-POSIX systems or realtime extended POSIX systems) to use the parameters of event handlers as the case label of a switch statement or as a pointer to an application-defined data structure. Since timer_ids are dynamically allocated by the timer_create() function, they can be used for neither of these functions without additional application overhead in the signal handler; for example, to search an array of saved timer IDs to associate the ID with a constant or application data structure.

FUTURE DIRECTIONS

None.

SEE ALSO

clock_getres() , timer_delete() , timer_getoverrun() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tolower(3p)

TOLOWER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tolower - transliterate uppercase characters to lowercase

SYNOPSIS

#include <ctype.h>

int tolower(int c);

DESCRIPTION

The tolower() function has as a domain a type int, the value of which is representable as an unsigned char or the value of EOF. If the argument has any other value, the behavior is undefined. If the argument of tolower() represents an uppercase letter, and there exists a corresponding lowercase letter (as defined by character type information in the program locale category LC_CTYPE ), the result shall be the corresponding lowercase letter. All other arguments in the domain are returned unchanged.

RETURN VALUE

Upon successful completion, tolower() shall return the lowercase letter corresponding to the argument passed; otherwise, it shall return the argument unchanged.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


puts(3p)

PUTS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

puts - put a string on standard output

SYNOPSIS

#include <stdio.h>

int puts(const char *s);

DESCRIPTION

The puts() function shall write the string pointed to by s, followed by a <newline>, to the standard output stream stdout. The terminating null byte shall not be written.

The st_ctime and st_mtime fields of the file shall be marked for update between the successful execution of puts() and the next successful completion of a call to fflush() or fclose() on the same stream or a call to exit() or abort().

RETURN VALUE

Upon successful completion, puts() shall return a non-negative number. Otherwise, it shall return EOF, shall set an error indicator for the stream, and errno shall be set to indicate the error.

ERRORS

Refer to fputc() .

The following sections are informative.

EXAMPLES

Printing to Standard Output

The following example gets the current time, converts it to a string using localtime() and asctime(), and prints it to standard output using puts(). It then prints the number of minutes to an event for which it is waiting.

#include <time.h>
#include <stdio.h>
...
time_t now;
int minutes_to_event;
...
time(&now);
printf("The time is ");
puts(asctime(localtime(&now)));
printf("There are %d minutes to the event.\n",
    minutes_to_event);
...

APPLICATION USAGE

The puts() function appends a <newline>, while fputs() does not.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , fputs() , putc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sched_getscheduler(3p)

SCHED_GETSCHEDULER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched_getscheduler - get scheduling policy (REALTIME)

SYNOPSIS

#include <sched.h>

int sched_getscheduler(pid_t pid);

DESCRIPTION

The sched_getscheduler() function shall return the scheduling policy of the process specified by pid. If the value of pid is negative, the behavior of the sched_getscheduler() function is unspecified.

The values that can be returned by sched_getscheduler() are defined in the <sched.h> header.

If a process specified by pid exists, and if the calling process has permission, the scheduling policy shall be returned for the process whose process ID is equal to pid.

If pid is zero, the scheduling policy shall be returned for the calling process.

RETURN VALUE

Upon successful completion, the sched_getscheduler() function shall return the scheduling policy of the specified process. If unsuccessful, the function shall return -1 and set errno to indicate the error.

ERRORS

The sched_getscheduler() function shall fail if:

EPERM
The requesting process does not have permission to determine the scheduling policy of the specified process.
ESRCH
No process can be found corresponding to that specified by pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sched_getparam() , sched_setparam() , sched_setscheduler() , the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventset_ismember (3p)

 Continue to this page.


timer_getoverrun (3p)

 Continue to this page.


seed48 (3p)

 Continue to this page.


strcat(3p)

STRCAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strcat - concatenate two strings

SYNOPSIS

#include <string.h>

char *strcat(char *restrict s1, const char *restrict s2);

DESCRIPTION

The strcat() function shall append a copy of the string pointed to by s2 (including the terminating null byte) to the end of the string pointed to by s1. The initial byte of s2 overwrites the null byte at the end of s1. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The strcat() function shall return s1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

This issue is aligned with the ISO C standard; this does not affect compatibility with XPG3 applications. Reliable error detection by this function was never guaranteed.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strncat() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strtold (3p)

 Continue to this page.


FD_ISSET (3p)

 Continue to this page.


atoll (3p)

 Continue to this page.


strtoll (3p)

 Continue to this page.


ftruncate(3p)

FTRUNCATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ftruncate - truncate a file to a specified length

SYNOPSIS

#include <unistd.h>

int ftruncate(int fildes, off_t length);

DESCRIPTION

If fildes is not a valid file descriptor open for writing, the ftruncate() function shall fail.

If fildes refers to a regular file, the ftruncate() function shall cause the size of the file to be truncated to length. If the size of the file previously exceeded length, the extra data shall no longer be available to reads on the file. If the file previously was smaller than this size, ftruncate() shall either increase the size of the file or fail. XSI-conformant systems shall increase the size of the file. If the file size is increased, the extended area shall appear as if it were zero-filled. The value of the seek pointer shall not be modified by a call to ftruncate().

Upon successful completion, if fildes refers to a regular file, the ftruncate() function shall mark for update the st_ctime and st_mtime fields of the file and the S_ISUID and S_ISGID bits of the file mode may be cleared. If the ftruncate() function is unsuccessful, the file is unaffected.

If the request would cause the file size to exceed the soft file size limit for the process, the request shall fail and the implementation shall generate the SIGXFSZ signal for the thread.

If fildes refers to a directory, ftruncate() shall fail.

If fildes refers to any other file type, except a shared memory object, the result is unspecified.

If fildes refers to a shared memory object, ftruncate() shall set the size of the shared memory object to length.

If the effect of ftruncate() is to decrease the size of a shared memory object or memory mapped file and whole pages beyond the new end were previously mapped, then the whole pages beyond the new end shall be discarded.

If the Memory Protection option is supported, references to discarded pages shall result in the generation of a SIGBUS signal; otherwise, the result of such references is undefined.

If the effect of ftruncate() is to increase the size of a shared memory object, it is unspecified whether the contents of any mapped pages between the old end-of-file and the new are flushed to the underlying object.

RETURN VALUE

Upon successful completion, ftruncate() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The ftruncate() function shall fail if:

EINTR
A signal was caught during execution.
EINVAL
The length argument was less than 0.
EFBIG or EINVAL

The length argument was greater than the maximum file size.

EFBIG
The file is a regular file and length is greater than the offset maximum established in the open file description associated with fildes.
EIO
An I/O error occurred while reading from or writing to a file system.
EBADF or EINVAL

The fildes argument is not a file descriptor open for writing.

EINVAL
The fildes argument references a file that was opened without write permission.
EROFS
The named file resides on a read-only file system.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The ftruncate() function is part of IEEE Std 1003.1-2001 as it was deemed to be more useful than truncate(). The truncate() function is provided as an XSI extension.

FUTURE DIRECTIONS

None.

SEE ALSO

open() , truncate() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getdate(3p)

GETDATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getdate - convert user format date and time

SYNOPSIS

#include <time.h>

struct tm *getdate(const char *string);

DESCRIPTION

The getdate() function shall convert a string representation of a date or time into a broken-down time.

The external variable or macro getdate_err is used by getdate() to return error values.

Templates are used to parse and interpret the input string. The templates are contained in a text file identified by the environment variable DATEMSK . The DATEMSK variable should be set to indicate the full pathname of the file that contains the templates. The first line in the template that matches the input specification is used for interpretation and conversion into the internal time format.

The following conversion specifications shall be supported:

%%
Equivalent to % .
%a
Abbreviated weekday name.
%A
Full weekday name.
%b
Abbreviated month name.
%B
Full month name.
%c
Locale's appropriate date and time representation.
%C
Century number [00,99]; leading zeros are permitted but not required.
%d
Day of month [01,31]; the leading 0 is optional.
%D
Date as %m / %d / %y .
%e
Equivalent to %d .
%h
Abbreviated month name.
%H
Hour [00,23].
%I
Hour [01,12].
%m
Month number [01,12].
%M
Minute [00,59].
%n
Equivalent to <newline>.
%p
Locale's equivalent of either AM or PM.
%r
The locale's appropriate representation of time in AM and PM notation. In the POSIX locale, this shall be equivalent to %I : %M : %S %p .
%R
Time as %H : %M .
%S
Seconds [00,60]. The range goes to 60 (rather than stopping at 59) to allow positive leap seconds to be expressed. Since leap seconds cannot be predicted by any algorithm, leap second data must come from some external source.
%t
Equivalent to <tab>.
%T
Time as %H : %M : %S .
%w
Weekday number (Sunday = [0,6]).
%x
Locale's appropriate date representation.
%X
Locale's appropriate time representation.
%y
Year within century. When a century is not otherwise specified, values in the range [69,99] shall refer to years 1969 to 1999 inclusive, and values in the range [00,68] shall refer to years 2000 to 2068 inclusive.
Note:
It is expected that in a future version of IEEE Std 1003.1-2001 the default century inferred from a 2-digit year will change. (This would apply to all commands accepting a 2-digit year as input.)

%Y
Year as "ccyy" (for example, 2001).
%Z
Timezone name or no characters if no timezone exists. If the timezone supplied by %Z is not the timezone that getdate() expects, an invalid input specification error shall result. The getdate() function calculates an expected timezone based on information supplied to the function (such as the hour, day, and month).

The match between the template and input specification performed by getdate() shall be case-insensitive.

The month and weekday names can consist of any combination of upper and lowercase letters. The process can request that the input date or time specification be in a specific language by setting the LC_TIME category (see setlocale() ).

Leading zeros are not necessary for the descriptors that allow leading zeros. However, at most two digits are allowed for those descriptors, including leading zeros. Extra whitespace in either the template file or in string shall be ignored.

The results are undefined if the conversion specifications %c , %x , and %X include unsupported conversion specifications.

The following rules apply for converting the input specification into the internal format:

*
If %Z is being scanned, then getdate() shall initialize the broken-down time to be the current time in the scanned timezone. Otherwise, it shall initialize the broken-down time based on the current local time as if localtime() had been called.

*
If only the weekday is given, the day chosen shall be the day, starting with today and moving into the future, which first matches the named day.

*
If only the month (and no year) is given, the month chosen shall be the month, starting with the current month and moving into the future, which first matches the named month. The first day of the month shall be assumed if no day is given.

*
If no hour, minute, and second are given, the current hour, minute, and second shall be assumed.

*
If no date is given, the hour chosen shall be the hour, starting with the current hour and moving into the future, which first matches the named hour.

If a conversion specification in the DATEMSK file does not correspond to one of the conversion specifications above, the behavior is unspecified.

The getdate() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, getdate() shall return a pointer to a struct tm. Otherwise, it shall return a null pointer and set getdate_err to indicate the error.

ERRORS

The getdate() function shall fail in the following cases, setting getdate_err to the value shown in the list below. Any changes to errno are unspecified.

1.
The DATEMSK environment variable is null or undefined.

2.
The template file cannot be opened for reading.

3.
Failed to get file status information.

4.
The template file is not a regular file.

5.
An I/O error is encountered while reading the template file.

6.
Memory allocation failed (not enough memory available).

7.
There is no line in the template that matches the input.

8.
Invalid input specification. For example, February 31; or a time is specified that cannot be represented in a time_t (representing the time in seconds since the Epoch).

The following sections are informative.

EXAMPLES

1.
The following example shows the possible contents of a template:

%m
%A %B %d, %Y, %H:%M:%S
%A
%B
%m/%d/%y %I %p
%d,%m,%Y %H:%M
at %A the %dst of %B in %Y
run job at %I %p,%B %dnd
%A den %d. %B %Y %H.%M Uhr

2.
The following are examples of valid input specifications for the template in Example 1:

getdate("10/1/87 4 PM");
getdate("Friday");
getdate("Friday September 18, 1987, 10:30:30");
getdate("24,9,1986 10:30");
getdate("at monday the 1st of december in 1986");
getdate("run job at 3 PM, december 2nd");

If the LC_TIME category is set to a German locale that includes freitag as a weekday name and oktober as a month name, the following would be valid:

getdate("freitag den 10. oktober 1986 10.30 Uhr");

3.
The following example shows how local date and time specification can be defined in the template:
Invocation Line in Template
getdate("11/27/86") %m/%d/%y
getdate("27.11.86") %d.%m.%y
getdate("86-11-27") %y-%m-%d
getdate("Friday 12:00:00") %A %H:%M:%S

4.
The following examples help to illustrate the above rules assuming that the current date is Mon Sep 22 12:19:47 EDT 1986 and the LC_TIME category is set to the default C locale:
Input Line in Template Date
Mon %a Mon Sep 22 12:19:47 EDT 1986
Sun %a Sun Sep 28 12:19:47 EDT 1986
Fri %a Fri Sep 26 12:19:47 EDT 1986
September %B Mon Sep 1 12:19:47 EDT 1986
January %B Thu Jan 1 12:19:47 EST 1987
December %B Mon Dec 1 12:19:47 EST 1986
Sep Mon %b %a Mon Sep 1 12:19:47 EDT 1986
Jan Fri %b %a Fri Jan 2 12:19:47 EST 1987
Dec Mon %b %a Mon Dec 1 12:19:47 EST 1986
Jan Wed 1989 %b %a %Y Wed Jan 4 12:19:47 EST 1989
Fri 9 %a %H Fri Sep 26 09:00:00 EDT 1986
Feb 10:30 %b %H:%S Sun Feb 1 10:00:30 EST 1987
10:30 %H:%M Tue Sep 23 10:30:00 EDT 1986
13:30 %H:%M Mon Sep 22 13:30:00 EDT 1986

APPLICATION USAGE

Although historical versions of getdate() did not require that <time.h> declare the external variable getdate_err, this volume of IEEE Std 1003.1-2001 does require it. The standard developers encourage applications to remove declarations of getdate_err and instead incorporate the declaration by including <time.h>.

Applications should use %Y (4-digit years) in preference to %y (2-digit years).

RATIONALE

In standard locales, the conversion specifications %c , %x , and %X do not include unsupported conversion specifiers and so the text regarding results being undefined is not a problem in that case.

FUTURE DIRECTIONS

None.

SEE ALSO

ctime() , localtime() , setlocale() , strftime() , times() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_cond_destroy (3p)

 Continue to this page.


iscntrl(3p)

ISCNTRL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iscntrl - test for a control character

SYNOPSIS

#include <ctype.h>

int iscntrl(int c);

DESCRIPTION

The iscntrl() function shall test whether c is a character of class cntrl in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is a type int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iscntrl() function shall return non-zero if c is a control character; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_getmaxdatasize (3p)

 Continue to this page.


stderr (3p)

 Continue to this page.


setcontext (3p)

 Continue to this page.


posix_trace_attr_getgenversion (3p)

 Continue to this page.


fgetwc(3p)

FGETWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fgetwc - get a wide-character code from a stream

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

wint_t fgetwc(FILE *stream);

DESCRIPTION

The fgetwc() function shall obtain the next character (if present) from the input stream pointed to by stream, convert that to the corresponding wide-character code, and advance the associated file position indicator for the stream (if defined).

If an error occurs, the resulting value of the file position indicator for the stream is unspecified.

The fgetwc() function may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fgetwc(), fgetws(), fread(), fscanf(), getc(), getchar(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc() or ungetwc().

RETURN VALUE

Upon successful completion, the fgetwc() function shall return the wide-character code of the character read from the input stream pointed to by stream converted to a type wint_t. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgetwc() shall return WEOF. If a read error occurs, the error indicator for the stream shall be set, fgetwc() shall return WEOF, and shall set errno to indicate the error. If an encoding error occurs, the error indicator for the stream shall be set, fgetwc() shall return WEOF, and shall set errno to indicate the error.

ERRORS

The fgetwc() function shall fail if data needs to be read and:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying stream and the process would be delayed in the fgetwc() operation.
EBADF
The file descriptor underlying stream is not a valid file descriptor open for reading.
EILSEQ
The data obtained from the input stream does not form a valid character.
EINTR
The read operation was terminated due to the receipt of a signal, and no data was transferred.
EIO
A physical I/O error has occurred, or the process is in a background process group attempting to read from its controlling terminal, and either the process is ignoring or blocking the SIGTTIN signal or the process group is orphaned. This error may also be generated for implementation-defined reasons.
EOVERFLOW
The file is a regular file and an attempt was made to read at or beyond the offset maximum associated with the corresponding stream.

The fgetwc() function may fail if:

ENOMEM
Insufficient storage space is available.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The ferror() or feof() functions must be used to distinguish between an error condition and an end-of-file condition.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feof() , ferror() , fopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strchr(3p)

STRCHR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strchr - string scanning operation

SYNOPSIS

#include <string.h>

char *strchr(const char *s, int c);

DESCRIPTION

The strchr() function shall locate the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null byte is considered to be part of the string.

RETURN VALUE

Upon completion, strchr() shall return a pointer to the byte, or a null pointer if the byte was not found.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strrchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


conj(3p)

CONJ

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

conj, conjf, conjl - complex conjugate functions

SYNOPSIS

#include <complex.h>

double complex conj(double complex z);
float complex conjf(float complex z);
long double complex conjl(long double complex z);

DESCRIPTION

These functions shall compute the complex conjugate of z, by reversing the sign of its imaginary part.

RETURN VALUE

These functions return the complex conjugate value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

carg() , cimag() , cproj() , creal() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fgetws(3p)

FGETWS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fgetws - get a wide-character string from a stream

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

wchar_t *fgetws(wchar_t *restrict ws, int n,
FILE *restrict stream);

DESCRIPTION

The fgetws() function shall read characters from the stream, convert these to the corresponding wide-character codes, place them in the wchar_t array pointed to by ws, until n-1 characters are read, or a <newline> is read, converted, and transferred to ws, or an end-of-file condition is encountered. The wide-character string, ws, shall then be terminated with a null wide-character code.

If an error occurs, the resulting value of the file position indicator for the stream is unspecified.

The fgetws() function may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fgetwc(), fgetws(), fread(), fscanf(), getc(), getchar(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc() or ungetwc().

RETURN VALUE

Upon successful completion, fgetws() shall return ws. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgetws() shall return a null pointer. If a read error occurs, the error indicator for the stream shall be set, fgetws() shall return a null pointer, and shall set errno to indicate the error.

ERRORS

Refer to fgetwc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , fread() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


rand(3p)

RAND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rand, rand_r, srand - pseudo-random number generator

SYNOPSIS

#include <stdlib.h>

int rand(void);

int rand_r(unsigned *seed);
void srand(unsigned seed);

DESCRIPTION

The rand() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}] with a period of at least 2**32.

The rand() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The rand_r() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}]. (The value of the {RAND_MAX} macro shall be at least 32767.)

If rand_r() is called with the same initial value for the object pointed to by seed and that object is not modified between successive returns and calls to rand_r(), the same sequence shall be generated.

The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand() is called before any calls to srand() are made, the same sequence shall be generated as when srand() is first called with a seed value of 1.

The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls rand() or srand().

RETURN VALUE

The rand() function shall return the next pseudo-random number in the sequence.

The rand_r() function shall return a pseudo-random integer.

The srand() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Generating a Pseudo-Random Number Sequence

The following example demonstrates how to generate a sequence of pseudo-random numbers.

#include <stdio.h>
#include <stdlib.h>
...
    long count, i;
    char *keystr;
    int elementlen, len;
    char c;
...
/* Initial random number generator. */
    srand(1);

    /* Create keys using only lowercase characters */
    len = 0;
    for (i=0; i<count; i++) {
        while (len < elementlen) {
            c = (char) (rand() % 128);
            if (islower(c))
                keystr[len++] = c;
        }

        keystr[len] = '\0';
        printf("%s Element%0*ld\n", keystr, elementlen, i);
        len = 0;
    }

Generating the Same Sequence on Different Machines

The following code defines a pair of functions that could be incorporated into applications wishing to ensure that the same sequence of numbers is generated across different machines.

static unsigned long next = 1;
int myrand(void)  /* RAND_MAX assumed to be 32767. */
{
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);
}

void mysrand(unsigned seed)
{
    next = seed;
}

APPLICATION USAGE

The drand48() function provides a much more elaborate random number generator.

The limitations on the amount of state that can be carried between one function call and another mean the rand_r() function can never be implemented in a way which satisfies all of the requirements on a pseudo-random number generator. Therefore this function should be avoided whenever non-trivial requirements (including safety) have to be fulfilled.

RATIONALE

The ISO C standard rand() and srand() functions allow per-process pseudo-random streams shared by all threads. Those two functions need not change, but there has to be mutual-exclusion that prevents interference between two threads concurrently accessing the random number generator.

With regard to rand(), there are two different behaviors that may be wanted in a multi-threaded program:

1.
A single per-process sequence of pseudo-random numbers that is shared by all threads that call rand()

2.
A different sequence of pseudo-random numbers for each thread that calls rand()

This is provided by the modified thread-safe function based on whether the seed value is global to the entire process or local to each thread.

This does not address the known deficiencies of the rand() function implementations, which have been approached by maintaining more state. In effect, this specifies new thread-safe forms of a deficient function.

FUTURE DIRECTIONS

None.

SEE ALSO

drand48() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fileno(3p)

FILENO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fileno - map a stream pointer to a file descriptor

SYNOPSIS

#include <stdio.h>

int fileno(FILE *stream);

DESCRIPTION

The fileno() function shall return the integer file descriptor associated with the stream pointed to by stream.

RETURN VALUE

Upon successful completion, fileno() shall return the integer value of the file descriptor associated with stream. Otherwise, the value -1 shall be returned and errno set to indicate the error.

ERRORS

The fileno() function may fail if:

EBADF
The stream argument is not a valid stream.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Without some specification of which file descriptors are associated with these streams, it is impossible for an application to set up the streams for another application it starts with fork() and exec. In particular, it would not be possible to write a portable version of the sh command interpreter (although there may be other constraints that would prevent that portability).

FUTURE DIRECTIONS

None.

SEE ALSO

Interaction of File Descriptors and Standard I/O Streams , fdopen() , fopen() , stdin() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctanf (3p)

 Continue to this page.


strtoul(3p)

STRTOUL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strtoul, strtoull - convert a string to an unsigned long

SYNOPSIS

#include <stdlib.h>

unsigned long strtoul(const char *restrict str,
char **restrict endptr, int base);
unsigned long long strtoull(const char *restrict str,
char **restrict endptr, int base);

DESCRIPTION

These functions shall convert the initial portion of the string pointed to by str to a type unsigned long and unsigned long long representation, respectively. First, they decompose the input string into three parts:

1.
An initial, possibly empty, sequence of white-space characters (as specified by isspace())

2.
A subject sequence interpreted as an integer represented in some radix determined by the value of base

3.
A final string of one or more unrecognized characters, including the terminating null byte of the input string

Then they shall attempt to convert the subject sequence to an unsigned integer, and return the result.

If the value of base is 0, the expected form of the subject sequence is that of a decimal constant, octal constant, or hexadecimal constant, any of which may be preceded by a '+' or '-' sign. A decimal constant begins with a non-zero digit, and consists of a sequence of decimal digits. An octal constant consists of the prefix '0' optionally followed by a sequence of the digits '0' to '7' only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and letters 'a' (or 'A' ) to 'f' (or 'F' ) with values 10 to 15 respectively.

If the value of base is between 2 and 36, the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a '+' or '-' sign. The letters from 'a' (or 'A' ) to 'z' (or 'Z' ) inclusive are ascribed the values 10 to 35; only letters whose ascribed values are less than that of base are permitted. If the value of base is 16, the characters 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.

The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character that is of the expected form. The subject sequence shall contain no characters if the input string is empty or consists entirely of white-space characters, or if the first non-white-space character is other than a sign or a permissible letter or digit.

If the subject sequence has the expected form and the value of base is 0, the sequence of characters starting with the first digit shall be interpreted as an integer constant. If the subject sequence has the expected form and the value of base is between 2 and 36, it shall be used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion shall be negated. A pointer to the final string shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

In other than the C or POSIX locales, other implementation-defined subject sequences may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion shall be performed; the value of str shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

The strtoul() function shall not change the setting of errno if successful.

Since 0, {ULONG_MAX}, and {ULLONG_MAX} are returned on error and are also valid returns on success, an application wishing to check for error situations should set errno to 0, then call strtoul() or strtoull(), then check errno.

RETURN VALUE

Upon successful completion, these functions shall return the converted value, if any. If no conversion could be performed, 0 shall be returned and errno may be set to [EINVAL]. If the correct value is outside the range of representable values, {ULONG_MAX} or {ULLONG_MAX} shall be returned and errno set to [ERANGE].

ERRORS

These functions shall fail if:

EINVAL
The value of base is not supported.
ERANGE
The value to be returned is not representable.

These functions may fail if:

EINVAL
No conversion could be performed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalpha() , scanf() , strtod() , strtol() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctanh(3p)

CTANH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ctanh, ctanhf, ctanhl - complex hyperbolic tangent functions

SYNOPSIS

#include <complex.h>

double complex ctanh(double complex z);
float complex ctanhf(float complex z);
long double complex ctanhl(long double complex z);

DESCRIPTION

These functions shall compute the complex hyperbolic tangent of z.

RETURN VALUE

These functions shall return the complex hyperbolic tangent value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

catanh() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lsearch(3p)

LSEARCH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lsearch, lfind - linear search and update

SYNOPSIS

#include <search.h>

void *lsearch(const void *key, void *base, size_t *nelp, size_t width,
int (*compar)(const void *, const void *));
void *lfind(const void *key, const void *base, size_t *nelp,
size_t width, int (*compar)(const void *, const void *));

DESCRIPTION

The lsearch() function shall linearly search the table and return a pointer into the table for the matching entry. If the entry does not occur, it shall be added at the end of the table. The key argument points to the entry to be sought in the table. The base argument points to the first element in the table. The width argument is the size of an element in bytes. The nelp argument points to an integer containing the current number of elements in the table. The integer to which nelp points shall be incremented if the entry is added to the table. The compar argument points to a comparison function which the application shall supply (for example, strcmp()). It is called with two arguments that point to the elements being compared. The application shall ensure that the function returns 0 if the elements are equal, and non-zero otherwise.

The lfind() function shall be equivalent to lsearch(), except that if the entry is not found, it is not added to the table. Instead, a null pointer is returned.

RETURN VALUE

If the searched for entry is found, both lsearch() and lfind() shall return a pointer to it. Otherwise, lfind() shall return a null pointer and lsearch() shall return a pointer to the newly added element.

Both functions shall return a null pointer in case of error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Storing Strings in a Table

This fragment reads in less than or equal to TABSIZE strings of length less than or equal to ELSIZE and stores them in a table, eliminating duplicates.

#include <stdio.h>
#include <string.h>
#include <search.h>

#define TABSIZE 50
#define ELSIZE 120

...
    char line[ELSIZE], tab[TABSIZE][ELSIZE];
    size_t nel = 0;
    ...
    while (fgets(line, ELSIZE, stdin) != NULL && nel < TABSIZE)
        (void) lsearch(line, tab, &nel,
            ELSIZE, (int (*)(const void *, const void *)) strcmp);
    ...

Finding a Matching Entry

The following example finds any line that reads "This is a test." .

#include <search.h>
#include <string.h>
...
char line[ELSIZE], tab[TABSIZE][ELSIZE];
size_t nel = 0;
char *findline;
void *entry;

findline = "This is a test.\n";

entry = lfind(findline, tab, &nel, ELSIZE, (
    int (*)(const void *, const void *)) strcmp);

APPLICATION USAGE

The comparison function need not compare every byte, so arbitrary data may be contained in the elements in addition to the values being compared.

Undefined results can occur if there is not enough room in the table to add a new item.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

hcreate() , tsearch() , the Base Definitions volume of IEEE Std 1003.1-2001, <search.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctanl (3p)

 Continue to this page.


posix_trace_attr_getname(3p)

POSIX_TRACE_ATTR_GETCLOCKRES

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_attr_getclockres, posix_trace_attr_getcreatetime, posix_trace_attr_getgenversion, posix_trace_attr_getname, posix_trace_attr_setname - retrieve and set information about a trace stream (TRACING)

SYNOPSIS

#include <time.h>
#include <trace.h>

int posix_trace_attr_getclockres(const trace_attr_t *attr,
struct timespec *resolution);
int posix_trace_attr_getcreatetime(const trace_attr_t *attr,
struct timespec *createtime);

#include <trace.h>
int posix_trace_attr_getgenversion(const trace_attr_t *attr,
char *genversion);
int posix_trace_attr_getname(const trace_attr_t *attr,
char *tracename);
int posix_trace_attr_setname(trace_attr_t *attr,
const char *tracename);

DESCRIPTION

The posix_trace_attr_getclockres() function shall copy the clock resolution of the clock used to generate timestamps from the clock-resolution attribute of the attributes object pointed to by the attr argument into the structure pointed to by the resolution argument.

The posix_trace_attr_getcreatetime() function shall copy the trace stream creation time from the creation-time attribute of the attributes object pointed to by the attr argument into the structure pointed to by the createtime argument. The creation-time attribute shall represent the time of creation of the trace stream.

The posix_trace_attr_getgenversion() function shall copy the string containing version information from the generation-version attribute of the attributes object pointed to by the attr argument into the string pointed to by the genversion argument. The genversion argument shall be the address of a character array which can store at least {TRACE_NAME_MAX} characters.

The posix_trace_attr_getname() function shall copy the string containing the trace name from the trace-name attribute of the attributes object pointed to by the attr argument into the string pointed to by the tracename argument. The tracename argument shall be the address of a character array which can store at least {TRACE_NAME_MAX} characters.

The posix_trace_attr_setname() function shall set the name in the trace-name attribute of the attributes object pointed to by the attr argument, using the trace name string supplied by the tracename argument. If the supplied string contains more than {TRACE_NAME_MAX} characters, the name copied into the trace-name attribute may be truncated to one less than the length of {TRACE_NAME_MAX} characters. The default value is a null string.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

If successful, the posix_trace_attr_getclockres() function stores the clock-resolution attribute value in the object pointed to by resolution. Otherwise, the content of this object is unspecified.

If successful, the posix_trace_attr_getcreatetime() function stores the trace stream creation time in the object pointed to by createtime. Otherwise, the content of this object is unspecified.

If successful, the posix_trace_attr_getgenversion() function stores the trace version information in the string pointed to by genversion. Otherwise, the content of this string is unspecified.

If successful, the posix_trace_attr_getname() function stores the trace name in the string pointed to by tracename. Otherwise, the content of this string is unspecified.

ERRORS

The posix_trace_attr_getclockres(), posix_trace_attr_getcreatetime(),
posix_trace_attr_getgenversion(), and
posix_trace_attr_getname() functions may fail if:

EINVAL
The value specified by one of the arguments is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_attr_init() , posix_trace_create() , posix_trace_get_attr() , uname() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


clock(3p)

CLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

clock - report CPU time used

SYNOPSIS

#include <time.h>

clock_t clock(void);

DESCRIPTION

The clock() function shall return the implementation's best approximation to the processor time used by the process since the beginning of an implementation-defined era related only to the process invocation.

RETURN VALUE

To determine the time in seconds, the value returned by clock() should be divided by the value of the macro CLOCKS_PER_SEC. CLOCKS_PER_SEC is defined to be one million in <time.h>. If the processor time used is not available or its value cannot be represented, the function shall return the value ( clock_t)-1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

In order to measure the time spent in a program, clock() should be called at the start of the program and its return value subtracted from the value returned by subsequent calls. The value returned by clock() is defined for compatibility across systems that have clocks with different resolutions. The resolution on any particular system need not be to microsecond accuracy.

The value returned by clock() may wrap around on some implementations. For example, on a machine with 32-bit values for clock_t, it wraps after 2147 seconds or 36 minutes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asctime() , ctime() , difftime() , gmtime() , localtime() , mktime() , strftime() , strptime() , time() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strcmp(3p)

STRCMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strcmp - compare two strings

SYNOPSIS

#include <string.h>

int strcmp(const char *s1, const char *s2);

DESCRIPTION

The strcmp() function shall compare the string pointed to by s1 to the string pointed to by s2.

The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared.

RETURN VALUE

Upon completion, strcmp() shall return an integer greater than, equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2, respectively.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Checking a Password Entry

The following example compares the information read from standard input to the value of the name of the user entry. If the strcmp() function returns 0 (indicating a match), a further check will be made to see if the user entered the proper old password. The crypt() function shall encrypt the old password entered by the user, using the value of the encrypted password in the passwd structure as the salt. If this value matches the value of the encrypted passwd in the structure, the entered password oldpasswd is the correct user's password. Finally, the program encrypts the new password so that it can store the information in the passwd structure.

#include <string.h>
#include <unistd.h>
#include <stdio.h>
...
int valid_change;
struct passwd *p;
char user[100];
char oldpasswd[100];
char newpasswd[100];
char savepasswd[100];
...
if (strcmp(p->pw_name, user) == 0) {
    if (strcmp(p->pw_passwd, crypt(oldpasswd, p->pw_passwd)) == 0) {
        strcpy(savepasswd, crypt(newpasswd, user));
        p->pw_passwd = savepasswd;
        valid_change = 1;
    }
    else {
        fprintf(stderr, "Old password is not valid\n");
    }
}
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strncmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vfwprintf (3p)

 Continue to this page.


cosf (3p)

 Continue to this page.


cosh(3p)

COSH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cosh, coshf, coshl - hyperbolic cosine functions

SYNOPSIS

#include <math.h>

double cosh(double x);
float coshf(float x);
long double coshl(long double x);

DESCRIPTION

These functions shall compute the hyperbolic cosine of their argument x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the hyperbolic cosine of x.

If the correct value would cause overflow, a range error shall occur and cosh(), coshf(), and coshl() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.

If x is NaN, a NaN shall be returned.

If x is ±0, the value 1.0 shall be returned.

If x is ±Inf, +Inf shall be returned.

ERRORS

These functions shall fail if:

Range Error
The result would cause an overflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

For IEEE Std 754-1985 double, 710.5 < |x| implies that cosh( x) has overflowed.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

acosh() , feclearexcept() , fetestexcept() , isnan() , sinh() , tanh() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cosl (3p)

 Continue to this page.


sched_getparam(3p)

SCHED_GETPARAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched_getparam - get scheduling parameters (REALTIME)

SYNOPSIS

#include <sched.h>

int sched_getparam(pid_t pid, struct sched_param *param);

DESCRIPTION

The sched_getparam() function shall return the scheduling parameters of a process specified by pid in the sched_param structure pointed to by param.

If a process specified by pid exists, and if the calling process has permission, the scheduling parameters for the process whose process ID is equal to pid shall be returned.

If pid is zero, the scheduling parameters for the calling process shall be returned. The behavior of the sched_getparam() function is unspecified if the value of pid is negative.

RETURN VALUE

Upon successful completion, the sched_getparam() function shall return zero. If the call to sched_getparam() is unsuccessful, the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sched_getparam() function shall fail if:

EPERM
The requesting process does not have permission to obtain the scheduling parameters of the specified process.
ESRCH
No process can be found corresponding to that specified by pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sched_getscheduler() , sched_setparam() , sched_setscheduler() , the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


hsearch (3p)

 Continue to this page.


wcstoumax (3p)

 Continue to this page.


clogf (3p)

 Continue to this page.


posix_trace_get_filter(3p)

POSIX_TRACE_GET_FILTER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_get_filter, posix_trace_set_filter - retrieve and set the filter of an initialized trace stream (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_get_filter(trace_id_t trid, trace_event_set_t *set);
int posix_trace_set_filter(trace_id_t trid,
const trace_event_set_t *set, int how);

DESCRIPTION

The posix_trace_get_filter() function shall retrieve, into the argument pointed to by set, the actual trace event filter from the trace stream specified by trid.

The posix_trace_set_filter() function shall change the set of filtered trace event types after a trace stream identified by the trid argument is created. This function may be called prior to starting the trace stream, or while the trace stream is active. By default, if no call is made to posix_trace_set_filter(), all trace events shall be recorded (that is, none of the trace event types are filtered out).

If this function is called while the trace is in progress, a special system trace event, POSIX_TRACE_FILTER, shall be recorded in the trace indicating both the old and the new sets of filtered trace event types (see Trace and Trace Event Filter Options: System Trace Events and Trace, Trace Log, and Trace Event Filter Options: System Trace Events ).

If the posix_trace_set_filter() function is interrupted by a signal, an error shall be returned and the filter shall not be changed. In this case, the state of the trace stream shall not be changed.

The value of the argument how indicates the manner in which the set is to be changed and shall have one of the following values, as defined in the <trace.h> header:

POSIX_TRACE_SET_EVENTSET

The resulting set of trace event types to be filtered shall be the trace event type set pointed to by the argument set.

POSIX_TRACE_ADD_EVENTSET

The resulting set of trace event types to be filtered shall be the union of the current set and the trace event type set pointed to by the argument set.

POSIX_TRACE_SUB_EVENTSET

The resulting set of trace event types to be filtered shall be all trace event types in the current set that are not in the set pointed to by the argument set; that is, remove each element of the specified set from the current filter.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

The posix_trace_get_filter() function stores the set of filtered trace event types in set, if successful.

ERRORS

These functions shall fail if:

EINVAL
The value of the trid argument does not correspond to an active trace stream or the value of the argument pointed to by set is invalid.
EINTR
The operation was interrupted by a signal.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Trace and Trace Event Filter Options: System Trace Events , Trace, Trace Log, and Trace Event Filter Options: System Trace Events , posix_trace_eventset_add() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strcpy(3p)

STRCPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strcpy - copy a string

SYNOPSIS

#include <string.h>

char *strcpy(char *restrict s1, const char *restrict s2);

DESCRIPTION

The strcpy() function shall copy the string pointed to by s2 (including the terminating null byte) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The strcpy() function shall return s1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Initializing a String

The following example copies the string "----------" into the permstring variable.

#include <string.h>
...
static char permstring[11];
...
strcpy(permstring, "----------");
...

Storing a Key and Data

The following example allocates space for a key using malloc() then uses strcpy() to place the key there. Then it allocates space for data using malloc(), and uses strcpy() to place data there. (The user-defined function dbfree() frees memory previously allocated to an array of type struct element *.)

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
...
/* Structure used to read data and store it. */
struct element {
    char *key;
    char *data;
};

struct element *tbl, *curtbl;
char *key, *data;
int count;
...
void dbfree(struct element *, int);
...
if ((curtbl->key = malloc(strlen(key) + 1)) == NULL) {
    perror("malloc"); dbfree(tbl, count); return NULL;
}
strcpy(curtbl->key, key);

if ((curtbl->data = malloc(strlen(data) + 1)) == NULL) {
    perror("malloc"); free(curtbl->key); dbfree(tbl, count); return NULL;
}
strcpy(curtbl->data, data);
...

APPLICATION USAGE

Character movement is performed differently in different implementations. Thus, overlapping moves may yield surprises.

This issue is aligned with the ISO C standard; this does not affect compatibility with XPG3 applications. Reliable error detection by this function was never guaranteed.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strncpy() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


clogl (3p)

 Continue to this page.


makecontext(3p)

MAKECONTEXT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

makecontext, swapcontext - manipulate user contexts

SYNOPSIS

#include <ucontext.h>

void makecontext(ucontext_t *ucp, void (*func)(void),
int argc, ...);
int swapcontext(ucontext_t *restrict oucp,
const ucontext_t *restrict ucp);

DESCRIPTION

The makecontext() function shall modify the context specified by ucp, which has been initialized using getcontext(). When this context is resumed using swapcontext() or setcontext(), program execution shall continue by calling func, passing it the arguments that follow argc in the makecontext() call.

Before a call is made to makecontext(), the application shall ensure that the context being modified has a stack allocated for it. The application shall ensure that the value of argc matches the number of arguments of type int passed to func; otherwise, the behavior is undefined.

The uc_link member is used to determine the context that shall be resumed when the context being modified by makecontext() returns. The application shall ensure that the uc_link member is initialized prior to the call to makecontext().

The swapcontext() function shall save the current context in the context structure pointed to by oucp and shall set the context to the context structure pointed to by ucp.

RETURN VALUE

Upon successful completion, swapcontext() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The swapcontext() function shall fail if:

ENOMEM
The ucp argument does not have enough stack left to complete the operation.

The following sections are informative.

EXAMPLES

The following example illustrates the use of makecontext():

#include <stdio.h>
#include <ucontext.h>

static ucontext_t ctx[3];

static void
f1 (void)
{
    puts("start f1");
    swapcontext(&ctx[1], &ctx[2]);
    puts("finish f1");
}

static void
f2 (void)
{
    puts("start f2");
    swapcontext(&ctx[2], &ctx[1]);
    puts("finish f2");
}

int
main (void)
{
    char st1[8192];
    char st2[8192];

    getcontext(&ctx[1]);
    ctx[1].uc_stack.ss_sp = st1;
    ctx[1].uc_stack.ss_size = sizeof st1;
    ctx[1].uc_link = &ctx[0];
    makecontext(&ctx[1], f1, 0);

    getcontext(&ctx[2]);
    ctx[2].uc_stack.ss_sp = st2;
    ctx[2].uc_stack.ss_size = sizeof st2;
    ctx[2].uc_link = &ctx[1];
    makecontext(&ctx[2], f2, 0);

    swapcontext(&ctx[0], &ctx[2]);
    return 0;
}

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exit() , getcontext() , sigaction() , sigprocmask() , the Base Definitions volume of IEEE Std 1003.1-2001, <ucontext.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_setstackaddr (3p)

 Continue to this page.


shmctl(3p)

SHMCTL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shmctl - XSI shared memory control operations

SYNOPSIS

#include <sys/shm.h>

int shmctl(int shmid, int cmd, struct shmid_ds *buf);

DESCRIPTION

The shmctl() function operates on XSI shared memory (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.340, Shared Memory Object). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The shmctl() function provides a variety of shared memory control operations as specified by cmd. The following values for cmd are available:

IPC_STAT
Place the current value of each member of the shmid_ds data structure associated with shmid into the structure pointed to by buf. The contents of the structure are defined in <sys/shm.h>.
IPC_SET
Set the value of the following members of the shmid_ds data structure associated with shmid to the corresponding value found in the structure pointed to by buf:

shm_perm.uid
shm_perm.gid
shm_perm.mode    Low-order nine bits.

IPC_SET can only be executed by a process that has an effective user ID equal to either that of a process with appropriate privileges or to the value of shm_perm.cuid or shm_perm.uid in the shmid_ds data structure associated with shmid.

IPC_RMID
Remove the shared memory identifier specified by shmid from the system and destroy the shared memory segment and shmid_ds data structure associated with it. IPC_RMID can only be executed by a process that has an effective user ID equal to either that of a process with appropriate privileges or to the value of shm_perm.cuid or shm_perm.uid in the shmid_ds data structure associated with shmid.

RETURN VALUE

Upon successful completion, shmctl() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The shmctl() function shall fail if:

EACCES
The argument cmd is equal to IPC_STAT and the calling process does not have read permission; see XSI Interprocess Communication .
EINVAL
The value of shmid is not a valid shared memory identifier, or the value of cmd is not a valid command.
EPERM
The argument cmd is equal to IPC_RMID or IPC_SET and the effective user ID of the calling process is not equal to that of a process with appropriate privileges and it is not equal to the value of shm_perm.cuid or shm_perm.uid in the data structure associated with shmid.

The shmctl() function may fail if:

EOVERFLOW
The cmd argument is IPC_STAT and the gid or uid value is too large to be stored in the structure pointed to by the buf argument.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , shmat() , shmdt() , shmget() , shm_open() , shm_unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/shm.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


casinhf (3p)

 Continue to this page.


sem_destroy(3p)

SEM_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_destroy - destroy an unnamed semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

int sem_destroy(sem_t *sem);

DESCRIPTION

The sem_destroy() function shall destroy the unnamed semaphore indicated by sem. Only a semaphore that was created using sem_init() may be destroyed using sem_destroy(); the effect of calling sem_destroy() with a named semaphore is undefined. The effect of subsequent use of the semaphore sem is undefined until sem is reinitialized by another call to sem_init().

It is safe to destroy an initialized semaphore upon which no threads are currently blocked. The effect of destroying a semaphore upon which other threads are currently blocked is undefined.

RETURN VALUE

Upon successful completion, a value of zero shall be returned. Otherwise, a value of -1 shall be returned and errno set to indicate the error.

ERRORS

The sem_destroy() function shall fail if:

EINVAL
The sem argument is not a valid semaphore.

The sem_destroy() function may fail if:

EBUSY
There are currently processes blocked on the semaphore.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sem_destroy() function is part of the Semaphores option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

semctl() , semget() , semop() , sem_init() , sem_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


casinhl (3p)

 Continue to this page.


cpow(3p)

CPOW

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cpow, cpowf, cpowl - complex power functions

SYNOPSIS

#include <complex.h>

double complex cpow(double complex x, double complex y);
float complex cpowf(float complex x, float complex y);
long double complex cpowl(long double complex x,
long double complex y);

DESCRIPTION

These functions shall compute the complex power function x**y, with a branch cut for the first parameter along the negative real axis.

RETURN VALUE

These functions shall return the complex power function value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cabs() , csqrt() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_init(3p)

POSIX_TRACE_ATTR_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_attr_destroy, posix_trace_attr_init - destroy and initialize the trace stream attributes object (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_attr_destroy(trace_attr_t *attr);
int posix_trace_attr_init(trace_attr_t *attr);

DESCRIPTION

The posix_trace_attr_destroy() function shall destroy an initialized trace attributes object. A destroyed attr attributes object can be reinitialized using posix_trace_attr_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

The posix_trace_attr_init() function shall initialize a trace attributes object attr with the default value for all of the individual attributes used by a given implementation. The read-only generation-version and clock-resolution attributes of the newly initialized trace attributes object shall be set to their appropriate values (see Trace Stream Attributes ).

Results are undefined if posix_trace_attr_init() is called specifying an already initialized attr attributes object.

Implementations may add extensions to the trace attributes object structure as permitted in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 2, Conformance.

The resulting attributes object (possibly modified by setting individual attributes values), when used by posix_trace_create(), defines the attributes of the trace stream created. A single attributes object can be used in multiple calls to posix_trace_create(). After one or more trace streams have been created using an attributes object, any function affecting that attributes object, including destruction, shall not affect any trace stream previously created. An initialized attributes object also serves to receive the attributes of an existing trace stream or trace log when calling the posix_trace_get_attr() function.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

ERRORS

The posix_trace_attr_destroy() function may fail if:

EINVAL
The value of attr is invalid.

The posix_trace_attr_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the trace attributes object.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_create() , posix_trace_get_attr() , uname() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_destroy (3p)

 Continue to this page.


sem_init(3p)

SEM_INIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_init - initialize an unnamed semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned value);

DESCRIPTION

The sem_init() function shall initialize the unnamed semaphore referred to by sem. The value of the initialized semaphore shall be value. Following a successful call to sem_init(), the semaphore may be used in subsequent calls to sem_wait(), sem_trywait(), sem_post(), and sem_destroy(). This semaphore shall remain usable until the semaphore is destroyed.

If the pshared argument has a non-zero value, then the semaphore is shared between processes; in this case, any process that can access the semaphore sem can use sem for performing sem_wait(), sem_trywait(), sem_post(), and sem_destroy() operations.

Only sem itself may be used for performing synchronization. The result of referring to copies of sem in calls to sem_wait(), sem_trywait(), sem_post(), and sem_destroy() is undefined.

If the pshared argument is zero, then the semaphore is shared between threads of the process; any thread in this process can use sem for performing sem_wait(), sem_trywait(), sem_post(), and sem_destroy() operations. The use of the semaphore by threads other than those created in the same process is undefined.

Attempting to initialize an already initialized semaphore results in undefined behavior.

RETURN VALUE

Upon successful completion, the sem_init() function shall initialize the semaphore in sem. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The sem_init() function shall fail if:

EINVAL
The value argument exceeds {SEM_VALUE_MAX}.
ENOSPC
A resource required to initialize the semaphore has been exhausted, or the limit on semaphores ( {SEM_NSEMS_MAX}) has been reached.
EPERM
The process lacks the appropriate privileges to initialize the semaphore.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sem_init() function is part of the Semaphores option and need not be available on all implementations.

RATIONALE

Although this volume of IEEE Std 1003.1-2001 fails to specify a successful return value, it is likely that a later version may require the implementation to return a value of zero if the call to sem_init() is successful.

FUTURE DIRECTIONS

None.

SEE ALSO

sem_destroy() , sem_post() , sem_timedwait() , sem_trywait() , sem_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


close(3p)

CLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

close - close a file descriptor

SYNOPSIS

#include <unistd.h>

int close(int fildes);

DESCRIPTION

The close() function shall deallocate the file descriptor indicated by fildes. To deallocate means to make the file descriptor available for return by subsequent calls to open() or other functions that allocate file descriptors. All outstanding record locks owned by the process on the file associated with the file descriptor shall be removed (that is, unlocked).

If close() is interrupted by a signal that is to be caught, it shall return -1 with errno set to [EINTR] and the state of fildes is unspecified. If an I/O error occurred while reading from or writing to the file system during close(), it may return -1 with errno set to [EIO]; if this error is returned, the state of fildes is unspecified.

When all file descriptors associated with a pipe or FIFO special file are closed, any data remaining in the pipe or FIFO shall be discarded.

When all file descriptors associated with an open file description have been closed, the open file description shall be freed.

If the link count of the file is 0, when all file descriptors associated with the file are closed, the space occupied by the file shall be freed and the file shall no longer be accessible.

If a STREAMS-based fildes is closed and the calling process was previously registered to receive a SIGPOLL signal for events associated with that STREAM, the calling process shall be unregistered for events associated with the STREAM. The last close() for a STREAM shall cause the STREAM associated with fildes to be dismantled. If O_NONBLOCK is not set and there have been no signals posted for the STREAM, and if there is data on the module's write queue, close() shall wait for an unspecified time (for each module and driver) for any output to drain before dismantling the STREAM. The time delay can be changed via an I_SETCLTIME ioctl() request. If the O_NONBLOCK flag is set, or if there are any pending signals, close() shall not wait for output to drain, and shall dismantle the STREAM immediately.

If the implementation supports STREAMS-based pipes, and fildes is associated with one end of a pipe, the last close() shall cause a hangup to occur on the other end of the pipe. In addition, if the other end of the pipe has been named by fattach(), then the last close() shall force the named end to be detached by fdetach(). If the named end has no open file descriptors associated with it and gets detached, the STREAM associated with that end shall also be dismantled.

If fildes refers to the master side of a pseudo-terminal, and this is the last close, a SIGHUP signal shall be sent to the controlling process, if any, for which the slave side of the pseudo-terminal is the controlling terminal. It is unspecified whether closing the master side of the pseudo-terminal flushes all queued input and output.

If fildes refers to the slave side of a STREAMS-based pseudo-terminal, a zero-length message may be sent to the master.

When there is an outstanding cancelable asynchronous I/O operation against fildes when close() is called, that I/O operation may be canceled. An I/O operation that is not canceled completes as if the close() operation had not yet occurred. All operations that are not canceled shall complete as if the close() blocked until the operations completed. The close() operation itself need not block awaiting such I/O completion. Whether any I/O operation is canceled, and which I/O operation may be canceled upon close(), is implementation-defined.

If a shared memory object or a memory mapped file remains referenced at the last close (that is, a process has it mapped), then the entire contents of the memory object shall persist until the memory object becomes unreferenced. If this is the last close of a shared memory object or a memory mapped file and the close results in the memory object becoming unreferenced, and the memory object has been unlinked, then the memory object shall be removed.

If fildes refers to a socket, close() shall cause the socket to be destroyed. If the socket is in connection-mode, and the SO_LINGER option is set for the socket with non-zero linger time, and the socket has untransmitted data, then close() shall block for up to the current linger interval until all data is transmitted.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The close() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINTR
The close() function was interrupted by a signal.

The close() function may fail if:

EIO
An I/O error occurred while reading from or writing to the file system.

The following sections are informative.

EXAMPLES

Reassigning a File Descriptor

The following example closes the file descriptor associated with standard output for the current process, re-assigns standard output to a new file descriptor, and closes the original file descriptor to clean up. This example assumes that the file descriptor 0 (which is the descriptor for standard input) is not closed.

#include <unistd.h>
...
int pfd;
...
close(1);
dup(pfd);
close(pfd);
...

Incidentally, this is exactly what could be achieved using:

dup2(pfd, 1);
close(pfd);

Closing a File Descriptor

In the following example, close() is used to close a file descriptor after an unsuccessful attempt is made to associate that file descriptor with a stream.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define LOCKFILE "/etc/ptmp"
...
int pfd;
FILE *fpfd;
...
if ((fpfd = fdopen (pfd, "w")) == NULL) {
    close(pfd);
    unlink(LOCKFILE);
    exit(1);
}
...

APPLICATION USAGE

An application that had used the stdio routine fopen() to open a file should use the corresponding fclose() routine rather than close(). Once a file is closed, the file descriptor no longer exists, since the integer corresponding to it no longer refers to a file.

RATIONALE

The use of interruptible device close routines should be discouraged to avoid problems with the implicit closes of file descriptors by exec and exit(). This volume of IEEE Std 1003.1-2001 only intends to permit such behavior by specifying the [EINTR] error condition.

FUTURE DIRECTIONS

None.

SEE ALSO

STREAMS , fattach() , fclose() , fdetach() , fopen() , ioctl() , open() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_join(3p)

PTHREAD_JOIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_join - wait for thread termination

SYNOPSIS

#include <pthread.h>

int pthread_join(pthread_t thread, void **value_ptr);

DESCRIPTION

The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated. On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr. When a pthread_join() returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined. If the thread calling pthread_join() is canceled, then the target thread shall not be detached.

It is unspecified whether a thread that has exited but remains unjoined counts against {PTHREAD_THREADS_MAX}.

RETURN VALUE

If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_join() function shall fail if:

EINVAL
The implementation has detected that the value specified by thread does not refer to a joinable thread.
ESRCH
No thread could be found corresponding to that specified by the given thread ID.

The pthread_join() function may fail if:

EDEADLK
A deadlock was detected or the value of thread specifies the calling thread.

The pthread_join() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

An example of thread creation and deletion follows:

typedef struct {
    int *ar;
    long n;
} subarray;

void *
incer(void *arg)
{
    long i;

    for (i = 0; i < ((subarray *)arg)->n; i++)
        ((subarray *)arg)->ar[i]++;
}

int main(void)
{
    int        ar[1000000];
    pthread_t  th1, th2;
    subarray   sb1, sb2;

    sb1.ar = &ar[0];
    sb1.n  = 500000;
    (void) pthread_create(&th1, NULL, incer, &sb1);

    sb2.ar = &ar[500000];
    sb2.n  = 500000;
    (void) pthread_create(&th2, NULL, incer, &sb2);

    (void) pthread_join(th1, NULL);
    (void) pthread_join(th2, NULL);
    return 0;
}

APPLICATION USAGE

None.

RATIONALE

The pthread_join() function is a convenience that has proven useful in multi-threaded applications. It is true that a programmer could simulate this function if it were not provided by passing extra state as part of the argument to the start_routine(). The terminating thread would set a flag to indicate termination and broadcast a condition that is part of that state; a joining thread would wait on that condition variable. While such a technique would allow a thread to wait on more complex conditions (for example, waiting for multiple threads to terminate), waiting on individual thread termination is considered widely useful. Also, including the pthread_join() function in no way precludes a programmer from coding such complex waits. Thus, while not a primitive, including pthread_join() in this volume of IEEE Std 1003.1-2001 was considered valuable.

The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread. For instance, after pthread_join() returns, any application-provided stack storage could be reclaimed.

The pthread_join() or pthread_detach() function should eventually be called for every thread that is created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE so that storage associated with the thread may be reclaimed.

The interaction between pthread_join() and cancellation is well-defined for the following reasons:

*
The pthread_join() function, like all other non-async-cancel-safe functions, can only be called with deferred cancelability type.

*
Cancellation cannot occur in the disabled cancelability state.

Thus, only the default cancelability state need be considered. As specified, either the pthread_join() call is canceled, or it succeeds, but not both. The difference is obvious to the application, since either a cancellation handler is run or pthread_join() returns. There are no race conditions since pthread_join() was called in the deferred cancelability state.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_create() , wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


crypt(3p)

CRYPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

crypt - string encoding function (CRYPT)

SYNOPSIS

#include <unistd.h>

char *crypt(const char *key, const char *salt);

DESCRIPTION

The crypt() function is a string encoding function. The algorithm is implementation-defined.

The key argument points to a string to be encoded. The salt argument is a string chosen from the set:

a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9 . /

The first two characters of this string may be used to perturb the encoding algorithm.

The return value of crypt() points to static data that is overwritten by each call.

The crypt() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, crypt() shall return a pointer to the encoded string. The first two characters of the returned value shall be those of the salt argument. Otherwise, it shall return a null pointer and set errno to indicate the error.

ERRORS

The crypt() function shall fail if:

ENOSYS
The functionality is not supported on this implementation.

The following sections are informative.

EXAMPLES

Encoding Passwords

The following example finds a user database entry matching a particular user name and changes the current password to a new password. The crypt() function generates an encoded version of each password. The first call to crypt() produces an encoded version of the old password; that encoded password is then compared to the password stored in the user database. The second call to crypt() encodes the new password before it is stored.

The putpwent() function, used in the following example, is not part of IEEE Std 1003.1-2001.

#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
...
int valid_change;
int pfd;  /* Integer for file descriptor returned by open(). */
FILE *fpfd;  /* File pointer for use in putpwent(). */
struct passwd *p;
char user[100];
char oldpasswd[100];
char newpasswd[100];
char savepasswd[100];
...
valid_change = 0;
while ((p = getpwent()) != NULL) {
    /* Change entry if found. */
    if (strcmp(p->pw_name, user) == 0) {
        if (strcmp(p->pw_passwd, crypt(oldpasswd, p->pw_passwd)) == 0) {
            strcpy(savepasswd, crypt(newpasswd, user));
            p->pw_passwd = savepasswd;
            valid_change = 1;
        }
        else {
            fprintf(stderr, "Old password is not valid\n");
        }
    }
    /* Put passwd entry into ptmp. */
    putpwent(p, fpfd);
}

APPLICATION USAGE

The values returned by this function need not be portable among XSI-conformant systems.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

encrypt() , setkey() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strdup(3p)

STRDUP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strdup - duplicate a string

SYNOPSIS

#include <string.h>

char *strdup(const char *s1);

DESCRIPTION

The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1. The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created.

RETURN VALUE

The strdup() function shall return a pointer to a new string on success. Otherwise, it shall return a null pointer and set errno to indicate the error.

ERRORS

The strdup() function may fail if:

ENOMEM
Storage space available is insufficient.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

free() , malloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getlogin(3p)

GETLOGIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getlogin, getlogin_r - get login name

SYNOPSIS

#include <unistd.h>

char *getlogin(void);

int getlogin_r(char *name, size_t namesize);

DESCRIPTION

The getlogin() function shall return a pointer to a string containing the user name associated by the login activity with the controlling terminal of the current process. If getlogin() returns a non-null pointer, then that pointer points to the name that the user logged in under, even if there are several login names with the same user ID.

The getlogin() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The getlogin_r() function shall put the name associated by the login activity with the controlling terminal of the current process in the character array pointed to by name. The array is namesize characters long and should have space for the name and the terminating null character. The maximum size of the login name is {LOGIN_NAME_MAX}.

If getlogin_r() is successful, name points to the name the user used at login, even if there are several login names with the same user ID.

RETURN VALUE

Upon successful completion, getlogin() shall return a pointer to the login name or a null pointer if the user's login name cannot be found. Otherwise, it shall return a null pointer and set errno to indicate the error.

The return value from getlogin() may point to static data whose content is overwritten by each call.

If successful, the getlogin_r() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The getlogin() and getlogin_r() functions may fail if:

EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.
ENXIO
The calling process has no controlling terminal.

The getlogin_r() function may fail if:

ERANGE
The value of namesize is smaller than the length of the string to be returned including the terminating null character.

The following sections are informative.

EXAMPLES

Getting the User Login Name

The following example calls the getlogin() function to obtain the name of the user associated with the calling process, and passes this information to the getpwnam() function to get the associated user database information.

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
...
char *lgn;
struct passwd *pw;
...
if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL) {
    fprintf(stderr, "Get of user information failed.\n"); exit(1);
    }

APPLICATION USAGE

Three names associated with the current process can be determined: getpwuid( geteuid()) shall return the name associated with the effective user ID of the process; getlogin() shall return the name associated with the current login activity; and getpwuid( getuid()) shall return the name associated with the real user ID of the process.

The getlogin_r() function is thread-safe and returns values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

The getlogin() function returns a pointer to the user's login name. The same user ID may be shared by several login names. If it is desired to get the user database entry that is used during login, the result of getlogin() should be used to provide the argument to the getpwnam() function. (This might be used to determine the user's login shell, particularly where a single user has multiple login shells with distinct login names, but the same user ID.)

The information provided by the cuserid() function, which was originally defined in the POSIX.1-1988 standard and subsequently removed, can be obtained by the following:

getpwuid(geteuid())

while the information provided by historical implementations of cuserid() can be obtained by:

getpwuid(getuid())

The thread-safe version of this function places the user name in a user-supplied buffer and returns a non-zero value if it fails. The non-thread-safe version may return the name in a static data area that may be overwritten by each call.

FUTURE DIRECTIONS

None.

SEE ALSO

getpwnam() , getpwuid() , geteuid() , getuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nexttoward (3p)

 Continue to this page.


pthread_mutexattr_getprioceiling(3p)

PTHREAD_MUTEXATTR_GETPRIOCEILING

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutexattr_getprioceiling, pthread_mutexattr_setprioceiling - get and set the prioceiling attribute of the mutex attributes object (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *
restrict attr, int *restrict prioceiling);
int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr,
int prioceiling);

DESCRIPTION

The pthread_mutexattr_getprioceiling() and pthread_mutexattr_setprioceiling() functions, respectively, shall get and set the priority ceiling attribute of a mutex attributes object pointed to by attr which was previously created by the function pthread_mutexattr_init().

The prioceiling attribute contains the priority ceiling of initialized mutexes. The values of prioceiling are within the maximum range of priorities defined by SCHED_FIFO.

The prioceiling attribute defines the priority ceiling of initialized mutexes, which is the minimum priority level at which the critical section guarded by the mutex is executed. In order to avoid priority inversion, the priority ceiling of the mutex shall be set to a priority higher than or equal to the highest priority of all the threads that may lock that mutex. The values of prioceiling are within the maximum range of priorities defined under the SCHED_FIFO scheduling policy.

RETURN VALUE

Upon successful completion, the pthread_mutexattr_getprioceiling() and pthread_mutexattr_setprioceiling() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_mutexattr_getprioceiling() and pthread_mutexattr_setprioceiling() functions may fail if:

EINVAL
The value specified by attr or prioceiling is invalid.
EPERM
The caller does not have the privilege to perform the operation.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_destroy() , pthread_create() , pthread_mutex_destroy() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigaltstack(3p)

SIGALTSTACK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigaltstack - set and get signal alternate stack context

SYNOPSIS

#include <signal.h>

int sigaltstack(const stack_t *restrict ss, stack_t *restrict oss);

DESCRIPTION

The sigaltstack() function allows a process to define and examine the state of an alternate stack for signal handlers for the current thread. Signals that have been explicitly declared to execute on the alternate stack shall be delivered on the alternate stack.

If ss is not a null pointer, it points to a stack_t structure that specifies the alternate signal stack that shall take effect upon return from sigaltstack(). The ss_flags member specifies the new stack state. If it is set to SS_DISABLE, the stack is disabled and ss_sp and ss_size are ignored. Otherwise, the stack shall be enabled, and the ss_sp and ss_size members specify the new address and size of the stack.

The range of addresses starting at ss_sp up to but not including ss_sp+ ss_size is available to the implementation for use as the stack. This function makes no assumptions regarding which end is the stack base and in which direction the stack grows as items are pushed.

If oss is not a null pointer, on successful completion it shall point to a stack_t structure that specifies the alternate signal stack that was in effect prior to the call to sigaltstack(). The ss_sp and ss_size members specify the address and size of that stack. The ss_flags member specifies the stack's state, and may contain one of the following values:

SS_ONSTACK
The process is currently executing on the alternate signal stack. Attempts to modify the alternate signal stack while the process is executing on it fail. This flag shall not be modified by processes.
SS_DISABLE
The alternate signal stack is currently disabled.

The value SIGSTKSZ is a system default specifying the number of bytes that would be used to cover the usual case when manually allocating an alternate stack area. The value MINSIGSTKSZ is defined to be the minimum stack size for a signal handler. In computing an alternate stack size, a program should add that amount to its stack requirements to allow for the system implementation overhead. The constants SS_ONSTACK, SS_DISABLE, SIGSTKSZ, and MINSIGSTKSZ are defined in <signal.h>.

After a successful call to one of the exec functions, there are no alternate signal stacks in the new process image.

In some implementations, a signal (whether or not indicated to execute on the alternate stack) shall always execute on the alternate stack if it is delivered while another signal is being caught using the alternate stack.

Use of this function by library threads that are not bound to kernel-scheduled entities results in undefined behavior.

RETURN VALUE

Upon successful completion, sigaltstack() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The sigaltstack() function shall fail if:

EINVAL
The ss argument is not a null pointer, and the ss_flags member pointed to by ss contains flags other than SS_DISABLE.
ENOMEM
The size of the alternate stack area is less than MINSIGSTKSZ.
EPERM
An attempt was made to modify an active stack.

The following sections are informative.

EXAMPLES

Allocating Memory for an Alternate Stack

The following example illustrates a method for allocating memory for an alternate stack.

#include <signal.h>
...
if ((sigstk.ss_sp = malloc(SIGSTKSZ)) == NULL)
    /* Error return. */
sigstk.ss_size = SIGSTKSZ;
sigstk.ss_flags = 0;
if (sigaltstack(&sigstk,(stack_t *)0) < 0)
    perror("sigaltstack");

APPLICATION USAGE

On some implementations, stack space is automatically extended as needed. On those implementations, automatic extension is typically not available for an alternate stack. If the stack overflows, the behavior is undefined.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , sigaction() , sigsetjmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_setstack (3p)

 Continue to this page.


pthread_rwlock_wrlock(3p)

PTHREAD_RWLOCK_TRYWRLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlock_trywrlock, pthread_rwlock_wrlock - lock a read-write lock object for writing

SYNOPSIS

#include <pthread.h>

int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);

DESCRIPTION

The pthread_rwlock_trywrlock() function shall apply a write lock like the pthread_rwlock_wrlock() function, with the exception that the function shall fail if any thread currently holds rwlock (for reading or writing).

The pthread_rwlock_wrlock() function shall apply a write lock to the read-write lock referenced by rwlock. The calling thread acquires the write lock if no other thread (reader or writer) holds the read-write lock rwlock. Otherwise, the thread shall block until it can acquire the lock. The calling thread may deadlock if at the time the call is made it holds the read-write lock (whether a read or write lock).

Implementations may favor writers over readers to avoid writer starvation.

Results are undefined if any of these functions are called with an uninitialized read-write lock.

If a signal is delivered to a thread waiting for a read-write lock for writing, upon return from the signal handler the thread resumes waiting for the read-write lock for writing as if it was not interrupted.

RETURN VALUE

The pthread_rwlock_trywrlock() function shall return zero if the lock for writing on the read-write lock object referenced by rwlock is acquired. Otherwise, an error number shall be returned to indicate the error.

If successful, the pthread_rwlock_wrlock() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_rwlock_trywrlock() function shall fail if:

EBUSY
The read-write lock could not be acquired for writing because it was already locked for reading or writing.

The pthread_rwlock_trywrlock() and pthread_rwlock_wrlock() functions may fail if:

EINVAL
The value specified by rwlock does not refer to an initialized read-write lock object.

The pthread_rwlock_wrlock() function may fail if:

EDEADLK
The current thread already owns the read-write lock for writing or reading.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_destroy() , pthread_rwlock_rdlock() , pthread_rwlock_timedrdlock() , pthread_rwlock_timedwrlock() , pthread_rwlock_tryrdlock() , pthread_rwlock_unlock() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


localtime_r (3p)

 Continue to this page.


read(3p)

READ

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pread, read - read from a file

SYNOPSIS

#include <unistd.h>

ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
ssize_t read(int fildes, void *buf, size_t nbyte);

DESCRIPTION

The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

Before any action described below is taken, and if nbyte is zero, the read() function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, the read() function shall return zero and have no other results.

On files that support seeking (for example, a regular file), the read() shall start at a position in the file given by the file offset associated with fildes. The file offset shall be incremented by the number of bytes actually read.

Files that do not support seeking-for example, terminals-always read from the current position. The value of a file offset associated with such a file is undefined.

No data transfer shall occur past the current end-of-file. If the starting position is at or after the end-of-file, 0 shall be returned. If the file refers to a device special file, the result of subsequent read() requests is implementation-defined.

If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined.

When attempting to read from an empty pipe or FIFO:

*
If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file.

*
If some process has the pipe open for writing and O_NONBLOCK is set, read() shall return -1 and set errno to [EAGAIN].

*
If some process has the pipe open for writing and O_NONBLOCK is clear, read() shall block the calling thread until some data is written or the pipe is closed by all processes that had the pipe open for writing.

When attempting to read a file (other than a pipe or FIFO) that supports non-blocking reads and has no data currently available:

*
If O_NONBLOCK is set, read() shall return -1 and set errno to [EAGAIN].

*
If O_NONBLOCK is clear, read() shall block the calling thread until some data becomes available.

*
The use of the O_NONBLOCK flag has no effect if there is some data available.

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads in the gap between the previous end of data and the newly written data shall return bytes with value 0 until data is written into the gap.

Upon successful completion, where nbyte is greater than 0, read() shall mark for update the st_atime field of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data.

If a read() is interrupted by a signal before it reads any data, it shall return -1 with errno set to [EINTR].

If a read() is interrupted by a signal after it has successfully read some data, it shall return the number of bytes read.

For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with fildes.

If fildes refers to a socket, read() shall be equivalent to recv() with no flags set.

If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If the O_SYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.

If fildes refers to a shared memory object, the result of the read() function is unspecified.

If fildes refers to a typed memory object, the result of the read() function is unspecified.

A read() from a STREAMS file can read data in three different modes: byte-stream mode, message-nondiscard mode, and message-discard mode. The default shall be byte-stream mode. This can be changed using the I_SRDOPT ioctl() request, and can be tested with I_GRDOPT ioctl(). In byte-stream mode, read() shall retrieve data from the STREAM until as many bytes as were requested are transferred, or until there is no more data to be retrieved. Byte-stream mode ignores message boundaries.

In STREAMS message-nondiscard mode, read() shall retrieve data until as many bytes as were requested are transferred, or until a message boundary is reached. If read() does not retrieve all the data in a message, the remaining data shall be left on the STREAM, and can be retrieved by the next read() call. Message-discard mode also retrieves data until as many bytes as were requested are transferred, or a message boundary is reached. However, unread data remaining in a message after the read() returns shall be discarded, and shall not be available for a subsequent read(), getmsg(), or getpmsg() call.

How read() handles zero-byte STREAMS messages is determined by the current read mode setting. In byte-stream mode, read() shall accept data until it has read nbyte bytes, or until there is no more data to read, or until a zero-byte message block is encountered. The read() function shall then return the number of bytes read, and place the zero-byte message back on the STREAM to be retrieved by the next read(), getmsg(), or getpmsg(). In message-nondiscard mode or message-discard mode, a zero-byte message shall return 0 and the message shall be removed from the STREAM. When a zero-byte message is read as the first message on a STREAM, the message shall be removed from the STREAM and 0 shall be returned, regardless of the read mode.

A read() from a STREAMS file shall return the data in the message at the front of the STREAM head read queue, regardless of the priority band of the message.

By default, STREAMs are in control-normal mode, in which a read() from a STREAMS file can only process messages that contain a data part but do not contain a control part. The read() shall fail if a message containing a control part is encountered at the STREAM head. This default action can be changed by placing the STREAM in either control-data mode or control-discard mode with the I_SRDOPT ioctl() command. In control-data mode, read() shall convert any control part to data and pass it to the application before passing any data part originally present in the same message. In control-discard mode, read() shall discard message control parts but return to the process any data part in the message.

In addition, read() shall fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno shall not reflect the result of read(), but reflect the prior error. If a hangup occurs on the STREAM being read, read() shall continue to operate normally until the STREAM head read queue is empty. Thereafter, it shall return 0.

The pread() function shall be equivalent to read(), except that it shall read from a given position in the file without changing the file pointer. The first three arguments to pread() are the same as read() with the addition of a fourth argument offset for the desired position inside the file. An attempt to perform a pread() on a file that is incapable of seeking shall result in an error.

RETURN VALUE

Upon successful completion, read() and pread() shall return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall return -1 and set errno to indicate the error.

ERRORS

The read() and pread() functions shall fail if:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor and the process would be delayed.
EBADF
The fildes argument is not a valid file descriptor open for reading.
EBADMSG
The file is a STREAM file that is set to control-normal mode and the message waiting to be read includes a control part.
EINTR
The read operation was terminated due to the receipt of a signal, and no data was transferred.
EINVAL
The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer.
EIO
The process is a member of a background process attempting to read from its controlling terminal, the process is ignoring or blocking the SIGTTIN signal, or the process group is orphaned. This error may also be generated for implementation-defined reasons.
EISDIR
The fildes argument refers to a directory and the implementation does not allow the directory to be read using read() or pread(). The readdir() function should be used instead.
EOVERFLOW
The file is a regular file, nbyte is greater than 0, the starting position is before the end-of-file, and the starting position is greater than or equal to the offset maximum established in the open file description associated with fildes.

The read() function shall fail if:

EAGAIN or EWOULDBLOCK

The file descriptor is for a socket, is marked O_NONBLOCK, and no data is waiting to be received.

ECONNRESET
A read was attempted on a socket and the connection was forcibly closed by its peer.
ENOTCONN
A read was attempted on a socket that is not connected.
ETIMEDOUT
A read was attempted on a socket and a transmission timeout occurred.

The read() and pread() functions may fail if:

EIO
A physical I/O error has occurred.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The pread() function shall fail, and the file pointer shall remain unchanged, if:

EINVAL
The offset argument is invalid. The value is negative.
EOVERFLOW
The file is a regular file and an attempt was made to read at or beyond the offset maximum associated with the file.
ENXIO
A request was outside the capabilities of the device.
ESPIPE
fildes is associated with a pipe or FIFO.

The following sections are informative.

EXAMPLES

Reading Data into a Buffer

The following example reads data from the file associated with the file descriptor fd into the buffer pointed to by buf.

#include <sys/types.h>
#include <unistd.h>
...
char buf[20];
size_t nbytes;
ssize_t bytes_read;
int fd;
...
nbytes = sizeof(buf);
bytes_read = read(fd, buf, nbytes);
...

APPLICATION USAGE

None.

RATIONALE

This volume of IEEE Std 1003.1-2001 does not specify the value of the file offset after an error is returned; there are too many cases. For programming errors, such as [EBADF], the concept is meaningless since no file is involved. For errors that are detected immediately, such as [EAGAIN], clearly the pointer should not change. After an interrupt or hardware error, however, an updated value would be very useful and is the behavior of many implementations.

Note that a read() of zero bytes does not modify st_atime. A read() that requests more than zero bytes, but returns zero, shall modify st_atime.

Implementations are allowed, but not required, to perform error checking for read() requests of zero bytes.

Input and Output

The use of I/O with large byte counts has always presented problems. Ideas such as lread() and lwrite() (using and returning longs) were considered at one time. The current solution is to use abstract types on the ISO C standard function to read() and write(). The abstract types can be declared so that existing functions work, but can also be declared so that larger types can be represented in future implementations. It is presumed that whatever constraints limit the maximum range of size_t also limit portable I/O requests to the same range. This volume of IEEE Std 1003.1-2001 also limits the range further by requiring that the byte count be limited so that a signed return value remains meaningful. Since the return type is also a (signed) abstract type, the byte count can be defined by the implementation to be larger than an int can hold.

The standard developers considered adding atomicity requirements to a pipe or FIFO, but recognized that due to the nature of pipes and FIFOs there could be no guarantee of atomicity of reads of {PIPE_BUF} or any other size that would be an aid to applications portability.

This volume of IEEE Std 1003.1-2001 requires that no action be taken for read() or write() when nbyte is zero. This is not intended to take precedence over detection of errors (such as invalid buffer pointers or file descriptors). This is consistent with the rest of this volume of IEEE Std 1003.1-2001, but the phrasing here could be misread to require detection of the zero case before any other errors. A value of zero is to be considered a correct value, for which the semantics are a no-op.

I/O is intended to be atomic to ordinary files and pipes and FIFOs. Atomic means that all the bytes from a single operation that started out together end up together, without interleaving from other I/O operations. It is a known attribute of terminals that this is not honored, and terminals are explicitly (and implicitly permanently) excepted, making the behavior unspecified. The behavior for other device types is also left unspecified, but the wording is intended to imply that future standards might choose to specify atomicity (or not).

There were recommendations to add format parameters to read() and write() in order to handle networked transfers among heterogeneous file system and base hardware types. Such a facility may be required for support by the OSI presentation of layer services. However, it was determined that this should correspond with similar C-language facilities, and that is beyond the scope of this volume of IEEE Std 1003.1-2001. The concept was suggested to the developers of the ISO C standard for their consideration as a possible area for future work.

In 4.3 BSD, a read() or write() that is interrupted by a signal before transferring any data does not by default return an [EINTR] error, but is restarted. In 4.2 BSD, 4.3 BSD, and the Eighth Edition, there is an additional function, select(), whose purpose is to pause until specified activity (data to read, space to write, and so on) is detected on specified file descriptors. It is common in applications written for those systems for select() to be used before read() in situations (such as keyboard input) where interruption of I/O due to a signal is desired.

The issue of which files or file types are interruptible is considered an implementation design issue. This is often affected primarily by hardware and reliability issues.

There are no references to actions taken following an "unrecoverable error". It is considered beyond the scope of this volume of IEEE Std 1003.1-2001 to describe what happens in the case of hardware errors.

Previous versions of IEEE Std 1003.1-2001 allowed two very different behaviors with regard to the handling of interrupts. In order to minimize the resulting confusion, it was decided that IEEE Std 1003.1-2001 should support only one of these behaviors. Historical practice on AT&T-derived systems was to have read() and write() return -1 and set errno to [EINTR] when interrupted after some, but not all, of the data requested had been transferred. However, the U.S. Department of Commerce FIPS 151-1 and FIPS 151-2 require the historical BSD behavior, in which read() and write() return the number of bytes actually transferred before the interrupt. If -1 is returned when any data is transferred, it is difficult to recover from the error on a seekable device and impossible on a non-seekable device. Most new implementations support this behavior. The behavior required by IEEE Std 1003.1-2001 is to return the number of bytes transferred.

IEEE Std 1003.1-2001 does not specify when an implementation that buffers read()ss actually moves the data into the user-supplied buffer, so an implementation may chose to do this at the latest possible moment. Therefore, an interrupt arriving earlier may not cause read() to return a partial byte count, but rather to return -1 and set errno to [EINTR].

Consideration was also given to combining the two previous options, and setting errno to [EINTR] while returning a short count. However, not only is there no existing practice that implements this, it is also contradictory to the idea that when errno is set, the function responsible shall return -1.

FUTURE DIRECTIONS

None.

SEE ALSO

fcntl() , ioctl() , lseek() , open() , pipe() , readv() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <stropts.h>, <sys/uio.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sem_getvalue(3p)

SEM_GETVALUE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_getvalue - get the value of a semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

int sem_getvalue(sem_t *restrict sem, int *restrict sval);

DESCRIPTION

The sem_getvalue() function shall update the location referenced by the sval argument to have the value of the semaphore referenced by sem without affecting the state of the semaphore. The updated value represents an actual semaphore value that occurred at some unspecified time during the call, but it need not be the actual value of the semaphore when it is returned to the calling process.

If sem is locked, then the object to which sval points shall either be set to zero or to a negative number whose absolute value represents the number of processes waiting for the semaphore at some unspecified time during the call.

RETURN VALUE

Upon successful completion, the sem_getvalue() function shall return a value of zero. Otherwise, it shall return a value of -1 and set errno to indicate the error.

ERRORS

The sem_getvalue() function shall fail if:

EINVAL
The sem argument does not refer to a valid semaphore.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sem_getvalue() function is part of the Semaphores option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

semctl() , semget() , semop() , sem_post() , sem_timedwait() , sem_trywait() , sem_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_setschedpolicy (3p)

 Continue to this page.


if_nameindex(3p)

IF_NAMEINDEX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

if_nameindex - return all network interface names and indexes

SYNOPSIS

#include <net/if.h>

struct if_nameindex *if_nameindex(void);

DESCRIPTION

The if_nameindex() function shall return an array of if_nameindex structures, one structure per interface. The end of the array is indicated by a structure with an if_index field of zero and an if_name field of NULL.

Applications should call if_freenameindex() to release the memory that may be dynamically allocated by this function, after they have finished using it.

RETURN VALUE

An array of structures identifying local interfaces. A NULL pointer is returned upon an error, with errno set to indicate the error.

ERRORS

The if_nameindex() function may fail if:

ENOBUFS
Insufficient resources are available to complete the function.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getsockopt() , if_freenameindex() , if_indextoname() , if_nametoindex() , setsockopt() , the Base Definitions volume of IEEE Std 1003.1-2001, <net/if.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


recv(3p)

RECV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

recv - receive a message from a connected socket

SYNOPSIS

#include <sys/socket.h>

ssize_t recv(int socket, void *buffer, size_t length, int flags);

DESCRIPTION

The recv() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connected sockets because it does not permit the application to retrieve the source address of received data.

The recv() function takes the following arguments:

socket
Specifies the socket file descriptor.
buffer
Points to a buffer where the message should be stored.
length
Specifies the length in bytes of the buffer pointed to by the buffer argument.
flags
Specifies the type of message reception. Values of this argument are formed by logically OR'ing zero or more of the following values:
MSG_PEEK
Peeks at an incoming message. The data is treated as unread and the next recv() or similar function shall still return this data.
MSG_OOB
Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific.
MSG_WAITALL
On SOCK_STREAM sockets this requests that the function block until the full amount of data can be returned. The function may return the smaller amount of data if the socket is a message-based socket, if a signal is caught, if the connection is terminated, if MSG_PEEK was specified, or if an error is pending for the socket.

The recv() function shall return the length of the message written to the buffer pointed to by the buffer argument. For message-based sockets, such as SOCK_DGRAM and SOCK_SEQPACKET, the entire message shall be read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument, the excess bytes shall be discarded. For stream-based sockets, such as SOCK_STREAM, message boundaries shall be ignored. In this case, data shall be returned to the user as soon as it becomes available, and no data shall be discarded.

If the MSG_WAITALL flag is not set, data shall be returned only up to the end of the first message.

If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, recv() shall block until a message arrives. If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, recv() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].

RETURN VALUE

Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The recv() function shall fail if:

EAGAIN or EWOULDBLOCK

The socket's file descriptor is marked O_NONBLOCK and no data is waiting to be received; or MSG_OOB is set and no out-of-band data is available and either the socket's file descriptor is marked O_NONBLOCK or the socket does not support blocking to await out-of-band data.

EBADF
The socket argument is not a valid file descriptor.
ECONNRESET
A connection was forcibly closed by a peer.
EINTR
The recv() function was interrupted by a signal that was caught, before any data was available.
EINVAL
The MSG_OOB flag is set and no out-of-band data is available.
ENOTCONN
A receive is attempted on a connection-mode socket that is not connected.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The specified flags are not supported for this socket type or protocol.
ETIMEDOUT
The connection timed out during connection establishment, or due to a transmission timeout on active connection.

The recv() function may fail if:

EIO
An I/O error occurred while reading from or writing to the file system.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The recv() function is equivalent to recvfrom() with a zero address_len argument, and to read() if no flags are used.

The select() and poll() functions can be used to determine when data is available to be received.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

poll() , read() , recvmsg() , recvfrom() , select() , send() , sendmsg() , sendto() , shutdown() , socket() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


csinhf (3p)

 Continue to this page.


csinhl (3p)

 Continue to this page.


endgrent (3p)

 Continue to this page.


pthread_attr_getscope(3p)

PTHREAD_ATTR_GETSCOPE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getscope, pthread_attr_setscope - get and set the contentionscope attribute (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_attr_getscope(const pthread_attr_t *restrict attr,
int *restrict contentionscope);
int pthread_attr_setscope(pthread_attr_t *attr, int contentionscope);

DESCRIPTION

The pthread_attr_getscope() and pthread_attr_setscope() functions, respectively, shall get and set the contentionscope attribute in the attr object.

The contentionscope attribute may have the values PTHREAD_SCOPE_SYSTEM, signifying system scheduling contention scope, or PTHREAD_SCOPE_PROCESS, signifying process scheduling contention scope. The symbols PTHREAD_SCOPE_SYSTEM and PTHREAD_SCOPE_PROCESS are defined in the <pthread.h> header.

RETURN VALUE

If successful, the pthread_attr_getscope() and pthread_attr_setscope() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_attr_setscope() function may fail if:

EINVAL
The value of contentionscope is not valid.
ENOTSUP
An attempt was made to set the attribute to an unsupported value.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

After these attributes have been set, a thread can be created with the specified attributes using pthread_create(). Using these routines does not affect the current running thread.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_attr_getinheritsched() , pthread_attr_getschedpolicy() , pthread_attr_getschedparam() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fabsf (3p)

 Continue to this page.


fabsl (3p)

 Continue to this page.


pthread_mutex_unlock (3p)

 Continue to this page.


seekdir(3p)

SEEKDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

seekdir - set the position of a directory stream

SYNOPSIS

#include <dirent.h>

void seekdir(DIR *dirp, long loc);

DESCRIPTION

The seekdir() function shall set the position of the next readdir() operation on the directory stream specified by dirp to the position specified by loc. The value of loc should have been returned from an earlier call to telldir(). The new position reverts to the one associated with the directory stream when telldir() was performed.

If the value of loc was not obtained from an earlier call to telldir(), or if a call to rewinddir() occurred between the call to telldir() and the call to seekdir(), the results of subsequent calls to readdir() are unspecified.

RETURN VALUE

The seekdir() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The original standard developers perceived that there were restrictions on the use of the seekdir() and telldir() functions related to implementation details, and for that reason these functions need not be supported on all POSIX-conforming systems. They are required on implementations supporting the XSI extension.

One of the perceived problems of implementation is that returning to a given point in a directory is quite difficult to describe formally, in spite of its intuitive appeal, when systems that use B-trees, hashing functions, or other similar mechanisms to order their directories are considered. The definition of seekdir() and telldir() does not specify whether, when using these interfaces, a given directory entry will be seen at all, or more than once.

On systems not supporting these functions, their capability can sometimes be accomplished by saving a filename found by readdir() and later using rewinddir() and a loop on readdir() to relocate the position from which the filename was saved.

FUTURE DIRECTIONS

None.

SEE ALSO

opendir() , readdir() , telldir() , the Base Definitions volume of IEEE Std 1003.1-2001, <dirent.h>, <stdio.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


csin(3p)

CSIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

csin, csinf, csinl - complex sine functions

SYNOPSIS

#include <complex.h>

double complex csin(double complex z);
float complex csinf(float complex z);
long double complex csinl(long double complex z);

DESCRIPTION

These functions shall compute the complex sine of z.

RETURN VALUE

These functions shall return the complex sine value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

casin() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


shmget(3p)

SHMGET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shmget - get an XSI shared memory segment

SYNOPSIS

#include <sys/shm.h>

int shmget(key_t key, size_t size, int shmflg);

DESCRIPTION

The shmget() function operates on XSI shared memory (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.340, Shared Memory Object). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The shmget() function shall return the shared memory identifier associated with key.

A shared memory identifier, associated data structure, and shared memory segment of at least size bytes (see <sys/shm.h>) are created for key if one of the following is true:

*
The argument key is equal to IPC_PRIVATE.

*
The argument key does not already have a shared memory identifier associated with it and (shmflg &IPC_CREAT) is non-zero.

Upon creation, the data structure associated with the new shared memory identifier shall be initialized as follows:

*
The values of shm_perm.cuid, shm_perm.uid, shm_perm.cgid, and shm_perm.gid are set equal to the effective user ID and effective group ID, respectively, of the calling process.

*
The low-order nine bits of shm_perm.mode are set equal to the low-order nine bits of shmflg.

*
The value of shm_segsz is set equal to the value of size.

*
The values of shm_lpid, shm_nattch, shm_atime, and shm_dtime are set equal to 0.

*
The value of shm_ctime is set equal to the current time.

When the shared memory segment is created, it shall be initialized with all zero values.

RETURN VALUE

Upon successful completion, shmget() shall return a non-negative integer, namely a shared memory identifier; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The shmget() function shall fail if:

EACCES
A shared memory identifier exists for key but operation permission as specified by the low-order nine bits of shmflg would not be granted; see XSI Interprocess Communication .
EEXIST
A shared memory identifier exists for the argument key but (shmflg &IPC_CREAT) &&(shmflg &IPC_EXCL) is non-zero.
EINVAL
A shared memory segment is to be created and the value of size is less than the system-imposed minimum or greater than the system-imposed maximum.
EINVAL
No shared memory segment is to be created and a shared memory segment exists for key but the size of the segment associated with it is less than size and size is not 0.
ENOENT
A shared memory identifier does not exist for the argument key and (shmflg &IPC_CREAT) is 0.
ENOMEM
A shared memory identifier and associated shared memory segment shall be created, but the amount of available physical memory is not sufficient to fill the request.
ENOSPC
A shared memory identifier is to be created, but the system-imposed limit on the maximum number of allowed shared memory identifiers system-wide would be exceeded.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , shmat() , shmctl() , shmdt() , shm_open() , shm_unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/shm.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


shmat(3p)

SHMAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shmat - XSI shared memory attach operation

SYNOPSIS

#include <sys/shm.h>

void *shmat(int shmid, const void *shmaddr, int shmflg);

DESCRIPTION

The shmat() function operates on XSI shared memory (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.340, Shared Memory Object). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The shmat() function attaches the shared memory segment associated with the shared memory identifier specified by shmid to the address space of the calling process. The segment is attached at the address specified by one of the following criteria:

*
If shmaddr is a null pointer, the segment is attached at the first available address as selected by the system.

*
If shmaddr is not a null pointer and (shmflg &SHM_RND) is non-zero, the segment is attached at the address given by (shmaddr -((uintptr_t)shmaddr %SHMLBA)). The character '%' is the C-language remainder operator.

*
If shmaddr is not a null pointer and (shmflg &SHM_RND) is 0, the segment is attached at the address given by shmaddr.

*
The segment is attached for reading if (shmflg &SHM_RDONLY) is non-zero and the calling process has read permission; otherwise, if it is 0 and the calling process has read and write permission, the segment is attached for reading and writing.

RETURN VALUE

Upon successful completion, shmat() shall increment the value of shm_nattch in the data structure associated with the shared memory ID of the attached shared memory segment and return the segment's start address.

Otherwise, the shared memory segment shall not be attached, shmat() shall return -1, and errno shall be set to indicate the error.

ERRORS

The shmat() function shall fail if:

EACCES
Operation permission is denied to the calling process; see XSI Interprocess Communication .
EINVAL
The value of shmid is not a valid shared memory identifier, the shmaddr is not a null pointer, and the value of (shmaddr -((uintptr_t)shmaddr %SHMLBA)) is an illegal address for attaching shared memory; or the shmaddr is not a null pointer, (shmflg &SHM_RND) is 0, and the value of shmaddr is an illegal address for attaching shared memory.
EMFILE
The number of shared memory segments attached to the calling process would exceed the system-imposed limit.
ENOMEM
The available data space is not large enough to accommodate the shared memory segment.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , exec() , exit() , fork() , shmctl() , shmdt() , shmget() , shm_open() , shm_unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/shm.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_getstacksize(3p)

PTHREAD_ATTR_GETSTACKSIZE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getstacksize, pthread_attr_setstacksize - get and set the stacksize attribute

SYNOPSIS

#include <pthread.h>

int pthread_attr_getstacksize(const pthread_attr_t *restrict attr,
size_t *restrict stacksize);
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);

DESCRIPTION

The pthread_attr_getstacksize() and pthread_attr_setstacksize() functions, respectively, shall get and set the thread creation stacksize attribute in the attr object.

The stacksize attribute shall define the minimum stack size (in bytes) allocated for the created threads stack.

RETURN VALUE

Upon successful completion, pthread_attr_getstacksize() and pthread_attr_setstacksize() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.

The pthread_attr_getstacksize() function stores the stacksize attribute value in stacksize if successful.

ERRORS

The pthread_attr_setstacksize() function shall fail if:

EINVAL
The value of stacksize is less than {PTHREAD_STACK_MIN} or exceeds a system-imposed limit.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_attr_getstackaddr() , pthread_attr_getdetachstate() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctan(3p)

CTAN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ctan, ctanf, ctanl - complex tangent functions

SYNOPSIS

#include <complex.h>

double complex ctan(double complex z);
float complex ctanf(float complex z);
long double complex ctanl(long double complex z);

DESCRIPTION

These functions shall compute the complex tangent of z.

RETURN VALUE

These functions shall return the complex tangent value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

catan() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isastream(3p)

ISASTREAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isastream - test a file descriptor (STREAMS)

SYNOPSIS

#include <stropts.h>

int isastream(int fildes);

DESCRIPTION

The isastream() function shall test whether fildes, an open file descriptor, is associated with a STREAMS-based file.

RETURN VALUE

Upon successful completion, isastream() shall return 1 if fildes refers to a STREAMS-based file and 0 if not. Otherwise, isastream() shall return -1 and set errno to indicate the error.

ERRORS

The isastream() function shall fail if:

EBADF
The fildes argument is not a valid open file descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fseeko (3p)

 Continue to this page.


getaddrinfo(3p)

FREEADDRINFO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

freeaddrinfo, getaddrinfo - get address information

SYNOPSIS

#include <sys/socket.h>
#include <netdb.h>

void freeaddrinfo(struct addrinfo *ai);
int getaddrinfo(const char *restrict nodename,
const char *restrict servname,
const struct addrinfo *restrict hints,
struct addrinfo **restrict res);

DESCRIPTION

The freeaddrinfo() function shall free one or more addrinfo structures returned by getaddrinfo(), along with any additional storage associated with those structures. If the ai_next field of the structure is not null, the entire list of structures shall be freed. The freeaddrinfo() function shall support the freeing of arbitrary sublists of an addrinfo list originally returned by getaddrinfo().

The getaddrinfo() function shall translate the name of a service location (for example, a host name) and/or a service name and shall return a set of socket addresses and associated information to be used in creating a socket with which to address the specified service.

Note:
In many cases it is implemented by the Domain Name System, as documented in RFC 1034, RFC 1035, and RFC 1886.

The freeaddrinfo() and getaddrinfo() functions shall be thread-safe.

The nodename and servname arguments are either null pointers or pointers to null-terminated strings. One or both of these two arguments shall be supplied by the application as a non-null pointer.

The format of a valid name depends on the address family or families. If a specific family is not given and the name could be interpreted as valid within multiple supported families, the implementation shall attempt to resolve the name in all supported families and, in absence of errors, one or more results shall be returned.

If the nodename argument is not null, it can be a descriptive name or can be an address string. If the specified address family is AF_INET, AF_INET6, or AF_UNSPEC, valid descriptive names include host names. If the specified address family is AF_INET or AF_UNSPEC, address strings using Internet standard dot notation as specified in inet_addr() are valid.

If the specified address family is AF_INET6 or AF_UNSPEC, standard IPv6 text forms described in inet_ntop() are valid.

If nodename is not null, the requested service location is named by nodename; otherwise, the requested service location is local to the caller.

If servname is null, the call shall return network-level addresses for the specified nodename. If servname is not null, it is a null-terminated character string identifying the requested service. This can be either a descriptive name or a numeric representation suitable for use with the address family or families. If the specified address family is AF_INET, AF_INET6, or AF_UNSPEC, the service can be specified as a string specifying a decimal port number.

If the hints argument is not null, it refers to a structure containing input values that may direct the operation by providing options and by limiting the returned information to a specific socket type, address family, and/or protocol. In this hints structure every member other than ai_flags, ai_family, ai_socktype, and ai_protocol shall be set to zero or a null pointer. A value of AF_UNSPEC for ai_family means that the caller shall accept any address family. A value of zero for ai_socktype means that the caller shall accept any socket type. A value of zero for ai_protocol means that the caller shall accept any protocol. If hints is a null pointer, the behavior shall be as if it referred to a structure containing the value zero for the ai_flags, ai_socktype, and ai_protocol fields, and AF_UNSPEC for the ai_family field.

The ai_flags field to which the hints parameter points shall be set to zero or be the bitwise-inclusive OR of one or more of the values AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST, AI_NUMERICSERV, AI_V4MAPPED, AI_ALL, and AI_ADDRCONFIG.

If the AI_PASSIVE flag is specified, the returned address information shall be suitable for use in binding a socket for accepting incoming connections for the specified service. In this case, if the nodename argument is null, then the IP address portion of the socket address structure shall be set to INADDR_ANY for an IPv4 address or IN6ADDR_ANY_INIT for an IPv6 address. If the AI_PASSIVE flag is not specified, the returned address information shall be suitable for a call to connect() (for a connection-mode protocol) or for a call to connect(), sendto(), or sendmsg() (for a connectionless protocol). In this case, if the nodename argument is null, then the IP address portion of the socket address structure shall be set to the loopback address. The AI_PASSIVE flag shall be ignored if the nodename argument is not null.

If the AI_CANONNAME flag is specified and the nodename argument is not null, the function shall attempt to determine the canonical name corresponding to nodename (for example, if nodename is an alias or shorthand notation for a complete name).

Note:
Since different implementations use different conceptual models, the terms ``canonical name'' and ``alias'' cannot be precisely defined for the general case. However, Domain Name System implementations are expected to interpret them as they are used in RFC 1034.

A numeric host address string is not a ``name'', and thus does not have a ``canonical name'' form; no address to host name translation is performed. See below for handling of the case where a canonical name cannot be obtained.

If the AI_NUMERICHOST flag is specified, then a non-null nodename string supplied shall be a numeric host address string. Otherwise, an [EAI_NONAME] error is returned. This flag shall prevent any type of name resolution service (for example, the DNS) from being invoked.

If the AI_NUMERICSERV flag is specified, then a non-null servname string supplied shall be a numeric port string. Otherwise, an [EAI_NONAME] error shall be returned. This flag shall prevent any type of name resolution service (for example, NIS+) from being invoked.

If the AI_V4MAPPED flag is specified along with an ai_family of AF_INET6, then getaddrinfo() shall return IPv4-mapped IPv6 addresses on finding no matching IPv6 addresses ( ai_addrlen shall be 16). The AI_V4MAPPED flag shall be ignored unless ai_family equals AF_INET6. If the AI_ALL flag is used with the AI_V4MAPPED flag, then getaddrinfo() shall return all matching IPv6 and IPv4 addresses. The AI_ALL flag without the AI_V4MAPPED flag is ignored.

If the AI_ADDRCONFIG flag is specified, IPv4 addresses shall be returned only if an IPv4 address is configured on the local system, and IPv6 addresses shall be returned only if an IPv6 address is configured on the local system.

The ai_socktype field to which argument hints points specifies the socket type for the service, as defined in socket() . If a specific socket type is not given (for example, a value of zero) and the service name could be interpreted as valid with multiple supported socket types, the implementation shall attempt to resolve the service name for all supported socket types and, in the absence of errors, all possible results shall be returned. A non-zero socket type value shall limit the returned information to values with the specified socket type.

If the ai_family field to which hints points has the value AF_UNSPEC, addresses shall be returned for use with any address family that can be used with the specified nodename and/or servname. Otherwise, addresses shall be returned for use only with the specified address family. If ai_family is not AF_UNSPEC and ai_protocol is not zero, then addresses are returned for use only with the specified address family and protocol; the value of ai_protocol shall be interpreted as in a call to the socket() function with the corresponding values of ai_family and ai_protocol.

RETURN VALUE

A zero return value for getaddrinfo() indicates successful completion; a non-zero return value indicates failure. The possible values for the failures are listed in the ERRORS section.

Upon successful return of getaddrinfo(), the location to which res points shall refer to a linked list of addrinfo structures, each of which shall specify a socket address and information for use in creating a socket with which to use that socket address. The list shall include at least one addrinfo structure. The ai_next field of each structure contains a pointer to the next structure on the list, or a null pointer if it is the last structure on the list. Each structure on the list shall include values for use with a call to the socket() function, and a socket address for use with the connect() function or, if the AI_PASSIVE flag was specified, for use with the bind() function. The fields ai_family, ai_socktype, and ai_protocol shall be usable as the arguments to the socket() function to create a socket suitable for use with the returned address. The fields ai_addr and ai_addrlen are usable as the arguments to the connect() or bind() functions with such a socket, according to the AI_PASSIVE flag.

If nodename is not null, and if requested by the AI_CANONNAME flag, the ai_canonname field of the first returned addrinfo structure shall point to a null-terminated string containing the canonical name corresponding to the input nodename; if the canonical name is not available, then ai_canonname shall refer to the nodename argument or a string with the same contents. The contents of the ai_flags field of the returned structures are undefined.

All fields in socket address structures returned by getaddrinfo() that are not filled in through an explicit argument (for example, sin6_flowinfo) shall be set to zero.

Note:
This makes it easier to compare socket address structures.

ERRORS

The getaddrinfo() function shall fail and return the corresponding value if:

EAI_AGAIN
The name could not be resolved at this time. Future attempts may succeed.
EAI_BADFLAGS

The flags parameter had an invalid value.

EAI_FAIL
A non-recoverable error occurred when attempting to resolve the name.
EAI_FAMILY
The address family was not recognized.
EAI_MEMORY
There was a memory allocation failure when trying to allocate storage for the return value.
EAI_NONAME
The name does not resolve for the supplied parameters.

Neither nodename nor servname were supplied. At least one of these shall be supplied.

EAI_SERVICE
The service passed was not recognized for the specified socket type.
EAI_SOCKTYPE

The intended socket type was not recognized.

EAI_SYSTEM
A system error occurred; the error code can be found in errno.
EAI_OVERFLOW

An argument buffer overflowed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the caller handles only TCP and not UDP, for example, then the ai_protocol member of the hints structure should be set to IPPROTO_TCP when getaddrinfo() is called.

If the caller handles only IPv4 and not IPv6, then the ai_family member of the hints structure should be set to AF_INET when getaddrinfo() is called.

The term ``canonical name'' is misleading; it is taken from the Domain Name System (RFC 2181). It should be noted that the canonical name is a result of alias processing, and not necessarily a unique attribute of a host, address, or set of addresses. See RFC 2181 for more discussion of this in the Domain Name System context.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

connect() , gai_strerror() , gethostbyaddr() , getnameinfo() , getservbyname() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


shmdt(3p)

SHMDT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shmdt - XSI shared memory detach operation

SYNOPSIS

#include <sys/shm.h>

int shmdt(const void *shmaddr);

DESCRIPTION

The shmdt() function operates on XSI shared memory (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.340, Shared Memory Object). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The shmdt() function detaches the shared memory segment located at the address specified by shmaddr from the address space of the calling process.

RETURN VALUE

Upon successful completion, shmdt() shall decrement the value of shm_nattch in the data structure associated with the shared memory ID of the attached shared memory segment and return 0.

Otherwise, the shared memory segment shall not be detached, shmdt() shall return -1, and errno shall be set to indicate the error.

ERRORS

The shmdt() function shall fail if:

EINVAL
The value of shmaddr is not the data segment start address of a shared memory segment.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , exec() , exit() , fork() , shmat() , shmctl() , shmget() , shm_open() , shm_unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/shm.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atexit(3p)

ATEXIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

atexit - register a function to run at process termination

SYNOPSIS

#include <stdlib.h>

int atexit(void (*func)(void));

DESCRIPTION

The atexit() function shall register the function pointed to by func, to be called without arguments at normal program termination. At normal program termination, all functions registered by the atexit() function shall be called, in the reverse order of their registration, except that a function is called after any previously registered functions that had already been called at the time it was registered. Normal termination occurs either by a call to exit() or a return from main().

At least 32 functions can be registered with atexit().

After a successful call to any of the exec functions, any functions previously registered by atexit() shall no longer be registered.

RETURN VALUE

Upon successful completion, atexit() shall return 0; otherwise, it shall return a non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The functions registered by a call to atexit() must return to ensure that all registered functions are called.

The application should call sysconf() to obtain the value of {ATEXIT_MAX}, the number of functions that can be registered. There is no way for an application to tell how many functions have already been registered with atexit().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exit() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


hcreate(3p)

HCREATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

hcreate, hdestroy, hsearch - manage hash search table

SYNOPSIS

#include <search.h>

int hcreate(size_t nel);
void hdestroy(void);
ENTRY *hsearch(ENTRY item, ACTION action);

DESCRIPTION

The hcreate(), hdestroy(), and hsearch() functions shall manage hash search tables.

The hcreate() function shall allocate sufficient space for the table, and the application shall ensure it is called before hsearch() is used. The nel argument is an estimate of the maximum number of entries that the table shall contain. This number may be adjusted upward by the algorithm in order to obtain certain mathematically favorable circumstances.

The hdestroy() function shall dispose of the search table, and may be followed by another call to hcreate(). After the call to hdestroy(), the data can no longer be considered accessible.

The hsearch() function is a hash-table search routine. It shall return a pointer into a hash table indicating the location at which an entry can be found. The item argument is a structure of type ENTRY (defined in the <search.h> header) containing two pointers: item.key points to the comparison key (a char *), and item.data (a void *) points to any other data to be associated with that key. The comparison function used by hsearch() is strcmp(). The action argument is a member of an enumeration type ACTION indicating the disposition of the entry if it cannot be found in the table. ENTER indicates that the item should be inserted in the table at an appropriate point. FIND indicates that no entry should be made. Unsuccessful resolution is indicated by the return of a null pointer.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The hcreate() function shall return 0 if it cannot allocate sufficient space for the table; otherwise, it shall return non-zero.

The hdestroy() function shall not return a value.

The hsearch() function shall return a null pointer if either the action is FIND and the item could not be found or the action is ENTER and the table is full.

ERRORS

The hcreate() and hsearch() functions may fail if:

ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

The following example reads in strings followed by two numbers and stores them in a hash table, discarding duplicates. It then reads in strings and finds the matching entry in the hash table and prints it out.

#include <stdio.h>
#include <search.h>
#include <string.h>

struct info {        /* This is the info stored in the table */
    int age, room;   /* other than the key. */
};

#define NUM_EMPL    5000    /* # of elements in search table. */

int main(void)
{
    char string_space[NUM_EMPL*20];   /* Space to store strings. */
    struct info info_space[NUM_EMPL]; /* Space to store employee info. */
    char *str_ptr = string_space;     /* Next space in string_space. */
    struct info *info_ptr = info_space;
                                      /* Next space in info_space. */
    ENTRY item;
    ENTRY *found_item; /* Name to look for in table. */
    char name_to_find[30];

    int i = 0;

    /* Create table; no error checking is performed. */
    (void) hcreate(NUM_EMPL);
    while (scanf("%s%d%d", str_ptr, &info_ptr->age,
           &info_ptr->room) != EOF && i++ < NUM_EMPL) {

        /* Put information in structure, and structure in item. */
        item.key = str_ptr;
        item.data = info_ptr;
        str_ptr += strlen(str_ptr) + 1;
        info_ptr++;

        /* Put item into table. */
        (void) hsearch(item, ENTER);
    }

    /* Access table. */
    item.key = name_to_find;
    while (scanf("%s", item.key) != EOF) {
        if ((found_item = hsearch(item, FIND)) != NULL) {

            /* If item is in the table. */
            (void)printf("found %s, age = %d, room = %d\n",
                found_item->key,
                ((struct info *)found_item->data)->age,
                ((struct info *)found_item->data)->room);
        } else
            (void)printf("no such employee %s\n", name_to_find);
    }
    return 0;
}

APPLICATION USAGE

The hcreate() and hsearch() functions may use malloc() to allocate space.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

bsearch() , lsearch() , malloc() , strcmp() , tsearch() , the Base Definitions volume of IEEE Std 1003.1-2001, <search.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_atfork(3p)

PTHREAD_ATFORK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_atfork - register fork handlers

SYNOPSIS

#include <pthread.h>

int pthread_atfork(void (*prepare)(void), void (*parent)(void),
void (*child)(void));

DESCRIPTION

The pthread_atfork() function shall declare fork handlers to be called before and after fork(), in the context of the thread that called fork(). The prepare fork handler shall be called before fork() processing commences. The parent fork handle shall be called after fork() processing completes in the parent process. The child fork handler shall be called after fork() processing completes in the child process. If no handling is desired at one or more of these three points, the corresponding fork handler address(es) may be set to NULL.

The order of calls to pthread_atfork() is significant. The parent and child fork handlers shall be called in the order in which they were established by calls to pthread_atfork(). The prepare fork handlers shall be called in the opposite order.

RETURN VALUE

Upon successful completion, pthread_atfork() shall return a value of zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_atfork() function shall fail if:

ENOMEM
Insufficient table space exists to record the fork handler addresses.

The pthread_atfork() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

There are at least two serious problems with the semantics of fork() in a multi-threaded program. One problem has to do with state (for example, memory) covered by mutexes. Consider the case where one thread has a mutex locked and the state covered by that mutex is inconsistent while another thread calls fork(). In the child, the mutex is in the locked state (locked by a nonexistent thread and thus can never be unlocked). Having the child simply reinitialize the mutex is unsatisfactory since this approach does not resolve the question about how to correct or otherwise deal with the inconsistent state in the child.

It is suggested that programs that use fork() call an exec function very soon afterwards in the child process, thus resetting all states. In the meantime, only a short list of async-signal-safe library routines are promised to be available.

Unfortunately, this solution does not address the needs of multi-threaded libraries. Application programs may not be aware that a multi-threaded library is in use, and they feel free to call any number of library routines between the fork() and exec calls, just as they always have. Indeed, they may be extant single-threaded programs and cannot, therefore, be expected to obey new restrictions imposed by the threads library.

On the other hand, the multi-threaded library needs a way to protect its internal state during fork() in case it is re-entered later in the child process. The problem arises especially in multi-threaded I/O libraries, which are almost sure to be invoked between the fork() and exec calls to effect I/O redirection. The solution may require locking mutex variables during fork(), or it may entail simply resetting the state in the child after the fork() processing completes.

The pthread_atfork() function provides multi-threaded libraries with a means to protect themselves from innocent application programs that call fork(), and it provides multi-threaded application programs with a standard mechanism for protecting themselves from fork() calls in a library routine or the application itself.

The expected usage is that the prepare handler acquires all mutex locks and the other two fork handlers release them.

For example, an application can supply a prepare routine that acquires the necessary mutexes the library maintains and supply child and parent routines that release those mutexes, thus ensuring that the child gets a consistent snapshot of the state of the library (and that no mutexes are left stranded). Alternatively, some libraries might be able to supply just a child routine that reinitializes the mutexes in the library and all associated states to some known value (for example, what it was when the image was originally executed).

When fork() is called, only the calling thread is duplicated in the child process. Synchronization variables remain in the same state in the child as they were in the parent at the time fork() was called. Thus, for example, mutex locks may be held by threads that no longer exist in the child process, and any associated states may be inconsistent. The parent process may avoid this by explicit code that acquires and releases locks critical to the child via pthread_atfork(). In addition, any critical threads need to be recreated and reinitialized to the proper state in the child (also via pthread_atfork()).

A higher-level package may acquire locks on its own data structures before invoking lower-level packages. Under this scenario, the order specified for fork handler calls allows a simple rule of initialization for avoiding package deadlock: a package initializes all packages on which it depends before it calls the pthread_atfork() function for itself.

FUTURE DIRECTIONS

None.

SEE ALSO

atexit() , fork() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigsuspend(3p)

SIGSUSPEND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigsuspend - wait for a signal

SYNOPSIS

#include <signal.h>

int sigsuspend(const sigset_t *sigmask);

DESCRIPTION

The sigsuspend() function shall replace the current signal mask of the calling thread with the set of signals pointed to by sigmask and then suspend the thread until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process. This shall not cause any other signals that may have been pending on the process to become pending on the thread.

If the action is to terminate the process then sigsuspend() shall never return. If the action is to execute a signal-catching function, then sigsuspend() shall return after the signal-catching function returns, with the signal mask restored to the set that existed prior to the sigsuspend() call.

It is not possible to block signals that cannot be ignored. This is enforced by the system without causing an error to be indicated.

RETURN VALUE

Since sigsuspend() suspends thread execution indefinitely, there is no successful completion return value. If a return occurs, -1 shall be returned and errno set to indicate the error.

ERRORS

The sigsuspend() function shall fail if:

EINTR
A signal is caught by the calling process and control is returned from the signal-catching function.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Normally, at the beginning of a critical code section, a specified set of signals is blocked using the sigprocmask() function. When the thread has completed the critical section and needs to wait for the previously blocked signal(s), it pauses by calling sigsuspend() with the mask that was returned by the sigprocmask() call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , pause() , sigaction() , sigaddset() , sigdelset() , sigemptyset() , sigfillset() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


clearerr(3p)

CLEARERR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

clearerr - clear indicators on a stream

SYNOPSIS

#include <stdio.h>

void clearerr(FILE *stream);

DESCRIPTION

The clearerr() function shall clear the end-of-file and error indicators for the stream to which stream points.

RETURN VALUE

The clearerr() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


clock_nanosleep(3p)

CLOCK_NANOSLEEP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

clock_nanosleep - high resolution sleep with specifiable clock (ADVANCED REALTIME)

SYNOPSIS

#include <time.h>

int clock_nanosleep(clockid_t clock_id, int flags,
const struct timespec *rqtp, struct timespec *rmtp);

DESCRIPTION

If the flag TIMER_ABSTIME is not set in the flags argument, the clock_nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed, or a signal is delivered to the calling thread and its action is to invoke a signal-catching function, or the process is terminated. The clock used to measure the time shall be the clock specified by clock_id.

If the flag TIMER_ABSTIME is set in the flags argument, the clock_nanosleep() function shall cause the current thread to be suspended from execution until either the time value of the clock specified by clock_id reaches the absolute time specified by the rqtp argument, or a signal is delivered to the calling thread and its action is to invoke a signal-catching function, or the process is terminated. If, at the time of the call, the time value specified by rqtp is less than or equal to the time value of the specified clock, then clock_nanosleep() shall return immediately and the calling process shall not be suspended.

The suspension time caused by this function may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution, or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time for the relative clock_nanosleep() function (that is, with the TIMER_ABSTIME flag not set) shall not be less than the time interval specified by rqtp, as measured by the corresponding clock. The suspension for the absolute clock_nanosleep() function (that is, with the TIMER_ABSTIME flag set) shall be in effect at least until the value of the corresponding clock reaches the absolute time specified by rqtp, except for the case of being interrupted by a signal.

The use of the clock_nanosleep() function shall have no effect on the action or blockage of any signal.

The clock_nanosleep() function shall fail if the clock_id argument refers to the CPU-time clock of the calling thread. It is unspecified whether clock_id values of other CPU-time clocks are allowed.

RETURN VALUE

If the clock_nanosleep() function returns because the requested time has elapsed, its return value shall be zero.

If the clock_nanosleep() function returns because it has been interrupted by a signal, it shall return the corresponding error value. For the relative clock_nanosleep() function, if the rmtp argument is non-NULL, the timespec structure referenced by it shall be updated to contain the amount of time remaining in the interval (the requested time minus the time actually slept). If the rmtp argument is NULL, the remaining time is not returned. The absolute clock_nanosleep() function has no effect on the structure referenced by rmtp.

If clock_nanosleep() fails, it shall return the corresponding error value.

ERRORS

The clock_nanosleep() function shall fail if:

EINTR
The clock_nanosleep() function was interrupted by a signal.
EINVAL
The rqtp argument specified a nanosecond value less than zero or greater than or equal to 1000 million; or the TIMER_ABSTIME flag was specified in flags and the rqtp argument is outside the range for the clock specified by clock_id; or the clock_id argument does not specify a known clock, or specifies the CPU-time clock of the calling thread.
ENOTSUP
The clock_id argument specifies a clock for which clock_nanosleep() is not supported, such as a CPU-time clock.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Calling clock_nanosleep() with the value TIMER_ABSTIME not set in the flags argument and with a clock_id of CLOCK_REALTIME is equivalent to calling nanosleep() with the same rqtp and rmtp arguments.

RATIONALE

The nanosleep() function specifies that the system-wide clock CLOCK_REALTIME is used to measure the elapsed time for this time service. However, with the introduction of the monotonic clock CLOCK_MONOTONIC a new relative sleep function is needed to allow an application to take advantage of the special characteristics of this clock.

There are many applications in which a process needs to be suspended and then activated multiple times in a periodic way; for example, to poll the status of a non-interrupting device or to refresh a display device. For these cases, it is known that precise periodic activation cannot be achieved with a relative sleep() or nanosleep() function call. Suppose, for example, a periodic process that is activated at time T0, executes for a while, and then wants to suspend itself until time T0+ T, the period being T. If this process wants to use the nanosleep() function, it must first call clock_gettime() to get the current time, then calculate the difference between the current time and T0+ T and, finally, call nanosleep() using the computed interval. However, the process could be preempted by a different process between the two function calls, and in this case the interval computed would be wrong; the process would wake up later than desired. This problem would not occur with the absolute clock_nanosleep() function, since only one function call would be necessary to suspend the process until the desired time. In other cases, however, a relative sleep is needed, and that is why both functionalities are required.

Although it is possible to implement periodic processes using the timers interface, this implementation would require the use of signals, and the reservation of some signal numbers. In this regard, the reasons for including an absolute version of the clock_nanosleep() function in IEEE Std 1003.1-2001 are the same as for the inclusion of the relative nanosleep().

It is also possible to implement precise periodic processes using pthread_cond_timedwait(), in which an absolute timeout is specified that takes effect if the condition variable involved is never signaled. However, the use of this interface is unnatural, and involves performing other operations on mutexes and condition variables that imply an unnecessary overhead. Furthermore, pthread_cond_timedwait() is not available in implementations that do not support threads.

Although the interface of the relative and absolute versions of the new high resolution sleep service is the same clock_nanosleep() function, the rmtp argument is only used in the relative sleep. This argument is needed in the relative clock_nanosleep() function to reissue the function call if it is interrupted by a signal, but it is not needed in the absolute clock_nanosleep() function call; if the call is interrupted by a signal, the absolute clock_nanosleep() function can be invoked again with the same rqtp argument used in the interrupted call.

FUTURE DIRECTIONS

None.

SEE ALSO

clock_getres() , nanosleep() , pthread_cond_timedwait() , sleep() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigaddset(3p)

SIGADDSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigaddset - add a signal to a signal set

SYNOPSIS

#include <signal.h>

int sigaddset(sigset_t *set, int signo);

DESCRIPTION

The sigaddset() function adds the individual signal specified by the signo to the signal set pointed to by set.

Applications shall call either sigemptyset() or sigfillset() at least once for each object of type sigset_t prior to any other use of that object. If such an object is not initialized in this way, but is nonetheless supplied as an argument to any of pthread_sigmask(), sigaction(), sigaddset(), sigdelset(), sigismember(), sigpending(), sigprocmask(), sigsuspend(), sigtimedwait(), sigwait(), or sigwaitinfo(), the results are undefined.

RETURN VALUE

Upon successful completion, sigaddset() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The sigaddset() function may fail if:

EINVAL
The value of the signo argument is an invalid or unsupported signal number.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , sigaction() , sigdelset() , sigemptyset() , sigfillset() , sigismember() , sigpending() , sigprocmask() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventtypelist_rewind (3p)

 Continue to this page.


pthread_getschedparam(3p)

PTHREAD_GETSCHEDPARAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_getschedparam, pthread_setschedparam - dynamic thread scheduling parameters access (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_getschedparam(pthread_t thread, int *restrict policy,
struct sched_param *restrict param);
int pthread_setschedparam(pthread_t thread, int policy,
const struct sched_param *param);

DESCRIPTION

The pthread_getschedparam() and pthread_setschedparam() functions shall, respectively, get and set the scheduling policy and parameters of individual threads within a multi-threaded process to be retrieved and set. For SCHED_FIFO and SCHED_RR, the only required member of the sched_param structure is the priority sched_priority. For SCHED_OTHER, the affected scheduling parameters are implementation-defined.

The pthread_getschedparam() function shall retrieve the scheduling policy and scheduling parameters for the thread whose thread ID is given by thread and shall store those values in policy and param, respectively. The priority value returned from pthread_getschedparam() shall be the value specified by the most recent pthread_setschedparam(), pthread_setschedprio(), or pthread_create() call affecting the target thread. It shall not reflect any temporary adjustments to its priority as a result of any priority inheritance or ceiling functions. The pthread_setschedparam() function shall set the scheduling policy and associated scheduling parameters for the thread whose thread ID is given by thread to the policy and associated parameters provided in policy and param, respectively.

The policy parameter may have the value SCHED_OTHER, SCHED_FIFO, or SCHED_RR. The scheduling parameters for the SCHED_OTHER policy are implementation-defined. The SCHED_FIFO and SCHED_RR policies shall have a single scheduling parameter, priority.

If _POSIX_THREAD_SPORADIC_SERVER is defined, then the policy argument may have the value SCHED_SPORADIC, with the exception for the pthread_setschedparam() function that if the scheduling policy was not SCHED_SPORADIC at the time of the call, it is implementation-defined whether the function is supported; in other words, the implementation need not allow the application to dynamically change the scheduling policy to SCHED_SPORADIC. The sporadic server scheduling policy has the associated parameters sched_ss_low_priority, sched_ss_repl_period, sched_ss_init_budget, sched_priority, and sched_ss_max_repl. The specified sched_ss_repl_period shall be greater than or equal to the specified sched_ss_init_budget for the function to succeed; if it is not, then the function shall fail. The value of sched_ss_max_repl shall be within the inclusive range [1, {SS_REPL_MAX}] for the function to succeed; if not, the function shall fail.

If the pthread_setschedparam() function fails, the scheduling parameters shall not be changed for the target thread.

RETURN VALUE

If successful, the pthread_getschedparam() and pthread_setschedparam() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_getschedparam() function may fail if:

ESRCH
The value specified by thread does not refer to an existing thread.

The pthread_setschedparam() function may fail if:

EINVAL
The value specified by policy or one of the scheduling parameters associated with the scheduling policy policy is invalid.
ENOTSUP
An attempt was made to set the policy or scheduling parameters to an unsupported value.
ENOTSUP
An attempt was made to dynamically change the scheduling policy to SCHED_SPORADIC, and the implementation does not support this change.
EPERM
The caller does not have the appropriate permission to set either the scheduling parameters or the scheduling policy of the specified thread.
EPERM
The implementation does not allow the application to modify one of the parameters to the value specified.
ESRCH
The value specified by thread does not refer to a existing thread.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_setschedprio() , sched_getparam() , sched_getscheduler() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


hdestroy (3p)

 Continue to this page.


rmdir(3p)

RMDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rmdir - remove a directory

SYNOPSIS

#include <unistd.h>

int rmdir(const char *path);

DESCRIPTION

The rmdir() function shall remove a directory whose name is given by path. The directory shall be removed only if it is an empty directory.

If the directory is the root directory or the current working directory of any process, it is unspecified whether the function succeeds, or whether it shall fail and set errno to [EBUSY].

If path names a symbolic link, then rmdir() shall fail and set errno to [ENOTDIR].

If the path argument refers to a path whose final component is either dot or dot-dot, rmdir() shall fail.

If the directory's link count becomes 0 and no process has the directory open, the space occupied by the directory shall be freed and the directory shall no longer be accessible. If one or more processes have the directory open when the last link is removed, the dot and dot-dot entries, if present, shall be removed before rmdir() returns and no new entries may be created in the directory, but the directory shall not be removed until all references to the directory are closed.

If the directory is not an empty directory, rmdir() shall fail and set errno to [EEXIST] or [ENOTEMPTY].

Upon successful completion, the rmdir() function shall mark for update the st_ctime and st_mtime fields of the parent directory.

RETURN VALUE

Upon successful completion, the function rmdir() shall return 0. Otherwise, -1 shall be returned, and errno set to indicate the error. If -1 is returned, the named directory shall not be changed.

ERRORS

The rmdir() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix, or write permission is denied on the parent directory of the directory to be removed.
EBUSY
The directory to be removed is currently in use by the system or some process and the implementation considers this to be an error.
EEXIST or ENOTEMPTY
The path argument names a directory that is not an empty directory, or there are hard links to the directory other than dot or a single entry in dot-dot.
EINVAL
The path argument contains a last component that is dot.
EIO
A physical I/O error has occurred.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file, or the path argument names a nonexistent directory or points to an empty string.
ENOTDIR
A component of path is not a directory.
EPERM or EACCES

The S_ISVTX flag is set on the parent directory of the directory to be removed and the caller is not the owner of the directory to be removed, nor is the caller the owner of the parent directory, nor does the caller have the appropriate privileges.

EROFS
The directory entry to be removed resides on a read-only file system.

The rmdir() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Removing a Directory

The following example shows how to remove a directory named /home/cnd/mod1.

#include <unistd.h>

int status;
...
status = rmdir("/home/cnd/mod1");

APPLICATION USAGE

None.

RATIONALE

The rmdir() and rename() functions originated in 4.2 BSD, and they used [ENOTEMPTY] for the condition when the directory to be removed does not exist or new already exists. When the 1984 /usr/group standard was published, it contained [EEXIST] instead. When these functions were adopted into System V, the 1984 /usr/group standard was used as a reference. Therefore, several existing applications and implementations support/use both forms, and no agreement could be reached on either value. All implementations are required to supply both [EEXIST] and [ENOTEMPTY] in <errno.h> with distinct values, so that applications can use both values in C-language case statements.

The meaning of deleting pathname /dot is unclear, because the name of the file (directory) in the parent directory to be removed is not clear, particularly in the presence of multiple links to a directory.

The POSIX.1-1990 standard was silent with regard to the behavior of rmdir() when there are multiple hard links to the directory being removed. The requirement to set errno to [EEXIST] or [ENOTEMPTY] clarifies the behavior in this case.

If the process' current working directory is being removed, that should be an allowed error.

Virtually all existing implementations detect [ENOTEMPTY] or the case of dot-dot. The text in Error Numbers about returning any one of the possible errors permits that behavior to continue. The [ELOOP] error may be returned if more than {SYMLOOP_MAX} symbolic links are encountered during resolution of the path argument.

FUTURE DIRECTIONS

None.

SEE ALSO

Error Numbers , mkdir() , remove() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_setname (3p)

 Continue to this page.


FD_ZERO (3p)

 Continue to this page.


wmemset(3p)

WMEMSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wmemset - set wide characters in memory

SYNOPSIS

#include <wchar.h>

wchar_t *wmemset(wchar_t *ws, wchar_t wc, size_t n);

DESCRIPTION

The wmemset() function shall copy the value of wc into each of the first n wide characters of the object pointed to by ws. This function shall not be affected by locale and all wchar_t values shall be treated identically. The null wide character and wchar_t values not corresponding to valid characters shall not be treated specially.

If n is zero, the application shall ensure that ws is a valid pointer, and the function shall copy zero wide characters.

RETURN VALUE

The wmemset() functions shall return the value of ws.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wmemchr() , wmemcmp() , wmemcpy() , wmemmove() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tsearch(3p)

TDELETE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tdelete, tfind, tsearch, twalk - manage a binary search tree

SYNOPSIS

#include <search.h>

void *tdelete(const void *restrict key, void **restrict rootp,
int(*compar)(const void *, const void *));
void *tfind(const void *key, void *const *rootp,
int(*compar)(const void *, const void *));
void *tsearch(const void *key, void **rootp,
int (*compar)(const void *, const void *));
void twalk(const void *root,
void (*action)(const void *, VISIT, int));

DESCRIPTION

The tdelete(), tfind(), tsearch(), and twalk() functions manipulate binary search trees. Comparisons are made with a user-supplied routine, the address of which is passed as the compar argument. This routine is called with two arguments, which are the pointers to the elements being compared. The application shall ensure that the user-supplied routine returns an integer less than, equal to, or greater than 0, according to whether the first argument is to be considered less than, equal to, or greater than the second argument. The comparison function need not compare every byte, so arbitrary data may be contained in the elements in addition to the values being compared.

The tsearch() function shall build and access the tree. The key argument is a pointer to an element to be accessed or stored. If there is a node in the tree whose element is equal to the value pointed to by key, a pointer to this found node shall be returned. Otherwise, the value pointed to by key shall be inserted (that is, a new node is created and the value of key is copied to this node), and a pointer to this node returned. Only pointers are copied, so the application shall ensure that the calling routine stores the data. The rootp argument points to a variable that points to the root node of the tree. A null pointer value for the variable pointed to by rootp denotes an empty tree; in this case, the variable shall be set to point to the node which shall be at the root of the new tree.

Like tsearch(), tfind() shall search for a node in the tree, returning a pointer to it if found. However, if it is not found, tfind() shall return a null pointer. The arguments for tfind() are the same as for tsearch().

The tdelete() function shall delete a node from a binary search tree. The arguments are the same as for tsearch(). The variable pointed to by rootp shall be changed if the deleted node was the root of the tree. The tdelete() function shall return a pointer to the parent of the deleted node, or a null pointer if the node is not found.

The twalk() function shall traverse a binary search tree. The root argument is a pointer to the root node of the tree to be traversed. (Any node in a tree may be used as the root for a walk below that node.) The argument action is the name of a routine to be invoked at each node. This routine is, in turn, called with three arguments. The first argument shall be the address of the node being visited. The structure pointed to by this argument is unspecified and shall not be modified by the application, but it shall be possible to cast a pointer-to-node into a pointer-to-pointer-to-element to access the element stored in the node. The second argument shall be a value from an enumeration data type:

typedef enum { preorder, postorder, endorder, leaf } VISIT;

(defined in <search.h>), depending on whether this is the first, second, or third time that the node is visited (during a depth-first, left-to-right traversal of the tree), or whether the node is a leaf. The third argument shall be the level of the node in the tree, with the root being level 0.

If the calling function alters the pointer to the root, the result is undefined.

RETURN VALUE

If the node is found, both tsearch() and tfind() shall return a pointer to it. If not, tfind() shall return a null pointer, and tsearch() shall return a pointer to the inserted item.

A null pointer shall be returned by tsearch() if there is not enough space available to create a new node.

A null pointer shall be returned by tdelete(), tfind(), and tsearch() if rootp is a null pointer on entry.

The tdelete() function shall return a pointer to the parent of the deleted node, or a null pointer if the node is not found.

The twalk() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following code reads in strings and stores structures containing a pointer to each string and a count of its length. It then walks the tree, printing out the stored strings and their lengths in alphabetical order.

#include <search.h>
#include <string.h>
#include <stdio.h>

#define STRSZ    10000
#define NODSZ    500

struct node {      /* Pointers to these are stored in the tree. */
    char    *string;
    int     length;
};

char   string_space[STRSZ];  /* Space to store strings. */
struct node nodes[NODSZ];    /* Nodes to store. */
void  *root = NULL;          /* This points to the root. */

int main(int argc, char *argv[])
{
    char   *strptr = string_space;
    struct node    *nodeptr = nodes;
    void   print_node(const void *, VISIT, int);
    int    i = 0, node_compare(const void *, const void *);

    while (gets(strptr) != NULL && i++ < NODSZ)  {
        /* Set node. */
        nodeptr->string = strptr;
        nodeptr->length = strlen(strptr);
        /* Put node into the tree. */
        (void) tsearch((void *)nodeptr, (void **)&root,
            node_compare);
        /* Adjust pointers, so we do not overwrite tree. */
        strptr += nodeptr->length + 1;
        nodeptr++;
    }
    twalk(root, print_node);
    return 0;
}

/*
 *  This routine compares two nodes, based on an
 *  alphabetical ordering of the string field.
 */
int
node_compare(const void *node1, const void *node2)
{
    return strcmp(((const struct node *) node1)->string,
        ((const struct node *) node2)->string);
}

/*
 *  This routine prints out a node, the second time
 *  twalk encounters it or if it is a leaf.
 */
void
print_node(const void *ptr, VISIT order, int level)
{
    const struct node *p = *(const struct node **) ptr;

    if (order == postorder || order == leaf)  {
        (void) printf("string = %s,  length = %d\n",
            p->string, p->length);
    }
}

APPLICATION USAGE

The root argument to twalk() is one level of indirection less than the rootp arguments to tdelete() and tsearch().

There are two nomenclatures used to refer to the order in which tree nodes are visited. The tsearch() function uses preorder, postorder, and endorder to refer respectively to visiting a node before any of its children, after its left child and before its right, and after both its children. The alternative nomenclature uses preorder, inorder, and postorder to refer to the same visits, which could result in some confusion over the meaning of postorder.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

hcreate() , lsearch() , the Base Definitions volume of IEEE Std 1003.1-2001, <search.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mbsinit(3p)

MBSINIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mbsinit - determine conversion object status

SYNOPSIS

#include <wchar.h>

int mbsinit(const mbstate_t *ps);

DESCRIPTION

If ps is not a null pointer, the mbsinit() function shall determine whether the object pointed to by ps describes an initial conversion state.

RETURN VALUE

The mbsinit() function shall return non-zero if ps is a null pointer, or if the pointed-to object describes an initial conversion state; otherwise, it shall return zero.

If an mbstate_t object is altered by any of the functions described as "restartable", and is then used with a different character sequence, or in the other conversion direction, or with a different LC_CTYPE category setting than on earlier function calls, the behavior is undefined.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The mbstate_t object is used to describe the current conversion state from a particular character sequence to a wide-character sequence (or vice versa) under the rules of a particular setting of the LC_CTYPE category of the current locale.

The initial conversion state corresponds, for a conversion in either direction, to the beginning of a new character sequence in the initial shift state. A zero valued mbstate_t object is at least one way to describe an initial conversion state. A zero valued mbstate_t object can be used to initiate conversion involving any character sequence, in any LC_CTYPE category setting.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mbrlen() , mbrtowc() , wcrtomb() , mbsrtowcs() , wcsrtombs() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sem_post(3p)

SEM_POST

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_post - unlock a semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

int sem_post(sem_t *sem);

DESCRIPTION

The sem_post() function shall unlock the semaphore referenced by sem by performing a semaphore unlock operation on that semaphore.

If the semaphore value resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become unlocked; the semaphore value is simply incremented.

If the value of the semaphore resulting from this operation is zero, then one of the threads blocked waiting for the semaphore shall be allowed to return successfully from its call to sem_wait(). If the Process Scheduling option is supported, the thread to be unblocked shall be chosen in a manner appropriate to the scheduling policies and parameters in effect for the blocked threads. In the case of the schedulers SCHED_FIFO and SCHED_RR, the highest priority waiting thread shall be unblocked, and if there is more than one highest priority thread blocked waiting for the semaphore, then the highest priority thread that has been waiting the longest shall be unblocked. If the Process Scheduling option is not defined, the choice of a thread to unblock is unspecified.

If the Process Sporadic Server option is supported, and the scheduling policy is SCHED_SPORADIC, the semantics are as per SCHED_FIFO above.

The sem_post() function shall be reentrant with respect to signals and may be invoked from a signal-catching function.

RETURN VALUE

If successful, the sem_post() function shall return zero; otherwise, the function shall return -1 and set errno to indicate the error.

ERRORS

The sem_post() function shall fail if:

EINVAL
The sem argument does not refer to a valid semaphore.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sem_post() function is part of the Semaphores option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

semctl() , semget() , semop() , sem_timedwait() , sem_trywait() , sem_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isupper(3p)

ISUPPER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isupper - test for an uppercase letter

SYNOPSIS

#include <ctype.h>

int isupper(int c);

DESCRIPTION

The isupper() function shall test whether c is a character of class upper in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isupper() function shall return non-zero if c is an uppercase letter; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isspace() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutexattr_getprotocol(3p)

PTHREAD_MUTEXATTR_GETPROTOCOL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutexattr_getprotocol, pthread_mutexattr_setprotocol - get and set the protocol attribute of the mutex attributes object (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *
restrict attr, int *restrict protocol);
int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr,
int protocol);

DESCRIPTION

The pthread_mutexattr_getprotocol() and pthread_mutexattr_setprotocol() functions, respectively, shall get and set the protocol attribute of a mutex attributes object pointed to by attr which was previously created by the function pthread_mutexattr_init().

The protocol attribute defines the protocol to be followed in utilizing mutexes. The value of protocol may be one of:

PTHREAD_PRIO_NONE

PTHREAD_PRIO_INHERIT

PTHREAD_PRIO_PROTECT

which are defined in the <pthread.h> header.

When a thread owns a mutex with the PTHREAD_PRIO_NONE protocol attribute, its priority and scheduling shall not be affected by its mutex ownership.

When a thread is blocking higher priority threads because of owning one or more mutexes with the PTHREAD_PRIO_INHERIT protocol attribute, it shall execute at the higher of its priority or the priority of the highest priority thread waiting on any of the mutexes owned by this thread and initialized with this protocol.

When a thread owns one or more mutexes initialized with the PTHREAD_PRIO_PROTECT protocol, it shall execute at the higher of its priority or the highest of the priority ceilings of all the mutexes owned by this thread and initialized with this attribute, regardless of whether other threads are blocked on any of these mutexes or not.

While a thread is holding a mutex which has been initialized with the PTHREAD_PRIO_INHERIT or PTHREAD_PRIO_PROTECT protocol attributes, it shall not be subject to being moved to the tail of the scheduling queue at its priority in the event that its original priority is changed, such as by a call to sched_setparam(). Likewise, when a thread unlocks a mutex that has been initialized with the PTHREAD_PRIO_INHERIT or PTHREAD_PRIO_PROTECT protocol attributes, it shall not be subject to being moved to the tail of the scheduling queue at its priority in the event that its original priority is changed.

If a thread simultaneously owns several mutexes initialized with different protocols, it shall execute at the highest of the priorities that it would have obtained by each of these protocols.

When a thread makes a call to pthread_mutex_lock(), the mutex was initialized with the protocol attribute having the value PTHREAD_PRIO_INHERIT, when the calling thread is blocked because the mutex is owned by another thread, that owner thread shall inherit the priority level of the calling thread as long as it continues to own the mutex. The implementation shall update its execution priority to the maximum of its assigned priority and all its inherited priorities. Furthermore, if this owner thread itself becomes blocked on another mutex, the same priority inheritance effect shall be propagated to this other owner thread, in a recursive manner.

RETURN VALUE

Upon successful completion, the pthread_mutexattr_getprotocol() and pthread_mutexattr_setprotocol() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_mutexattr_setprotocol() function shall fail if:

ENOTSUP
The value specified by protocol is an unsupported value.

The pthread_mutexattr_getprotocol() and pthread_mutexattr_setprotocol() functions may fail if:

EINVAL
The value specified by attr or protocol is invalid.
EPERM
The caller does not have the privilege to perform the operation.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_destroy() , pthread_create() , pthread_mutex_destroy() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


socketpair(3p)

SOCKETPAIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

socketpair - create a pair of connected sockets

SYNOPSIS

#include <sys/socket.h>

int socketpair(int domain, int type, int protocol,
int socket_vector[2]);

DESCRIPTION

The socketpair() function shall create an unbound pair of connected sockets in a specified domain, of a specified type, under the protocol optionally specified by the protocol argument. The two sockets shall be identical. The file descriptors used in referencing the created sockets shall be returned in socket_vector[0] and socket_vector[1].

The socketpair() function takes the following arguments:

domain
Specifies the communications domain in which the sockets are to be created.
type
Specifies the type of sockets to be created.
protocol
Specifies a particular protocol to be used with the sockets. Specifying a protocol of 0 causes socketpair() to use an unspecified default protocol appropriate for the requested socket type.
socket_vector
Specifies a 2-integer array to hold the file descriptors of the created socket pair.

The type argument specifies the socket type, which determines the semantics of communications over the socket. The following socket types are defined; implementations may specify additional socket types:

SOCK_STREAM
Provides sequenced, reliable, bidirectional, connection-mode byte streams, and may provide a transmission mechanism for out-of-band data.
SOCK_DGRAM
Provides datagrams, which are connectionless-mode, unreliable messages of fixed maximum length.
SOCK_SEQPACKET
Provides sequenced, reliable, bidirectional, connection-mode transmission paths for records. A record can be sent using one or more output operations and received using one or more input operations, but a single operation never transfers part of more than one record. Record boundaries are visible to the receiver via the MSG_EOR flag.

If the protocol argument is non-zero, it shall specify a protocol that is supported by the address family. If the protocol argument is zero, the default protocol for this address family and type shall be used. The protocols supported by the system are implementation-defined.

The process may need to have appropriate privileges to use the socketpair() function or to create some sockets.

RETURN VALUE

Upon successful completion, this function shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The socketpair() function shall fail if:

EAFNOSUPPORT

The implementation does not support the specified address family.

EMFILE
No more file descriptors are available for this process.
ENFILE
No more file descriptors are available for the system.
EOPNOTSUPP
The specified protocol does not permit creation of socket pairs.
EPROTONOSUPPORT

The protocol is not supported by the address family, or the protocol is not supported by the implementation.

EPROTOTYPE
The socket type is not supported by the protocol.

The socketpair() function may fail if:

EACCES
The process does not have appropriate privileges.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The documentation for specific address families specifies which protocols each address family supports. The documentation for specific protocols specifies which socket types each protocol supports.

The socketpair() function is used primarily with UNIX domain sockets and need not be supported for other domains.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ulimit(3p)

ULIMIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ulimit - get and set process limits

SYNOPSIS

#include <ulimit.h>

long ulimit(int cmd, ...);

DESCRIPTION

The ulimit() function shall control process limits. The process limits that can be controlled by this function include the maximum size of a single file that can be written (this is equivalent to using setrlimit() with RLIMIT_FSIZE). The cmd values, defined in <ulimit.h>, include:

UL_GETFSIZE
Return the file size limit (RLIMIT_FSIZE) of the process. The limit shall be in units of 512-byte blocks and shall be inherited by child processes. Files of any size can be read. The return value shall be the integer part of the soft file size limit divided by 512. If the result cannot be represented as a long, the result is unspecified.
UL_SETFSIZE
Set the file size limit for output operations of the process to the value of the second argument, taken as a long, multiplied by 512. If the result would overflow an rlim_t, the actual value set is unspecified. Any process may decrease its own limit, but only a process with appropriate privileges may increase the limit. The return value shall be the integer part of the new file size limit divided by 512.

The ulimit() function shall not change the setting of errno if successful.

As all return values are permissible in a successful situation, an application wishing to check for error situations should set errno to 0, then call ulimit(), and, if it returns -1, check to see if errno is non-zero.

RETURN VALUE

Upon successful completion, ulimit() shall return the value of the requested limit. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The ulimit() function shall fail and the limit shall be unchanged if:

EINVAL
The cmd argument is not valid.
EPERM
A process not having appropriate privileges attempts to increase its file size limit.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getrlimit() , setrlimit() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <ulimit.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


csqrt(3p)

CSQRT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

csqrt, csqrtf, csqrtl - complex square root functions

SYNOPSIS

#include <complex.h>

double complex csqrt(double complex z);
float complex csqrtf(float complex z);
long double complex csqrtl(long double complex z);

DESCRIPTION

These functions shall compute the complex square root of z, with a branch cut along the negative real axis.

RETURN VALUE

These functions shall return the complex square root value, in the range of the right half-plane (including the imaginary axis).

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cabs() , cpow() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcsrtombs(3p)

WCSRTOMBS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsrtombs - convert a wide-character string to a character string (restartable)

SYNOPSIS

#include <wchar.h>

size_t wcsrtombs(char *restrict dst, const wchar_t **restrict src,
size_t len, mbstate_t *restrict ps);

DESCRIPTION

The wcsrtombs() function shall convert a sequence of wide characters from the array indirectly pointed to by src into a sequence of corresponding characters, beginning in the conversion state described by the object pointed to by ps. If dst is not a null pointer, the converted characters shall then be stored into the array pointed to by dst. Conversion continues up to and including a terminating null wide character, which shall also be stored. Conversion shall stop earlier in the following cases:

*
When a code is reached that does not correspond to a valid character

*
When the next character would exceed the limit of len total bytes to be stored in the array pointed to by dst (and dst is not a null pointer)

Each conversion shall take place as if by a call to the wcrtomb() function.

If dst is not a null pointer, the pointer object pointed to by src shall be assigned either a null pointer (if conversion stopped due to reaching a terminating null wide character) or the address just past the last wide character converted (if any). If conversion stopped due to reaching a terminating null wide character, the resulting state described shall be the initial conversion state.

If ps is a null pointer, the wcsrtombs() function shall use its own internal mbstate_t object, which is initialized at program start-up to the initial conversion state. Otherwise, the mbstate_t object pointed to by ps shall be used to completely describe the current conversion state of the associated character sequence. The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls wcsrtombs().

If the application uses any of the _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS functions, the application shall ensure that the wcsrtombs() function is called with a non-NULL ps argument.

The behavior of this function shall be affected by the LC_CTYPE category of the current locale.

RETURN VALUE

If conversion stops because a code is reached that does not correspond to a valid character, an encoding error occurs. In this case, the wcsrtombs() function shall store the value of the macro [EILSEQ] in errno and return (size_t)-1; the conversion state is undefined. Otherwise, it shall return the number of bytes in the resulting character sequence, not including the terminating null (if any).

ERRORS

The wcsrtombs() function may fail if:

EINVAL
ps points to an object that contains an invalid conversion state.
EILSEQ
A wide-character code does not correspond to a valid character.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mbsinit() , wcrtomb() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


llroundf (3p)

 Continue to this page.


llroundl (3p)

 Continue to this page.


kill(3p)

KILL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

kill - send a signal to a process or a group of processes

SYNOPSIS

#include <signal.h>

int kill(pid_t pid, int sig);

DESCRIPTION

The kill() function shall send a signal to a process or a group of processes specified by pid. The signal to be sent is specified by sig and is either one from the list given in <signal.h> or 0. If sig is 0 (the null signal), error checking is performed but no signal is actually sent. The null signal can be used to check the validity of pid.

For a process to have permission to send a signal to a process designated by pid, unless the sending process has appropriate privileges, the real or effective user ID of the sending process shall match the real or saved set-user-ID of the receiving process.

If pid is greater than 0, sig shall be sent to the process whose process ID is equal to pid.

If pid is 0, sig shall be sent to all processes (excluding an unspecified set of system processes) whose process group ID is equal to the process group ID of the sender, and for which the process has permission to send a signal.

If pid is -1, sig shall be sent to all processes (excluding an unspecified set of system processes) for which the process has permission to send that signal.

If pid is negative, but not -1, sig shall be sent to all processes (excluding an unspecified set of system processes) whose process group ID is equal to the absolute value of pid, and for which the process has permission to send a signal.

If the value of pid causes sig to be generated for the sending process, and if sig is not blocked for the calling thread and if no other thread has sig unblocked or is waiting in a sigwait() function for sig, either sig or at least one pending unblocked signal shall be delivered to the sending thread before kill() returns.

The user ID tests described above shall not be applied when sending SIGCONT to a process that is a member of the same session as the sending process.

An implementation that provides extended security controls may impose further implementation-defined restrictions on the sending of signals, including the null signal. In particular, the system may deny the existence of some or all of the processes specified by pid.

The kill() function is successful if the process has permission to send sig to any of the processes specified by pid. If kill() fails, no signal shall be sent.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The kill() function shall fail if:

EINVAL
The value of the sig argument is an invalid or unsupported signal number.
EPERM
The process does not have permission to send the signal to any receiving process.
ESRCH
No process or process group can be found corresponding to that specified by pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The semantics for permission checking for kill() differed between System V and most other implementations, such as Version 7 or 4.3 BSD. The semantics chosen for this volume of IEEE Std 1003.1-2001 agree with System V. Specifically, a set-user-ID process cannot protect itself against signals (or at least not against SIGKILL) unless it changes its real user ID. This choice allows the user who starts an application to send it signals even if it changes its effective user ID. The other semantics give more power to an application that wants to protect itself from the user who ran it.

Some implementations provide semantic extensions to the kill() function when the absolute value of pid is greater than some maximum, or otherwise special, value. Negative values are a flag to kill(). Since most implementations return [ESRCH] in this case, this behavior is not included in this volume of IEEE Std 1003.1-2001, although a conforming implementation could provide such an extension.

The implementation-defined processes to which a signal cannot be sent may include the scheduler or init.

There was initially strong sentiment to specify that, if pid specifies that a signal be sent to the calling process and that signal is not blocked, that signal would be delivered before kill() returns. This would permit a process to call kill() and be guaranteed that the call never return. However, historical implementations that provide only the signal() function make only the weaker guarantee in this volume of IEEE Std 1003.1-2001, because they only deliver one signal each time a process enters the kernel. Modifications to such implementations to support the sigaction() function generally require entry to the kernel following return from a signal-catching function, in order to restore the signal mask. Such modifications have the effect of satisfying the stronger requirement, at least when sigaction() is used, but not necessarily when signal() is used. The developers of this volume of IEEE Std 1003.1-2001 considered making the stronger requirement except when signal() is used, but felt this would be unnecessarily complex. Implementors are encouraged to meet the stronger requirement whenever possible. In practice, the weaker requirement is the same, except in the rare case when two signals arrive during a very short window. This reasoning also applies to a similar requirement for sigprocmask().

In 4.2 BSD, the SIGCONT signal can be sent to any descendant process regardless of user-ID security checks. This allows a job control shell to continue a job even if processes in the job have altered their user IDs (as in the su command). In keeping with the addition of the concept of sessions, similar functionality is provided by allowing the SIGCONT signal to be sent to any process in the same session regardless of user ID security checks. This is less restrictive than BSD in the sense that ancestor processes (in the same session) can now be the recipient. It is more restrictive than BSD in the sense that descendant processes that form new sessions are now subject to the user ID checks. A similar relaxation of security is not necessary for the other job control signals since those signals are typically sent by the terminal driver in recognition of special characters being typed; the terminal driver bypasses all security checks.

In secure implementations, a process may be restricted from sending a signal to a process having a different security label. In order to prevent the existence or nonexistence of a process from being used as a covert channel, such processes should appear nonexistent to the sender; that is, [ESRCH] should be returned, rather than [EPERM], if pid refers only to such processes.

Existing implementations vary on the result of a kill() with pid indicating an inactive process (a terminated process that has not been waited for by its parent). Some indicate success on such a call (subject to permission checking), while others give an error of [ESRCH]. Since the definition of process lifetime in this volume of IEEE Std 1003.1-2001 covers inactive processes, the [ESRCH] error as described is inappropriate in this case. In particular, this means that an application cannot have a parent process check for termination of a particular child with kill(). (Usually this is done with the null signal; this can be done reliably with waitpid().)

There is some belief that the name kill() is misleading, since the function is not always intended to cause process termination. However, the name is common to all historical implementations, and any change would be in conflict with the goal of minimal changes to existing application code.

FUTURE DIRECTIONS

None.

SEE ALSO

getpid() , raise() , setsid() , sigaction() , sigqueue() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


select(3p)

PSELECT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pselect, select - synchronous I/O multiplexing

SYNOPSIS

#include <sys/select.h>

int pselect(int nfds, fd_set *restrict readfds,
fd_set *restrict writefds, fd_set *restrict errorfds,
const struct timespec *restrict timeout,
const sigset_t *restrict sigmask);
int select(int nfds, fd_set *restrict readfds,
fd_set *restrict writefds, fd_set *restrict errorfds,
struct timeval *restrict timeout);
void FD_CLR(int fd, fd_set *fdset);
int FD_ISSET(int fd, fd_set *fdset);
void FD_SET(int fd, fd_set *fdset);
void FD_ZERO(fd_set *fdset);

DESCRIPTION

The pselect() function shall examine the file descriptor sets whose addresses are passed in the readfds, writefds, and errorfds parameters to see whether some of their descriptors are ready for reading, are ready for writing, or have an exceptional condition pending, respectively.

The select() function shall be equivalent to the pselect() function, except as follows:

*
For the select() function, the timeout period is given in seconds and microseconds in an argument of type struct timeval, whereas for the pselect() function the timeout period is given in seconds and nanoseconds in an argument of type struct timespec.

*
The select() function has no sigmask argument; it shall behave as pselect() does when sigmask is a null pointer.

*
Upon successful completion, the select() function may modify the object pointed to by the timeout argument.

The pselect() and select() functions shall support regular files, terminal and pseudo-terminal devices, STREAMS-based files, FIFOs, pipes, and sockets. The behavior of pselect() and select() on file descriptors that refer to other types of file is unspecified.

The nfds argument specifies the range of descriptors to be tested. The first nfds descriptors shall be checked in each set; that is, the descriptors from zero through nfds-1 in the descriptor sets shall be examined.

If the readfds argument is not a null pointer, it points to an object of type fd_set that on input specifies the file descriptors to be checked for being ready to read, and on output indicates which file descriptors are ready to read.

If the writefds argument is not a null pointer, it points to an object of type fd_set that on input specifies the file descriptors to be checked for being ready to write, and on output indicates which file descriptors are ready to write.

If the errorfds argument is not a null pointer, it points to an object of type fd_set that on input specifies the file descriptors to be checked for error conditions pending, and on output indicates which file descriptors have error conditions pending.

Upon successful completion, the pselect() or select() function shall modify the objects pointed to by the readfds, writefds, and errorfds arguments to indicate which file descriptors are ready for reading, ready for writing, or have an error condition pending, respectively, and shall return the total number of ready descriptors in all the output sets. For each file descriptor less than nfds, the corresponding bit shall be set on successful completion if it was set on input and the associated condition is true for that file descriptor.

If none of the selected descriptors are ready for the requested operation, the pselect() or select() function shall block until at least one of the requested operations becomes ready, until the timeout occurs, or until interrupted by a signal. The timeout parameter controls how long the pselect() or select() function shall take before timing out. If the timeout parameter is not a null pointer, it specifies a maximum interval to wait for the selection to complete. If the specified time interval expires without any requested operation becoming ready, the function shall return. If the timeout parameter is a null pointer, then the call to pselect() or select() shall block indefinitely until at least one descriptor meets the specified criteria. To effect a poll, the timeout parameter should not be a null pointer, and should point to a zero-valued timespec structure.

The use of a timeout does not affect any pending timers set up by alarm(), ualarm(), or setitimer().

Implementations may place limitations on the maximum timeout interval supported. All implementations shall support a maximum timeout interval of at least 31 days. If the timeout argument specifies a timeout interval greater than the implementation-defined maximum value, the maximum value shall be used as the actual timeout value. Implementations may also place limitations on the granularity of timeout intervals. If the requested timeout interval requires a finer granularity than the implementation supports, the actual timeout interval shall be rounded up to the next supported value.

If sigmask is not a null pointer, then the pselect() function shall replace the signal mask of the process by the set of signals pointed to by sigmask before examining the descriptors, and shall restore the signal mask of the process before returning.

A descriptor shall be considered ready for reading when a call to an input function with O_NONBLOCK clear would not block, whether or not the function would transfer data successfully. (The function might return data, an end-of-file indication, or an error other than one indicating that it is blocked, and in each of these cases the descriptor shall be considered ready for reading.)

A descriptor shall be considered ready for writing when a call to an output function with O_NONBLOCK clear would not block, whether or not the function would transfer data successfully.

If a socket has a pending error, it shall be considered to have an exceptional condition pending. Otherwise, what constitutes an exceptional condition is file type-specific. For a file descriptor for use with a socket, it is protocol-specific except as noted below. For other file types it is implementation-defined. If the operation is meaningless for a particular file type, pselect() or select() shall indicate that the descriptor is ready for read or write operations, and shall indicate that the descriptor has no exceptional condition pending.

If a descriptor refers to a socket, the implied input function is the recvmsg() function with parameters requesting normal and ancillary data, such that the presence of either type shall cause the socket to be marked as readable. The presence of out-of-band data shall be checked if the socket option SO_OOBINLINE has been enabled, as out-of-band data is enqueued with normal data. If the socket is currently listening, then it shall be marked as readable if an incoming connection request has been received, and a call to the accept() function shall complete without blocking.

If a descriptor refers to a socket, the implied output function is the sendmsg() function supplying an amount of normal data equal to the current value of the SO_SNDLOWAT option for the socket. If a non-blocking call to the connect() function has been made for a socket, and the connection attempt has either succeeded or failed leaving a pending error, the socket shall be marked as writable.

A socket shall be considered to have an exceptional condition pending if a receive operation with O_NONBLOCK clear for the open file description and with the MSG_OOB flag set would return out-of-band data without blocking. (It is protocol-specific whether the MSG_OOB flag would be used to read out-of-band data.) A socket shall also be considered to have an exceptional condition pending if an out-of-band data mark is present in the receive queue. Other circumstances under which a socket may be considered to have an exceptional condition pending are protocol-specific and implementation-defined.

If the readfds, writefds, and errorfds arguments are all null pointers and the timeout argument is not a null pointer, the pselect() or select() function shall block for the time specified, or until interrupted by a signal. If the readfds, writefds, and errorfds arguments are all null pointers and the timeout argument is a null pointer, the pselect() or select() function shall block until interrupted by a signal.

File descriptors associated with regular files shall always select true for ready to read, ready to write, and error conditions.

On failure, the objects pointed to by the readfds, writefds, and errorfds arguments shall not be modified. If the timeout interval expires without the specified condition being true for any of the specified file descriptors, the objects pointed to by the readfds, writefds, and errorfds arguments shall have all bits set to 0.

File descriptor masks of type fd_set can be initialized and tested with FD_CLR(), FD_ISSET(), FD_SET(), and FD_ZERO(). It is unspecified whether each of these is a macro or a function. If a macro definition is suppressed in order to access an actual function, or a program defines an external identifier with any of these names, the behavior is undefined.

FD_CLR(fd, fdsetp) shall remove the file descriptor fd from the set pointed to by fdsetp. If fd is not a member of this set, there shall be no effect on the set, nor will an error be returned.

FD_ISSET(fd, fdsetp) shall evaluate to non-zero if the file descriptor fd is a member of the set pointed to by fdsetp, and shall evaluate to zero otherwise.

FD_SET(fd, fdsetp) shall add the file descriptor fd to the set pointed to by fdsetp. If the file descriptor fd is already in this set, there shall be no effect on the set, nor will an error be returned.

FD_ZERO(fdsetp) shall initialize the descriptor set pointed to by fdsetp to the null set. No error is returned if the set is not empty at the time FD_ZERO() is invoked.

The behavior of these macros is undefined if the fd argument is less than 0 or greater than or equal to FD_SETSIZE, or if fd is not a valid file descriptor, or if any of the arguments are expressions with side effects.

RETURN VALUE

Upon successful completion, the pselect() and select() functions shall return the total number of bits set in the bit masks. Otherwise, -1 shall be returned, and errno shall be set to indicate the error.

FD_CLR(), FD_SET(), and FD_ZERO() do not return a value. FD_ISSET() shall return a non-zero value if the bit for the file descriptor fd is set in the file descriptor set pointed to by fdset, and 0 otherwise.

ERRORS

Under the following conditions, pselect() and select() shall fail and set errno to:

EBADF
One or more of the file descriptor sets specified a file descriptor that is not a valid open file descriptor.
EINTR
The function was interrupted before any of the selected events occurred and before the timeout interval expired.

If SA_RESTART has been set for the interrupting signal, it is implementation-defined whether the function restarts or returns with [EINTR].

EINVAL
An invalid timeout interval was specified.
EINVAL
The nfds argument is less than 0 or greater than FD_SETSIZE.
EINVAL
One of the specified file descriptors refers to a STREAM or multiplexer that is linked (directly or indirectly) downstream from a multiplexer.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

In previous versions of the Single UNIX Specification, the select() function was defined in the <sys/time.h> header. This is now changed to <sys/select.h>. The rationale for this change was as follows: the introduction of the pselect() function included the <sys/select.h> header and the <sys/select.h> header defines all the related definitions for the pselect() and select() functions. Backwards-compatibility to existing XSI implementations is handled by allowing <sys/time.h> to include <sys/select.h>.

FUTURE DIRECTIONS

None.

SEE ALSO

accept() , alarm() , connect() , fcntl() , poll() , read() , recvmsg() , sendmsg() , setitimer() , ualarm() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/select.h>, <sys/time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getgrgid_r (3p)

 Continue to this page.


pthread_cleanup_push(3p)

PTHREAD_CLEANUP_POP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_cleanup_pop, pthread_cleanup_push - establish cancellation handlers

SYNOPSIS

#include <pthread.h>

void pthread_cleanup_pop(int execute);
void pthread_cleanup_push(void (*routine)(void*), void *arg);

DESCRIPTION

The pthread_cleanup_pop() function shall remove the routine at the top of the calling thread's cancellation cleanup stack and optionally invoke it (if execute is non-zero).

The pthread_cleanup_push() function shall push the specified cancellation cleanup handler routine onto the calling thread's cancellation cleanup stack. The cancellation cleanup handler shall be popped from the cancellation cleanup stack and invoked with the argument arg when:

*
The thread exits (that is, calls pthread_exit()).

*
The thread acts upon a cancellation request.

*
The thread calls pthread_cleanup_pop() with a non-zero execute argument.

These functions may be implemented as macros. The application shall ensure that they appear as statements, and in pairs within the same lexical scope (that is, the pthread_cleanup_push() macro may be thought to expand to a token list whose first token is '{' with pthread_cleanup_pop() expanding to a token list whose last token is the corresponding '}' ).

The effect of calling longjmp() or siglongjmp() is undefined if there have been any calls to pthread_cleanup_push() or pthread_cleanup_pop() made without the matching call since the jump buffer was filled. The effect of calling longjmp() or siglongjmp() from inside a cancellation cleanup handler is also undefined unless the jump buffer was also filled in the cancellation cleanup handler.

RETURN VALUE

The pthread_cleanup_push() and pthread_cleanup_pop() functions shall not return a value.

ERRORS

No errors are defined.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

The following is an example using thread primitives to implement a cancelable, writers-priority read-write lock:

typedef struct {
    pthread_mutex_t lock;
    pthread_cond_t rcond,
        wcond;
    int lock_count; /* < 0 .. Held by writer. */
                    /* > 0 .. Held by lock_count readers. */
                    /* = 0 .. Held by nobody. */
    int waiting_writers; /* Count of waiting writers. */
} rwlock;

void
waiting_reader_cleanup(void *arg)
{
    rwlock *l;

    l = (rwlock *) arg;
    pthread_mutex_unlock(&l->lock);
}

void
lock_for_read(rwlock *l)
{
    pthread_mutex_lock(&l->lock);
    pthread_cleanup_push(waiting_reader_cleanup, l);
    while ((l->lock_count < 0) && (l->waiting_writers != 0))
        pthread_cond_wait(&l->rcond, &l->lock);
    l->lock_count++;
   /*
    * Note the pthread_cleanup_pop executes
    * waiting_reader_cleanup.
    */
    pthread_cleanup_pop(1);
}

void
release_read_lock(rwlock *l)
{
    pthread_mutex_lock(&l->lock);
    if (--l->lock_count == 0)
        pthread_cond_signal(&l->wcond);
    pthread_mutex_unlock(l);
}

void
waiting_writer_cleanup(void *arg)
{
    rwlock *l;

    l = (rwlock *) arg;
    if ((--l->waiting_writers == 0) && (l->lock_count >= 0)) {
       /*
        * This only happens if we have been canceled.
        */
        pthread_cond_broadcast(&l->wcond);
}
    pthread_mutex_unlock(&l->lock);
}

void
lock_for_write(rwlock *l)
{
    pthread_mutex_lock(&l->lock);
    l->waiting_writers++;
    pthread_cleanup_push(waiting_writer_cleanup, l);
    while (l->lock_count != 0)
        pthread_cond_wait(&l->wcond, &l->lock);
    l->lock_count = -1;
   /*
    * Note the pthread_cleanup_pop executes
    * waiting_writer_cleanup.
    */
    pthread_cleanup_pop(1);
}

void
release_write_lock(rwlock *l)
{
    pthread_mutex_lock(&l->lock);
    l->lock_count = 0;
    if (l->waiting_writers == 0)
        pthread_cond_broadcast(&l->rcond)
    else
        pthread_cond_signal(&l->wcond);
    pthread_mutex_unlock(&l->lock);
}

/*
 * This function is called to initialize the read/write lock.
 */
void
initialize_rwlock(rwlock *l)
{
    pthread_mutex_init(&l->lock, pthread_mutexattr_default);
    pthread_cond_init(&l->wcond, pthread_condattr_default);
    pthread_cond_init(&l->rcond, pthread_condattr_default);
    l->lock_count = 0;
    l->waiting_writers = 0;
}

reader_thread()
{
    lock_for_read(&lock);
    pthread_cleanup_push(release_read_lock, &lock);
   /*
    * Thread has read lock.
    */
    pthread_cleanup_pop(1);
}

writer_thread()
{
    lock_for_write(&lock);
    pthread_cleanup_push(release_write_lock, &lock);
   /*
    * Thread has write lock.
    */
pthread_cleanup_pop(1);
}

APPLICATION USAGE

The two routines that push and pop cancellation cleanup handlers, pthread_cleanup_push() and pthread_cleanup_pop(), can be thought of as left and right parentheses. They always need to be matched.

RATIONALE

The restriction that the two routines that push and pop cancellation cleanup handlers, pthread_cleanup_push() and pthread_cleanup_pop(), have to appear in the same lexical scope allows for efficient macro or compiler implementations and efficient storage management. A sample implementation of these routines as macros might look like this:

#define pthread_cleanup_push(rtn,arg) { \
    struct _pthread_handler_rec __cleanup_handler, **__head; \
    __cleanup_handler.rtn = rtn; \
    __cleanup_handler.arg = arg; \
    (void) pthread_getspecific(_pthread_handler_key, &__head); \
    __cleanup_handler.next = *__head; \
    *__head = &__cleanup_handler;

#define pthread_cleanup_pop(ex) \
    *__head = __cleanup_handler.next; \
    if (ex) (*__cleanup_handler.rtn)(__cleanup_handler.arg); \
}

A more ambitious implementation of these routines might do even better by allowing the compiler to note that the cancellation cleanup handler is a constant and can be expanded inline.

This volume of IEEE Std 1003.1-2001 currently leaves unspecified the effect of calling longjmp() from a signal handler executing in a POSIX System Interfaces function. If an implementation wants to allow this and give the programmer reasonable behavior, the longjmp() function has to call all cancellation cleanup handlers that have been pushed but not popped since the time setjmp() was called.

Consider a multi-threaded function called by a thread that uses signals. If a signal were delivered to a signal handler during the operation of qsort() and that handler were to call longjmp() (which, in turn, did not call the cancellation cleanup handlers) the helper threads created by the qsort() function would not be canceled. Instead, they would continue to execute and write into the argument array even though the array might have been popped off the stack.

Note that the specified cleanup handling mechanism is especially tied to the C language and, while the requirement for a uniform mechanism for expressing cleanup is language-independent, the mechanism used in other languages may be quite different. In addition, this mechanism is really only necessary due to the lack of a real exception mechanism in the C language, which would be the ideal solution.

There is no notion of a cancellation cleanup-safe function. If an application has no cancellation points in its signal handlers, blocks any signal whose handler may have cancellation points while calling async-unsafe functions, or disables cancellation while calling async-unsafe functions, all functions may be safely called from cancellation cleanup routines.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cancel() , pthread_setcancelstate() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcspbrk(3p)

WCSPBRK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcspbrk - scan a wide-character string for a wide-character code

SYNOPSIS

#include <wchar.h>

wchar_t *wcspbrk(const wchar_t *ws1, const wchar_t *ws2);

DESCRIPTION

The wcspbrk() function shall locate the first occurrence in the wide-character string pointed to by ws1 of any wide-character code from the wide-character string pointed to by ws2.

RETURN VALUE

Upon successful completion, wcspbrk() shall return a pointer to the wide-character code or a null pointer if no wide-character code from ws2 occurs in ws1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcschr() , wcsrchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


gai_strerror(3p)

GAI_STRERROR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gai_strerror - address and name information error description

SYNOPSIS

#include <netdb.h>

const char *gai_strerror(int ecode);

DESCRIPTION

The gai_strerror() function shall return a text string describing an error value for the getaddrinfo() and getnameinfo() functions listed in the <netdb.h> header.

When the ecode argument is one of the following values listed in the <netdb.h> header:

[EAI_AGAIN]
[EAI_BADFLAGS]
[EAI_FAIL]
[EAI_FAMILY]
[EAI_MEMORY]
[EAI_NONAME]
[EAI_OVERFLOW]
[EAI_SERVICE]
[EAI_SOCKTYPE]
[EAI_SYSTEM]

the function return value shall point to a string describing the error. If the argument is not one of those values, the function shall return a pointer to a string whose contents indicate an unknown error.

RETURN VALUE

Upon successful completion, gai_strerror() shall return a pointer to an implementation-defined string.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getaddrinfo() , the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


aio_return(3p)

AIO_RETURN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio_return - retrieve return status of an asynchronous I/O operation (REALTIME)

SYNOPSIS

#include <aio.h>

ssize_t aio_return(struct aiocb *aiocbp);

DESCRIPTION

The aio_return() function shall return the return status associated with the aiocb structure referenced by the aiocbp argument. The return status for an asynchronous I/O operation is the value that would be returned by the corresponding read(), write(), or fsync() function call. If the error status for the operation is equal to [EINPROGRESS], then the return status for the operation is undefined. The aio_return() function may be called exactly once to retrieve the return status of a given asynchronous operation; thereafter, if the same aiocb structure is used in a call to aio_return() or aio_error(), an error may be returned. When the aiocb structure referred to by aiocbp is used to submit another asynchronous operation, then aio_return() may be successfully used to retrieve the return status of that operation.

RETURN VALUE

If the asynchronous I/O operation has completed, then the return status, as described for read(), write(), and fsync(), shall be returned. If the asynchronous I/O operation has not yet completed, the results of aio_return() are undefined.

ERRORS

The aio_return() function may fail if:

EINVAL
The aiocbp argument does not refer to an asynchronous operation whose return status has not yet been retrieved.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The aio_return() function is part of the Asynchronous Input and Output option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_cancel() , aio_error() , aio_fsync() , aio_read() , aio_write() , close() , exec() , exit() , fork() , lio_listio() , lseek() , read() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


memccpy(3p)

MEMCCPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

memccpy - copy bytes in memory

SYNOPSIS

#include <string.h>

void *memccpy(void *restrict s1, const void *restrict s2,
int c, size_t n);

DESCRIPTION

The memccpy() function shall copy bytes from memory area s2 into s1, stopping after the first occurrence of byte c (converted to an unsigned char) is copied, or after n bytes are copied, whichever comes first. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The memccpy() function shall return a pointer to the byte after the copy of c in s1, or a null pointer if c was not found in the first n bytes of s2.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The memccpy() function does not check for the overflow of the receiving memory area.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


j0(3p)

J0

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

j0, j1, jn - Bessel functions of the first kind

SYNOPSIS

#include <math.h>

double j0(double x);
double j1(double x);
double jn(int n, double x);

DESCRIPTION

The j0(), j1(), and jn() functions shall compute Bessel functions of x of the first kind of orders 0, 1, and n, respectively.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the relevant Bessel value of x of the first kind.

If the x argument is too large in magnitude, or the correct result would cause underflow, 0 shall be returned and a range error may occur.

If x is NaN, a NaN shall be returned.

ERRORS

These functions may fail if:

Range Error
The value of x was too large in magnitude, or an underflow occurred.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

No other errors shall occur.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , y0() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


j1 (3p)

 Continue to this page.


pthread_attr_setguardsize (3p)

 Continue to this page.


nl_langinfo(3p)

NL_LANGINFO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nl_langinfo - language information

SYNOPSIS

#include <langinfo.h>

char *nl_langinfo(nl_item item);

DESCRIPTION

The nl_langinfo() function shall return a pointer to a string containing information relevant to the particular language or cultural area defined in the program's locale (see <langinfo.h>). The manifest constant names and values of item are defined in <langinfo.h>. For example:

nl_langinfo(ABDAY_1)

would return a pointer to the string "Dom" if the identified language was Portuguese, and "Sun" if the identified language was English.

Calls to setlocale() with a category corresponding to the category of item (see <langinfo.h>), or to the category LC_ALL , may overwrite the array pointed to by the return value.

The nl_langinfo() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

In a locale where langinfo data is not defined, nl_langinfo() shall return a pointer to the corresponding string in the POSIX locale. In all locales, nl_langinfo() shall return a pointer to an empty string if item contains an invalid setting.

This pointer may point to static data that may be overwritten on the next call.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Getting Date and Time Formatting Information

The following example returns a pointer to a string containing date and time formatting information, as defined in the LC_TIME category of the current locale.

#include <time.h>
#include <langinfo.h>
...
strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm);
...

APPLICATION USAGE

The array pointed to by the return value should not be modified by the program, but may be modified by further calls to nl_langinfo().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <langinfo.h>, <nl_types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_kill(3p)

PTHREAD_KILL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_kill - send a signal to a thread

SYNOPSIS

#include <signal.h>

int pthread_kill(pthread_t thread, int sig);

DESCRIPTION

The pthread_kill() function shall request that a signal be delivered to the specified thread.

As in kill(), if sig is zero, error checking shall be performed but no signal shall actually be sent.

RETURN VALUE

Upon successful completion, the function shall return a value of zero. Otherwise, the function shall return an error number. If the pthread_kill() function fails, no signal shall be sent.

ERRORS

The pthread_kill() function shall fail if:

ESRCH
No thread could be found corresponding to that specified by the given thread ID.
EINVAL
The value of the sig argument is an invalid or unsupported signal number.

The pthread_kill() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_kill() function provides a mechanism for asynchronously directing a signal at a thread in the calling process. This could be used, for example, by one thread to affect broadcast delivery of a signal to a set of threads.

Note that pthread_kill() only causes the signal to be handled in the context of the given thread; the signal action (termination or stopping) affects the process as a whole.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

kill() , pthread_self() , raise() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mq_unlink(3p)

MQ_UNLINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_unlink - remove a message queue (REALTIME)

SYNOPSIS

#include <mqueue.h>

int mq_unlink(const char *name);

DESCRIPTION

The mq_unlink() function shall remove the message queue named by the pathname name. After a successful call to mq_unlink() with name, a call to mq_open() with name shall fail if the flag O_CREAT is not set in flags. If one or more processes have the message queue open when mq_unlink() is called, destruction of the message queue shall be postponed until all references to the message queue have been closed.

Calls to mq_open() to recreate the message queue may fail until the message queue is actually removed. However, the mq_unlink() call need not block until all references have been closed; it may return immediately.

RETURN VALUE

Upon successful completion, the function shall return a value of zero. Otherwise, the named message queue shall be unchanged by this function call, and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The mq_unlink() function shall fail if:

EACCES
Permission is denied to unlink the named message queue.
ENAMETOOLONG
The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
The named message queue does not exist.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_close() , mq_open() , msgctl() , msgget() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


jn (3p)

 Continue to this page.


wordfree (3p)

 Continue to this page.


pthread_rwlock_timedrdlock(3p)

PTHREAD_RWLOCK_TIMEDRDLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlock_timedrdlock - lock a read-write lock for reading

SYNOPSIS

#include <pthread.h>
#include <time.h>

int pthread_rwlock_timedrdlock(pthread_rwlock_t *restrict rwlock,
const struct timespec *restrict abs_timeout);

DESCRIPTION

The pthread_rwlock_timedrdlock() function shall apply a read lock to the read-write lock referenced by rwlock as in the pthread_rwlock_rdlock() function. However, if the lock cannot be acquired without waiting for other threads to unlock the lock, this wait shall be terminated when the specified timeout expires. The timeout shall expire when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call.

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock. If the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function. The resolution of the timeout shall be the resolution of the clock on which it is based. The timespec data type is defined in the <time.h> header. Under no circumstances shall the function fail with a timeout if the lock can be acquired immediately. The validity of the abs_timeout parameter need not be checked if the lock can be immediately acquired.

If a signal that causes a signal handler to be executed is delivered to a thread blocked on a read-write lock via a call to pthread_rwlock_timedrdlock(), upon return from the signal handler the thread shall resume waiting for the lock as if it was not interrupted.

The calling thread may deadlock if at the time the call is made it holds a write lock on rwlock. The results are undefined if this function is called with an uninitialized read-write lock.

RETURN VALUE

The pthread_rwlock_timedrdlock() function shall return zero if the lock for reading on the read-write lock object referenced by rwlock is acquired. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_rwlock_timedrdlock() function shall fail if:

ETIMEDOUT
The lock could not be acquired before the specified timeout expired.

The pthread_rwlock_timedrdlock() function may fail if:

EAGAIN
The read lock could not be acquired because the maximum number of read locks for lock would be exceeded.
EDEADLK
The calling thread already holds a write lock on rwlock.
EINVAL
The value specified by rwlock does not refer to an initialized read-write lock object, or the abs_timeout nanosecond value is less than zero or greater than or equal to 1000 million.

This function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using this function may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

The pthread_rwlock_timedrdlock() function is part of the Threads and Timeouts options and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_destroy() , pthread_rwlock_rdlock() , pthread_rwlock_timedwrlock()
, pthread_rwlock_tryrdlock() , pthread_rwlock_trywrlock()
, pthread_rwlock_unlock() , pthread_rwlock_wrlock() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>,
<time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_cond_timedwait (3p)

 Continue to this page.


pthread_barrierattr_destroy (3p)

 Continue to this page.


nearbyint(3p)

NEARBYINT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nearbyint, nearbyintf, nearbyintl - floating-point rounding functions

SYNOPSIS

#include <math.h>

double nearbyint(double x);
float nearbyintf(float x);
long double nearbyintl(long double x);

DESCRIPTION

These functions shall round their argument to an integer value in floating-point format, using the current rounding direction and without raising the inexact floating-point exception.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the rounded integer value.

If x is NaN, a NaN shall be returned.

If x is ±0, ±0 shall be returned.

If x is ±Inf, x shall be returned.

If the correct value would cause overflow, a range error shall occur and nearbyint(), nearbyintf(), and nearbyintl() shall return the value of the macro ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (with the same sign as x), respectively.

ERRORS

These functions shall fail if:

Range Error
The result would cause an overflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wprintf(3p)

FWPRINTF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fwprintf, swprintf, wprintf - print formatted wide-character output

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

int fwprintf(FILE *restrict stream, const wchar_t *restrict format, ...);
int swprintf(wchar_t *restrict ws, size_t n,
const wchar_t *restrict format, ...);
int wprintf(const wchar_t *restrict format, ...);

DESCRIPTION

The fwprintf() function shall place output on the named output stream. The wprintf() function shall place output on the standard output stream stdout. The swprintf() function shall place output followed by the null wide character in consecutive wide characters starting at *ws; no more than n wide characters shall be written, including a terminating null wide character, which is always added (unless n is zero).

Each of these functions shall convert, format, and print its arguments under control of the format wide-character string. The format is composed of zero or more directives: ordinary wide-characters, which are simply copied to the output stream, and conversion specifications, each of which results in the fetching of zero or more arguments. The results are undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments are evaluated but are otherwise ignored.

Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier wide character % (see below) is replaced by the sequence "%n$" , where n is a decimal integer in the range [1,{NL_ARGMAX}], giving the position of the argument in the argument list. This feature provides for the definition of format wide-character strings that select arguments in an order appropriate to specific languages (see the EXAMPLES section).

The format can contain either numbered argument specifications (that is, "%n$" and "*m$"), or unnumbered argument conversion specifications (that is, % and * ), but not both. The only exception to this is that %% can be mixed with the "%n$" form. The results of mixing numbered and unnumbered argument specifications in a format wide-character string are undefined. When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the (N-1)th, are specified in the format wide-character string.

In format wide-character strings containing the "%n$" form of conversion specification, numbered arguments in the argument list can be referenced from the format wide-character string as many times as required.

In format wide-character strings containing the % form of conversion specification, each argument in the argument list shall be used exactly once.

All forms of the fwprintf() function allow for the insertion of a locale-dependent radix character in the output string, output as a wide-character value. The radix character is defined in the program's locale (category LC_NUMERIC ). In the POSIX locale, or in a locale where the radix character is not defined, the radix character shall default to a period ( '.' ).

Each conversion specification is introduced by the '%' wide character or by the wide-character sequence "%n$", after which the following appear in sequence:

*
Zero or more flags (in any order), which modify the meaning of the conversion specification.

*
An optional minimum field width. If the converted value has fewer wide characters than the field width, it shall be padded with spaces by default on the left; it shall be padded on the right, if the left-adjustment flag ( '-' ), described below, is given to the field width. The field width takes the form of an asterisk ( '*' ), described below, or a decimal integer.

*
An optional precision that gives the minimum number of digits to appear for the d , i , o , u , x , and X conversion specifiers; the number of digits to appear after the radix character for the a , A , e , E , f , and F conversion specifiers; the maximum number of significant digits for the g and G conversion specifiers; or the maximum number of wide characters to be printed from a string in the s conversion specifiers. The precision takes the form of a period ( '.' ) followed either by an asterisk ( '*' ), described below, or an optional decimal digit string, where a null digit string is treated as 0. If a precision appears with any other conversion wide character, the behavior is undefined.

*
An optional length modifier that specifies the size of the argument.

*
A conversion specifier wide character that indicates the type of conversion to be applied.

A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision. Applications shall ensure that arguments specifying field width, or precision, or both appear in that order before the argument, if any, to be converted. A negative field width is taken as a '-' flag followed by a positive field width. A negative precision is taken as if the precision were omitted. In format wide-character strings containing the "%n$" form of a conversion specification, a field width or precision may be indicated by the sequence "*m$", where m is a decimal integer in the range [1,{NL_ARGMAX}] giving the position in the argument list (after the format argument) of an integer argument containing the field width or precision, for example:

wprintf(L"%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);

The flag wide characters and their meanings are:

'
The integer portion of the result of a decimal conversion ( %i , %d , %u , %f , %F , %g , or %G ) shall be formatted with thousands' grouping wide characters. For other conversions, the behavior is undefined. The numeric grouping wide character is used.
-
The result of the conversion shall be left-justified within the field. The conversion shall be right-justified if this flag is not specified.
+
The result of a signed conversion shall always begin with a sign ( '+' or '-' ). The conversion shall begin with a sign only when a negative value is converted if this flag is not specified.
<space>
If the first wide character of a signed conversion is not a sign, or if a signed conversion results in no wide characters, a <space> shall be prefixed to the result. This means that if the <space> and '+' flags both appear, the <space> flag shall be ignored.
#
Specifies that the value is to be converted to an alternative form. For o conversion, it increases the precision (if necessary) to force the first digit of the result to be 0. For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a , A , e , E , f , F , g , and G conversion specifiers, the result shall always contain a radix character, even if no digits follow it. Without this flag, a radix character appears in the result of these conversions only if a digit follows it. For g and G conversion specifiers, trailing zeros shall not be removed from the result as they normally are. For other conversion specifiers, the behavior is undefined.
0
For d , i , o , u , x , X , a , A , e , E , f , F , g , and G conversion specifiers, leading zeros (following any indication of sign or base) are used to pad to the field width; no space padding is performed. If the '0' and '-' flags both appear, the '0' flag shall be ignored. For d , i , o , u , x , and X conversion specifiers, if a precision is specified, the '0' flag shall be ignored. If the '0' and '" flags both appear, the grouping wide characters are inserted before zero padding. For other conversions, the behavior is undefined.

The length modifiers and their meanings are:

hh
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.
h
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a short or unsigned short argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to short or unsigned short before printing); or that a following n conversion specifier applies to a pointer to a short argument.
l (ell)
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a long or unsigned long argument; that a following n conversion specifier applies to a pointer to a long argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a , A , e , E , f , F , g , or G conversion specifier.
ll (ell-ell)

Specifies that a following d , i , o , u , x , or X conversion specifier applies to a long long or unsigned long long argument; or that a following n conversion specifier applies to a pointer to a long long argument.

j
Specifies that a following d , i , o , u , x , or X conversion specifier applies to an intmax_t or uintmax_t argument; or that a following n conversion specifier applies to a pointer to an intmax_t argument.
z
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a size_t or the corresponding signed integer type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to a size_t argument.
t
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.
L
Specifies that a following a , A , e , E , f , F , g , or G conversion specifier applies to a long double argument.

If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.

The conversion specifiers and their meanings are:

d, i
The int argument shall be converted to a signed decimal in the style "[-]dddd". The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision shall be 1. The result of converting zero with an explicit precision of zero shall be no wide characters.
o
The unsigned argument shall be converted to unsigned octal format in the style "dddd" . The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision shall be 1. The result of converting zero with an explicit precision of zero shall be no wide characters.
u
The unsigned argument shall be converted to unsigned decimal format in the style "dddd" . The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision shall be 1. The result of converting zero with an explicit precision of zero shall be no wide characters.
x
The unsigned argument shall be converted to unsigned hexadecimal format in the style "dddd" ; the letters "abcdef" are used. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision shall be 1. The result of converting zero with an explicit precision of zero shall be no wide characters.
X
Equivalent to the x conversion specifier, except that letters "ABCDEF" are used instead of "abcdef" .
f, F
The double argument shall be converted to decimal notation in the style "[-]ddd.ddd", where the number of digits after the radix character shall be equal to the precision specification. If the precision is missing, it shall be taken as 6; if the precision is explicitly zero and no '#' flag is present, no radix character shall appear. If a radix character appears, at least one digit shall appear before it. The value shall be rounded in an implementation-defined manner to the appropriate number of digits.

A double argument representing an infinity shall be converted in one of the styles "[-]inf" or "[-]infinity" ; which style is implementation-defined. A double argument representing a NaN shall be converted in one of the styles "[-]nan" or "[-]nan(n-char-sequence)"; which style, and the meaning of any n-char-sequence, is implementation-defined. The F conversion specifier produces "INF" , "INFINITY" , or "NAN" instead of "inf" , "infinity" , or "nan" , respectively.

e, E
The double argument shall be converted in the style "[-]d.ddde±dd", where there shall be one digit before the radix character (which is non-zero if the argument is non-zero) and the number of digits after it shall be equal to the precision; if the precision is missing, it shall be taken as 6; if the precision is zero and no '#' flag is present, no radix character shall appear. The value shall be rounded in an implementation-defined manner to the appropriate number of digits. The E conversion wide character shall produce a number with 'E' instead of 'e' introducing the exponent. The exponent shall always contain at least two digits. If the value is zero, the exponent shall be zero.

A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier.

g, G
The double argument shall be converted in the style f or e (or in the style F or E in the case of a G conversion specifier), with the precision specifying the number of significant digits. If an explicit precision is zero, it shall be taken as 1. The style used depends on the value converted; style e (or E ) shall be used only if the exponent resulting from such a conversion is less than -4 or greater than or equal to the precision. Trailing zeros shall be removed from the fractional portion of the result; a radix character shall appear only if it is followed by a digit.

A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier.

a, A
A double argument representing a floating-point number shall be converted in the style "[-]0xh.hhhhp±d", where there shall be one hexadecimal digit (which is non-zero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point wide character and the number of hexadecimal digits after it shall be equal to the precision; if the precision is missing and FLT_RADIX is a power of 2, then the precision shall be sufficient for an exact representation of the value; if the precision is missing and FLT_RADIX is not a power of 2, then the precision shall be sufficient to distinguish values of type double, except that trailing zeros may be omitted; if the precision is zero and the '#' flag is not specified, no decimal-point wide character shall appear. The letters "abcdef" are used for a conversion and the letters "ABCDEF" for A conversion. The A conversion specifier produces a number with 'X' and 'P' instead of 'x' and 'p' . The exponent shall always contain at least one digit, and only as many more digits as necessary to represent the decimal exponent of 2. If the value is zero, the exponent shall be zero.

A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier.

c
If no l (ell) qualifier is present, the int argument shall be converted to a wide character as if by calling the btowc() function and the resulting wide character shall be written. Otherwise, the wint_t argument shall be converted to wchar_t, and written.
s
If no l (ell) qualifier is present, the application shall ensure that the argument is a pointer to a character array containing a character sequence beginning in the initial shift state. Characters from the array shall be converted as if by repeated calls to the mbrtowc() function, with the conversion state described by an mbstate_t object initialized to zero before the first character is converted, and written up to (but not including) the terminating null wide character. If the precision is specified, no more than that many wide characters shall be written. If the precision is not specified, or is greater than the size of the array, the application shall ensure that the array contains a null wide character.

If an l (ell) qualifier is present, the application shall ensure that the argument is a pointer to an array of type wchar_t. Wide characters from the array shall be written up to (but not including) a terminating null wide character. If no precision is specified, or is greater than the size of the array, the application shall ensure that the array contains a null wide character. If a precision is specified, no more than that many wide characters shall be written.

p
The application shall ensure that the argument is a pointer to void. The value of the pointer shall be converted to a sequence of printable wide characters in an implementation-defined manner.
n
The application shall ensure that the argument is a pointer to an integer into which is written the number of wide characters written to the output so far by this call to one of the fwprintf() functions. No argument shall be converted, but one shall be consumed. If the conversion specification includes any flags, a field width, or a precision, the behavior is undefined.
C
Equivalent to lc .
S
Equivalent to ls .
%
Output a '%' wide character; no argument shall be converted. The entire conversion specification shall be %% .

If a conversion specification does not match one of the above forms, the behavior is undefined.

In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field shall be expanded to contain the conversion result. Characters generated by fwprintf() and wprintf() shall be printed as if fputwc() had been called.

For a and A conversions, if FLT_RADIX is not a power of 2 and the result is not exactly representable in the given precision, the result should be one of the two adjacent numbers in hexadecimal floating style with the given precision, with the extra stipulation that the error should have a correct sign for the current rounding direction.

For e , E , f , F , g , and G conversion specifiers, if the number of significant decimal digits is at most DECIMAL_DIG, then the result should be correctly rounded. If the number of significant decimal digits is more than DECIMAL_DIG but the source value is exactly representable with DECIMAL_DIG digits, then the result should be an exact representation with trailing zeros. Otherwise, the source value is bounded by two adjacent decimal strings L < U, both having DECIMAL_DIG significant digits; the value of the resultant decimal string D should satisfy L <= D <= U, with the extra stipulation that the error should have a correct sign for the current rounding direction.

The st_ctime and st_mtime fields of the file shall be marked for update between the call to a successful execution of fwprintf() or wprintf() and the next successful completion of a call to fflush() or fclose() on the same stream, or a call to exit() or abort().

RETURN VALUE

Upon successful completion, these functions shall return the number of wide characters transmitted, excluding the terminating null wide character in the case of swprintf(), or a negative value if an output error was encountered, and set errno to indicate the error.

If n or more wide characters were requested to be written, swprintf() shall return a negative value, and set errno to indicate the error.

ERRORS

For the conditions under which fwprintf() and wprintf() fail and may fail, refer to fputwc() .

In addition, all forms of fwprintf() may fail if:

EILSEQ
A wide-character code that does not correspond to a valid character has been detected.
EINVAL
There are insufficient arguments.

In addition, wprintf() and fwprintf() may fail if:

ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

To print the language-independent date and time format, the following statement could be used:

wprintf(format, weekday, month, day, hour, min);

For American usage, format could be a pointer to the wide-character string:

L"%s, %s %d, %d:%.2d\n"

producing the message:

Sunday, July 3, 10:02

whereas for German usage, format could be a pointer to the wide-character string:

L"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"

producing the message:

Sonntag, 3. Juli, 10:02

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

btowc() , fputwc() , fwscanf() , mbrtowc() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlock_init(3p)

PTHREAD_RWLOCK_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlock_destroy, pthread_rwlock_init - destroy and initialize a read-write lock object

SYNOPSIS

#include <pthread.h>

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr);

DESCRIPTION

The pthread_rwlock_destroy() function shall destroy the read-write lock object referenced by rwlock and release any resources used by the lock. The effect of subsequent use of the lock is undefined until the lock is reinitialized by another call to pthread_rwlock_init(). An implementation may cause pthread_rwlock_destroy() to set the object referenced by rwlock to an invalid value. Results are undefined if pthread_rwlock_destroy() is called when any thread holds rwlock. Attempting to destroy an uninitialized read-write lock results in undefined behavior.

The pthread_rwlock_init() function shall allocate any resources required to use the read-write lock referenced by rwlock and initializes the lock to an unlocked state with attributes referenced by attr. If attr is NULL, the default read-write lock attributes shall be used; the effect is the same as passing the address of a default read-write lock attributes object. Once initialized, the lock can be used any number of times without being reinitialized. Results are undefined if pthread_rwlock_init() is called specifying an already initialized read-write lock. Results are undefined if a read-write lock is used without first being initialized.

If the pthread_rwlock_init() function fails, rwlock shall not be initialized and the contents of rwlock are undefined.

Only the object referenced by rwlock may be used for performing synchronization. The result of referring to copies of that object in calls to pthread_rwlock_destroy(), pthread_rwlock_rdlock(), pthread_rwlock_timedrdlock(), pthread_rwlock_timedwrlock(), pthread_rwlock_tryrdlock(), pthread_rwlock_trywrlock(), pthread_rwlock_unlock(), or pthread_rwlock_wrlock() is undefined.

RETURN VALUE

If successful, the pthread_rwlock_destroy() and pthread_rwlock_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

The [EBUSY] and [EINVAL] error checks, if implemented, act as if they were performed immediately at the beginning of processing for the function and caused an error return prior to modifying the state of the read-write lock specified by rwlock.

ERRORS

The pthread_rwlock_destroy() function may fail if:

EBUSY
The implementation has detected an attempt to destroy the object referenced by rwlock while it is locked.
EINVAL
The value specified by rwlock is invalid.

The pthread_rwlock_init() function shall fail if:

EAGAIN
The system lacked the necessary resources (other than memory) to initialize another read-write lock.
ENOMEM
Insufficient memory exists to initialize the read-write lock.
EPERM
The caller does not have the privilege to perform the operation.

The pthread_rwlock_init() function may fail if:

EBUSY
The implementation has detected an attempt to reinitialize the object referenced by rwlock, a previously initialized but not yet destroyed read-write lock.
EINVAL
The value specified by attr is invalid.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these and related read-write lock functions may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_rdlock() , pthread_rwlock_timedrdlock()
, pthread_rwlock_timedwrlock() , pthread_rwlock_tryrdlock()
, pthread_rwlock_trywrlock() , pthread_rwlock_unlock()
, pthread_rwlock_wrlock() , the Base Definitions volume of IEEE Std 1003.1-2001,
<pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctime(3p)

CTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ctime, ctime_r - convert a time value to a date and time string

SYNOPSIS

#include <time.h>

char *ctime(const time_t *clock);

char *ctime_r(const time_t *clock, char *buf);

DESCRIPTION

For ctime(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The ctime() function shall convert the time pointed to by clock, representing time in seconds since the Epoch, to local time in the form of a string. It shall be equivalent to:

asctime(localtime(clock))

The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.

The ctime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The ctime_r() function shall convert the calendar time pointed to by clock to local time in exactly the same form as ctime() and put the string into the array pointed to by buf (which shall be at least 26 bytes in size) and return buf.

Unlike ctime(), the thread-safe version ctime_r() is not required to set tzname.

RETURN VALUE

The ctime() function shall return the pointer returned by asctime() with that broken-down time as an argument.

Upon successful completion, ctime_r() shall return a pointer to the string pointed to by buf. When an error is encountered, a null pointer shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Values for the broken-down time structure can be obtained by calling gmtime() or localtime(). The ctime() function is included for compatibility with older implementations, and does not support localized date and time formats. Applications should use the strftime() function to achieve maximum portability.

The ctime_r() function is thread-safe and shall return values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asctime() , clock() , difftime() , gmtime() , localtime() , mktime() , strftime() , strptime() , time() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vsscanf (3p)

 Continue to this page.


labs(3p)

LABS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

labs, llabs - return a long integer absolute value

SYNOPSIS

#include <stdlib.h>

long labs(long i);
long long llabs(long long i);

DESCRIPTION

The labs() function shall compute the absolute value of the long integer operand i. The llabs() function shall compute the absolute value of the long long integer operand i. If the result cannot be represented, the behavior is undefined.

RETURN VALUE

The labs() function shall return the absolute value of the long integer operand. The labs() function shall return the absolute value of the long long integer operand.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

abs() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


y0(3p)

Y0

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

y0, y1, yn - Bessel functions of the second kind

SYNOPSIS

#include <math.h>

double y0(double x);
double y1(double x);
double yn(int n, double x);

DESCRIPTION

The y0(), y1(), and yn() functions shall compute Bessel functions of x of the second kind of orders 0, 1, and n, respectively.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the relevant Bessel value of x of the second kind.

If x is NaN, NaN shall be returned.

If the x argument to these functions is negative, -HUGE_VAL or NaN shall be returned, and a domain error may occur.

If x is 0.0, -HUGE_VAL shall be returned and a range error may occur.

If the correct result would cause underflow, 0.0 shall be returned and a range error may occur.

If the correct result would cause overflow, -HUGE_VAL or 0.0 shall be returned and a range error may occur.

ERRORS

These functions may fail if:

Domain Error
The value of x is negative.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Range Error
The value of x is 0.0, or the correct result would cause overflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

Range Error
The value of x is too large in magnitude, or the correct result would cause underflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , j0() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


y1 (3p)

 Continue to this page.


rint(3p)

RINT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rint, rintf, rintl - round-to-nearest integral value

SYNOPSIS

#include <math.h>

double rint(double x);
float rintf(float x);
long double rintl(long double x);

DESCRIPTION

These functions shall return the integral value (represented as a double) nearest x in the direction of the current rounding mode. The current rounding mode is implementation-defined.

If the current rounding mode rounds toward negative infinity, then rint() shall be equivalent to floor() . If the current rounding mode rounds toward positive infinity, then rint() shall be equivalent to ceil() .

These functions differ from the nearbyint(), nearbyintf(), and nearbyintl() functions only in that they may raise the inexact floating-point exception if the result differs in value from the argument.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the integer (represented as a double precision number) nearest x in the direction of the current rounding mode.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

If the correct value would cause overflow, a range error shall occur and rint(), rintf(), and rintl() shall return the value of the macro ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (with the same sign as x), respectively.

ERRORS

These functions shall fail if:

Range Error
The result would cause an overflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

abs() , ceil() , feclearexcept() , fetestexcept() , floor() , isnan() , nearbyint() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


endnetent (3p)

 Continue to this page.


sprintf (3p)

 Continue to this page.


pthread_getcpuclockid(3p)

PTHREAD_GETCPUCLOCKID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_getcpuclockid - access a thread CPU-time clock (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>
#include <time.h>

int pthread_getcpuclockid(pthread_t thread_id, clockid_t *clock_id);

DESCRIPTION

The pthread_getcpuclockid() function shall return in clock_id the clock ID of the CPU-time clock of the thread specified by thread_id, if the thread specified by thread_id exists.

RETURN VALUE

Upon successful completion, pthread_getcpuclockid() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_getcpuclockid() function may fail if:

ESRCH
The value specified by thread_id does not refer to an existing thread.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_getcpuclockid() function is part of the Thread CPU-Time Clocks option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clock_getcpuclockid() , clock_getres() , timer_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mbrtowc(3p)

MBRTOWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mbrtowc - convert a character to a wide-character code (restartable)

SYNOPSIS

#include <wchar.h>

size_t mbrtowc(wchar_t *restrict pwc, const char *restrict s,
size_t n, mbstate_t *restrict ps);

DESCRIPTION

If s is a null pointer, the mbrtowc() function shall be equivalent to the call:

mbrtowc(NULL, "", 1, ps)

In this case, the values of the arguments pwc and n are ignored.

If s is not a null pointer, the mbrtowc() function shall inspect at most n bytes beginning at the byte pointed to by s to determine the number of bytes needed to complete the next character (including any shift sequences). If the function determines that the next character is completed, it shall determine the value of the corresponding wide character and then, if pwc is not a null pointer, shall store that value in the object pointed to by pwc. If the corresponding wide character is the null wide character, the resulting state described shall be the initial conversion state.

If ps is a null pointer, the mbrtowc() function shall use its own internal mbstate_t object, which shall be initialized at program start-up to the initial conversion state. Otherwise, the mbstate_t object pointed to by ps shall be used to completely describe the current conversion state of the associated character sequence. The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls mbrtowc().

The behavior of this function is affected by the LC_CTYPE category of the current locale.

RETURN VALUE

The mbrtowc() function shall return the first of the following that applies:

0
If the next n or fewer bytes complete the character that corresponds to the null wide character (which is the value stored).
between 1 and n inclusive

If the next n or fewer bytes complete a valid character (which is the value stored); the value returned shall be the number of bytes that complete the character.

(size_t)-2
If the next n bytes contribute to an incomplete but potentially valid character, and all n bytes have been processed (no value is stored). When n has at least the value of the {MB_CUR_MAX} macro, this case can only occur if s points at a sequence of redundant shift sequences (for implementations with state-dependent encodings).
(size_t)-1
If an encoding error occurs, in which case the next n or fewer bytes do not contribute to a complete and valid character (no value is stored). In this case, [EILSEQ] shall be stored in errno and the conversion state is undefined.

ERRORS

The mbrtowc() function may fail if:

EINVAL
ps points to an object that contains an invalid conversion state.
EILSEQ
Invalid character sequence is detected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mbsinit() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mbtowc(3p)

MBTOWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mbtowc - convert a character to a wide-character code

SYNOPSIS

#include <stdlib.h>

int mbtowc(wchar_t *restrict pwc, const char *restrict s, size_t n);

DESCRIPTION

If s is not a null pointer, mbtowc() shall determine the number of bytes that constitute the character pointed to by s. It shall then determine the wide-character code for the value of type wchar_t that corresponds to that character. (The value of the wide-character code corresponding to the null byte is 0.) If the character is valid and pwc is not a null pointer, mbtowc() shall store the wide-character code in the object pointed to by pwc.

The behavior of this function is affected by the LC_CTYPE category of the current locale. For a state-dependent encoding, this function is placed into its initial state by a call for which its character pointer argument, s, is a null pointer. Subsequent calls with s as other than a null pointer shall cause the internal state of the function to be altered as necessary. A call with s as a null pointer shall cause this function to return a non-zero value if encodings have state dependency, and 0 otherwise. If the implementation employs special bytes to change the shift state, these bytes shall not produce separate wide-character codes, but shall be grouped with an adjacent character. Changing the LC_CTYPE category causes the shift state of this function to be unspecified. At most n bytes of the array pointed to by s shall be examined.

The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls mbtowc().

RETURN VALUE

If s is a null pointer, mbtowc() shall return a non-zero or 0 value, if character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, mbtowc() shall either return 0 (if s points to the null byte), or return the number of bytes that constitute the converted character (if the next n or fewer bytes form a valid character), or return -1 and may set errno to indicate the error (if they do not form a valid character).

In no case shall the value returned be greater than n or the value of the {MB_CUR_MAX} macro.

ERRORS

The mbtowc() function may fail if:

EILSEQ
Invalid character sequence is detected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mblen() , mbstowcs() , wctomb() , wcstombs() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


expm1f (3p)

 Continue to this page.


ldexp(3p)

LDEXP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ldexp, ldexpf, ldexpl - load exponent of a floating-point number

SYNOPSIS

#include <math.h>

double ldexp(double x, int exp);
float ldexpf(float x, int exp);
long double ldexpl(long double x, int exp);

DESCRIPTION

These functions shall compute the quantity x * 2**exp.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return x multiplied by 2, raised to the power exp.

If these functions would cause overflow, a range error shall occur and ldexp(), ldexpf(), and ldexpl() shall return ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (according to the sign of x), respectively.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

If exp is 0, x shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

ERRORS

These functions shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , frexp() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


expm1l (3p)

 Continue to this page.


pthread_key_create(3p)

PTHREAD_KEY_CREATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_key_create - thread-specific data key creation

SYNOPSIS

#include <pthread.h>

int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

DESCRIPTION

The pthread_key_create() function shall create a thread-specific data key visible to all threads in the process. Key values provided by pthread_key_create() are opaque objects used to locate thread-specific data. Although the same key value may be used by different threads, the values bound to the key by pthread_setspecific() are maintained on a per-thread basis and persist for the life of the calling thread.

Upon key creation, the value NULL shall be associated with the new key in all active threads. Upon thread creation, the value NULL shall be associated with all defined keys in the new thread.

An optional destructor function may be associated with each key value. At thread exit, if a key value has a non-NULL destructor pointer, and the thread has a non-NULL value associated with that key, the value of the key is set to NULL, and then the function pointed to is called with the previously associated value as its sole argument. The order of destructor calls is unspecified if more than one destructor exists for a thread when it exits.

If, after all the destructors have been called for all non-NULL values with associated destructors, there are still some non-NULL values with associated destructors, then the process is repeated. If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor calls for outstanding non-NULL values, there are still some non-NULL values with associated destructors, implementations may stop calling destructors, or they may continue calling destructors until no non-NULL values with associated destructors exist, even though this might result in an infinite loop.

RETURN VALUE

If successful, the pthread_key_create() function shall store the newly created key value at *key and shall return zero. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_key_create() function shall fail if:

EAGAIN
The system lacked the necessary resources to create another thread-specific data key, or the system-imposed limit on the total number of keys per process {PTHREAD_KEYS_MAX} has been exceeded.
ENOMEM
Insufficient memory exists to create the key.

The pthread_key_create() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

The following example demonstrates a function that initializes a thread-specific data key when it is first called, and associates a thread-specific object with each calling thread, initializing this object when necessary.

static pthread_key_t key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;

static void
make_key()
{
    (void) pthread_key_create(&key, NULL);
}

func()
{
    void *ptr;

    (void) pthread_once(&key_once, make_key);
    if ((ptr = pthread_getspecific(key)) == NULL) {
        ptr = malloc(OBJECT_SIZE);
        ...
        (void) pthread_setspecific(key, ptr);
    }
    ...
}

Note that the key has to be initialized before pthread_getspecific() or pthread_setspecific() can be used. The pthread_key_create() call could either be explicitly made in a module initialization routine, or it can be done implicitly by the first call to a module as in this example. Any attempt to use the key before it is initialized is a programming error, making the code below incorrect.

static pthread_key_t key;

func()
{
    void *ptr;

   /* KEY NOT INITIALIZED!!!  THIS WON'T WORK!!! */
    if ((ptr = pthread_getspecific(key)) == NULL &&
        pthread_setspecific(key, NULL) != 0) {
        pthread_key_create(&key, NULL);
        ...
    }
}

APPLICATION USAGE

None.

RATIONALE

Destructor Functions

Normally, the value bound to a key on behalf of a particular thread is a pointer to storage allocated dynamically on behalf of the calling thread. The destructor functions specified with pthread_key_create() are intended to be used to free this storage when the thread exits. Thread cancellation cleanup handlers cannot be used for this purpose because thread-specific data may persist outside the lexical scope in which the cancellation cleanup handlers operate.

If the value associated with a key needs to be updated during the lifetime of the thread, it may be necessary to release the storage associated with the old value before the new value is bound. Although the pthread_setspecific() function could do this automatically, this feature is not needed often enough to justify the added complexity. Instead, the programmer is responsible for freeing the stale storage:

pthread_getspecific(key, &old);
new = allocate();
destructor(old);
pthread_setspecific(key, new);
Note:
The above example could leak storage if run with asynchronous cancellation enabled. No such problems occur in the default cancellation state if no cancellation points occur between the get and set.

There is no notion of a destructor-safe function. If an application does not call pthread_exit() from a signal handler, or if it blocks any signal whose handler may call pthread_exit() while calling async-unsafe functions, all functions may be safely called from destructors.

Non-Idempotent Data Key Creation

There were requests to make pthread_key_create() idempotent with respect to a given key address parameter. This would allow applications to call pthread_key_create() multiple times for a given key address and be guaranteed that only one key would be created. Doing so would require the key value to be previously initialized (possibly at compile time) to a known null value and would require that implicit mutual-exclusion be performed based on the address and contents of the key parameter in order to guarantee that exactly one key would be created.

Unfortunately, the implicit mutual-exclusion would not be limited to only pthread_key_create(). On many implementations, implicit mutual-exclusion would also have to be performed by pthread_getspecific() and pthread_setspecific() in order to guard against using incompletely stored or not-yet-visible key values. This could significantly increase the cost of important operations, particularly pthread_getspecific().

Thus, this proposal was rejected. The pthread_key_create() function performs no implicit synchronization. It is the responsibility of the programmer to ensure that it is called exactly once per key before use of the key. Several straightforward mechanisms can already be used to accomplish this, including calling explicit module initialization functions, using mutexes, and using pthread_once(). This places no significant burden on the programmer, introduces no possibly confusing ad hoc implicit synchronization mechanism, and potentially allows commonly used thread-specific data operations to be more efficient.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_getspecific() , pthread_key_delete() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strlen(3p)

STRLEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strlen - get string length

SYNOPSIS

#include <string.h>

size_t strlen(const char *s);

DESCRIPTION

The strlen() function shall compute the number of bytes in the string to which s points, not including the terminating null byte.

RETURN VALUE

The strlen() function shall return the length of s; no return value shall be reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Getting String Lengths

The following example sets the maximum length of key and data by using strlen() to get the lengths of those strings.

#include <string.h>
...
struct element {
    char *key;
    char *data;
};
...
char *key, *data;
int len;

*keylength = *datalength = 0;
...
if ((len = strlen(key)) > *keylength)
    *keylength = len;
if ((len = strlen(data)) > *datalength)
    *datalength = len;
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


yn (3p)

 Continue to this page.


getcontext(3p)

GETCONTEXT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getcontext, setcontext - get and set current user context

SYNOPSIS

#include <ucontext.h>

int getcontext(ucontext_t *ucp);
int setcontext(const ucontext_t *ucp);

DESCRIPTION

The getcontext() function shall initialize the structure pointed to by ucp to the current user context of the calling thread. The ucontext_t type that ucp points to defines the user context and includes the contents of the calling thread's machine registers, the signal mask, and the current execution stack.

The setcontext() function shall restore the user context pointed to by ucp. A successful call to setcontext() shall not return; program execution resumes at the point specified by the ucp argument passed to setcontext(). The ucp argument should be created either by a prior call to getcontext() or makecontext(), or by being passed as an argument to a signal handler. If the ucp argument was created with getcontext(), program execution continues as if the corresponding call of getcontext() had just returned. If the ucp argument was created with makecontext(), program execution continues with the function passed to makecontext(). When that function returns, the thread shall continue as if after a call to setcontext() with the ucp argument that was input to makecontext(). If the uc_link member of the ucontext_t structure pointed to by the ucp argument is equal to 0, then this context is the main context, and the thread shall exit when this context returns. The effects of passing a ucp argument obtained from any other source are unspecified.

RETURN VALUE

Upon successful completion, setcontext() shall not return and getcontext() shall return 0; otherwise, a value of -1 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Refer to makecontext() .

APPLICATION USAGE

When a signal handler is executed, the current user context is saved and a new context is created. If the thread leaves the signal handler via longjmp(), then it is unspecified whether the context at the time of the corresponding setjmp() call is restored and thus whether future calls to getcontext() provide an accurate representation of the current context, since the context restored by longjmp() does not necessarily contain all the information that setcontext() requires. Signal handlers should use siglongjmp() or setcontext() instead.

Conforming applications should not modify or access the uc_mcontext member of ucontext_t. A conforming application cannot assume that context includes any process-wide static data, possibly including errno. Users manipulating contexts should take care to handle these explicitly when required.

Use of contexts to create alternate stacks is not defined by this volume of IEEE Std 1003.1-2001.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

bsd_signal() , makecontext() , setcontext() , setjmp() , sigaction() , sigaltstack() , siglongjmp() , sigprocmask() , sigsetjmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <ucontext.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswspace(3p)

ISWSPACE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswspace - test for a white-space wide-character code

SYNOPSIS

#include <wctype.h>

int iswspace(wint_t wc);

DESCRIPTION

The iswspace() function shall test whether wc is a wide-character code representing a character of class space in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswspace() function shall return non-zero if wc is a white-space wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isfinite(3p)

ISFINITE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isfinite - test for finite value

SYNOPSIS

#include <math.h>

int isfinite(real-floating x);

DESCRIPTION

The isfinite() macro shall determine whether its argument has a finite value (zero, subnormal, or normal, and not infinite or NaN). First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.

RETURN VALUE

The isfinite() macro shall return a non-zero value if and only if its argument has a finite value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fpclassify() , isinf() , isnan() , isnormal() , signbit() , the Base Definitions volume of IEEE Std 1003.1-2001 <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


clock_getcpuclockid(3p)

CLOCK_GETCPUCLOCKID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

clock_getcpuclockid - access a process CPU-time clock (ADVANCED REALTIME)

SYNOPSIS

#include <time.h>

int clock_getcpuclockid(pid_t pid, clockid_t *clock_id);

DESCRIPTION

The clock_getcpuclockid() function shall return the clock ID of the CPU-time clock of the process specified by pid. If the process described by pid exists and the calling process has permission, the clock ID of this clock shall be returned in clock_id.

If pid is zero, the clock_getcpuclockid() function shall return the clock ID of the CPU-time clock of the process making the call, in clock_id.

The conditions under which one process has permission to obtain the CPU-time clock ID of other processes are implementation-defined.

RETURN VALUE

Upon successful completion, clock_getcpuclockid() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The clock_getcpuclockid() function shall fail if:

EPERM
The requesting process does not have permission to access the CPU-time clock for the process.

The clock_getcpuclockid() function may fail if:

ESRCH
No process can be found corresponding to the process specified by pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The clock_getcpuclockid() function is part of the Process CPU-Time Clocks option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clock_getres() , timer_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


bcopy(3p)

BCOPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bcopy - memory operations (LEGACY)

SYNOPSIS

#include <strings.h>

void bcopy(const void *s1, void *s2, size_t n);

DESCRIPTION

The bcopy() function shall copy n bytes from the area pointed to by s1 to the area pointed to by s2.

The bytes are copied correctly even if the area pointed to by s1 overlaps the area pointed to by s2.

RETURN VALUE

The bcopy() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The memmove() function is preferred over this function.

The following are approximately equivalent (note the order of the arguments):

bcopy(s1,s2,n) ~= memmove(s2,s1,n)

For maximum portability, it is recommended to replace the function call to bcopy() as follows:

#define bcopy(b1,b2,len) (memmove((b2), (b1), (len)), (void) 0)

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

memmove() , the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutex_timedlock(3p)

PTHREAD_MUTEX_TIMEDLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutex_timedlock - lock a mutex (ADVANCED REALTIME)

SYNOPSIS

#include <pthread.h>
#include <time.h>

int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex,
const struct timespec *restrict abs_timeout);

DESCRIPTION

The pthread_mutex_timedlock() function shall lock the mutex object referenced by mutex. If the mutex is already locked, the calling thread shall block until the mutex becomes available as in the pthread_mutex_lock() function. If the mutex cannot be locked without waiting for another thread to unlock the mutex, this wait shall be terminated when the specified timeout expires.

The timeout shall expire when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call.

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock; if the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function.

The resolution of the timeout shall be the resolution of the clock on which it is based. The timespec data type is defined in the <time.h> header.

Under no circumstance shall the function fail with a timeout if the mutex can be locked immediately. The validity of the abs_timeout parameter need not be checked if the mutex can be locked immediately.

As a consequence of the priority inheritance rules (for mutexes initialized with the PRIO_INHERIT protocol), if a timed mutex wait is terminated because its timeout expires, the priority of the owner of the mutex shall be adjusted as necessary to reflect the fact that this thread is no longer among the threads waiting for the mutex.

RETURN VALUE

If successful, the pthread_mutex_timedlock() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_mutex_timedlock() function shall fail if:

EINVAL
The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread's priority is higher than the mutex' current priority ceiling.
EINVAL
The process or thread would have blocked, and the abs_timeout parameter specified a nanoseconds field value less than zero or greater than or equal to 1000 million.
ETIMEDOUT
The mutex could not be locked before the specified timeout expired.

The pthread_mutex_timedlock() function may fail if:

EINVAL
The value specified by mutex does not refer to an initialized mutex object.
EAGAIN
The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.
EDEADLK
The current thread already owns the mutex.

This function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_mutex_timedlock() function is part of the Threads and Timeouts options and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_mutex_destroy() , pthread_mutex_lock() , pthread_mutex_trylock() , time() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswdigit(3p)

ISWDIGIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswdigit - test for a decimal digit wide-character code

SYNOPSIS

#include <wctype.h>

int iswdigit(wint_t wc);

DESCRIPTION

The iswdigit() function shall test whether wc is a wide-character code representing a character of class digit in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswdigit() function shall return non-zero if wc is a decimal digit wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getgroups(3p)

GETGROUPS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getgroups - get supplementary group IDs

SYNOPSIS

#include <unistd.h>

int getgroups(int gidsetsize, gid_t grouplist[]);

DESCRIPTION

The getgroups() function shall fill in the array grouplist with the current supplementary group IDs of the calling process. It is implementation-defined whether getgroups() also returns the effective group ID in the grouplist array.

The gidsetsize argument specifies the number of elements in the array grouplist. The actual number of group IDs stored in the array shall be returned. The values of array entries with indices greater than or equal to the value returned are undefined.

If gidsetsize is 0, getgroups() shall return the number of group IDs that it would otherwise return without modifying the array pointed to by grouplist.

If the effective group ID of the process is returned with the supplementary group IDs, the value returned shall always be greater than or equal to one and less than or equal to the value of {NGROUPS_MAX}+1.

RETURN VALUE

Upon successful completion, the number of supplementary group IDs shall be returned. A return value of -1 indicates failure and errno shall be set to indicate the error.

ERRORS

The getgroups() function shall fail if:

EINVAL
The gidsetsize argument is non-zero and less than the number of group IDs that would have been returned.

The following sections are informative.

EXAMPLES

Getting the Supplementary Group IDs of the Calling Process

The following example places the current supplementary group IDs of the calling process into the group array.

#include <sys/types.h>
#include <unistd.h>
...
gid_t *group;
int nogroups;
long ngroups_max;

ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
group = (gid_t *)malloc(ngroups_max *sizeof(gid_t));

ngroups = getgroups(ngroups_max, group);

APPLICATION USAGE

None.

RATIONALE

The related function setgroups() is a privileged operation and therefore is not covered by this volume of IEEE Std 1003.1-2001.

As implied by the definition of supplementary groups, the effective group ID may appear in the array returned by getgroups() or it may be returned only by getegid(). Duplication may exist, but the application needs to call getegid() to be sure of getting all of the information. Various implementation variations and administrative sequences cause the set of groups appearing in the result of getgroups() to vary in order and as to whether the effective group ID is included, even when the set of groups is the same (in the mathematical sense of "set"). (The history of a process and its parents could affect the details of the result.)

Application writers should note that {NGROUPS_MAX} is not necessarily a constant on all implementations.

FUTURE DIRECTIONS

None.

SEE ALSO

getegid() , setgid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cexpf (3p)

 Continue to this page.


cexpl (3p)

 Continue to this page.


endservent (3p)

 Continue to this page.


posix_typed_mem_get_info(3p)

POSIX_TYPED_MEM_GET_INFO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_typed_mem_get_info - query typed memory information (ADVANCED REALTIME)

SYNOPSIS

#include <sys/mman.h>

int posix_typed_mem_get_info(int fildes,
struct posix_typed_mem_info *info);

DESCRIPTION

The posix_typed_mem_get_info() function shall return, in the posix_tmi_length field of the posix_typed_mem_info structure pointed to by info, the maximum length which may be successfully allocated by the typed memory object designated by fildes. This maximum length shall take into account the flag POSIX_TYPED_MEM_ALLOCATE or POSIX_TYPED_MEM_ALLOCATE_CONTIG specified when the typed memory object represented by fildes was opened. The maximum length is dynamic; therefore, the value returned is valid only while the current mapping of the corresponding typed memory pool remains unchanged.

If fildes represents a typed memory object opened with neither the POSIX_TYPED_MEM_ALLOCATE flag nor the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag specified, the returned value of info->posix_tmi_length is unspecified.

The posix_typed_mem_get_info() function may return additional implementation-defined information in other fields of the posix_typed_mem_info structure pointed to by info.

If the memory object specified by fildes is not a typed memory object, then the behavior of this function is undefined.

RETURN VALUE

Upon successful completion, the posix_typed_mem_get_info() function shall return zero; otherwise, the corresponding error status value shall be returned.

ERRORS

The posix_typed_mem_get_info() function shall fail if:

EBADF
The fildes argument is not a valid open file descriptor.
ENODEV
The fildes argument is not connected to a memory object supported by this function.

This function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

An application that needs to allocate a block of typed memory with length dependent upon the amount of memory currently available must either query the typed memory object to obtain the amount available, or repeatedly invoke mmap() attempting to guess an appropriate length. While the latter method is existing practice with malloc(), it is awkward and imprecise. The posix_typed_mem_get_info() function allows an application to immediately determine available memory. This is particularly important for typed memory objects that may in some cases be scarce resources. Note that when a typed memory pool is a shared resource, some form of mutual-exclusion or synchronization may be required while typed memory is being queried and allocated to prevent race conditions.

The existing fstat() function is not suitable for this purpose. We realize that implementations may wish to provide other attributes of typed memory objects (for example, alignment requirements, page size, and so on). The fstat() function returns a structure which is not extensible and, furthermore, contains substantial information that is inappropriate for typed memory objects.

FUTURE DIRECTIONS

None.

SEE ALSO

fstat() , mmap() , posix_typed_mem_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_condattr_destroy (3p)

 Continue to this page.


stdout (3p)

 Continue to this page.


dbm_delete (3p)

 Continue to this page.


errno(3p)

ERRNO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

errno - error return value

SYNOPSIS

#include <errno.h>

DESCRIPTION

The lvalue errno is used by many functions to return error values.

Many functions provide an error number in errno, which has type int and is defined in <errno.h>. The value of errno shall be defined only after a call to a function for which it is explicitly stated to be set and until it is changed by the next function call or if the application assigns it a value. The value of errno should only be examined when it is indicated to be valid by a function's return value. Applications shall obtain the definition of errno by the inclusion of <errno.h>. No function in this volume of IEEE Std 1003.1-2001 shall set errno to 0.

It is unspecified whether errno is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name errno, the behavior is undefined.

The symbolic values stored in errno are documented in the ERRORS sections on all relevant pages.

RETURN VALUE

None.

ERRORS

None.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Previously both POSIX and X/Open documents were more restrictive than the ISO C standard in that they required errno to be defined as an external variable, whereas the ISO C standard required only that errno be defined as a modifiable lvalue with type int.

An application that needs to examine the value of errno to determine the error should set it to 0 before a function call, then inspect it before a subsequent function call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Error Numbers , the Base Definitions volume of IEEE Std 1003.1-2001, <errno.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tmpnam(3p)

TMPNAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tmpnam - create a name for a temporary file

SYNOPSIS

#include <stdio.h>

char *tmpnam(char *s);

DESCRIPTION

The tmpnam() function shall generate a string that is a valid filename and that is not the same as the name of an existing file. The function is potentially capable of generating {TMP_MAX} different strings, but any or all of them may already be in use by existing files and thus not be suitable return values.

The tmpnam() function generates a different string each time it is called from the same process, up to {TMP_MAX} times. If it is called more than {TMP_MAX} times, the behavior is implementation-defined.

The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls tmpnam().

If the application uses any of the functions guaranteed to be available if either _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS is defined, the application shall ensure that the tmpnam() function is called with a non-NULL parameter.

RETURN VALUE

Upon successful completion, tmpnam() shall return a pointer to a string. If no suitable string can be generated, the tmpnam() function shall return a null pointer.

If the argument s is a null pointer, tmpnam() shall leave its result in an internal static object and return a pointer to that object. Subsequent calls to tmpnam() may modify the same object. If the argument s is not a null pointer, it is presumed to point to an array of at least L_tmpnam chars; tmpnam() shall write its result in that array and shall return the argument as its value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Generating a Filename

The following example generates a unique filename and stores it in the array pointed to by ptr.

#include <stdio.h>
...
char filename[L_tmpnam+1];
char *ptr;

ptr = tmpnam(filename);

APPLICATION USAGE

This function only creates filenames. It is the application's responsibility to create and remove the files.

Between the time a pathname is created and the file is opened, it is possible for some other process to create a file with the same name. Applications may find tmpfile() more useful.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , open() , tempnam() , tmpfile() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


llrint(3p)

LLRINT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

llrint, llrintf, llrintl - round to the nearest integer value using current rounding direction

SYNOPSIS

#include <math.h>

long long llrint(double x);
long long llrintf(float x);
long long llrintl(long double x);

DESCRIPTION

These functions shall round their argument to the nearest integer value, rounding according to the current rounding direction.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the rounded integer value.

If x is NaN, a domain error shall occur, and an unspecified value is returned.

If x is +Inf, a domain error shall occur and an unspecified value is returned.

If x is -Inf, a domain error shall occur and an unspecified value is returned.

If the correct value is positive and too large to represent as a long long, a domain error shall occur and an unspecified value is returned.

If the correct value is negative and too large to represent as a long long, a domain error shall occur and an unspecified value is returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is NaN or ±Inf, or the correct value is not representable as an integer.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

These functions provide floating-to-integer conversions. They round according to the current rounding direction. If the rounded value is outside the range of the return type, the numeric result is unspecified and the invalid floating-point exception is raised. When they raise no other floating-point exception and the result differs from the argument, they raise the inexact floating-point exception.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , lrint() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vsnprintf (3p)

 Continue to this page.


posix_trace_event(3p)

POSIX_TRACE_EVENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_event, posix_trace_eventid_open - trace functions for instrumenting application code (TRACING)

SYNOPSIS

#include <sys/types.h>
#include <trace.h>

void posix_trace_event(trace_event_id_t event_id,
const void *restrict data_ptr, size_t data_len);
int posix_trace_eventid_open(const char *restrict event_name,
trace_event_id_t *restrict event_id);

DESCRIPTION

The posix_trace_event() function shall record the event_id and the user data pointed to by data_ptr in the trace stream into which the calling process is being traced and in which event_id is not filtered out. If the total size of the user trace event data represented by data_len is not greater than the declared maximum size for user trace event data, then the truncation-status attribute of the trace event recorded is POSIX_TRACE_NOT_TRUNCATED. Otherwise, the user trace event data is truncated to this declared maximum size and the truncation-status attribute of the trace event recorded is POSIX_TRACE_TRUNCATED_RECORD.

If there is no trace stream created for the process or if the created trace stream is not running, or if the trace event specified by event_id is filtered out in the trace stream, the posix_trace_event() function shall have no effect.

The posix_trace_eventid_open() function shall associate a user trace event name with a trace event type identifier for the calling process. The trace event name is the string pointed to by the argument event_name. It shall have a maximum of {TRACE_EVENT_NAME_MAX} characters (which has the minimum value {_POSIX_TRACE_EVENT_NAME_MAX}). The number of user trace event type identifiers that can be defined for any given process is limited by the maximum value {TRACE_USER_EVENT_MAX}, which has the minimum value {POSIX_TRACE_USER_EVENT_MAX}.

If the Trace Inherit option is not supported, the posix_trace_eventid_open() function shall associate the user trace event name pointed to by the event_name argument with a trace event type identifier that is unique for the traced process, and is returned in the variable pointed to by the event_id argument. If the user trace event name has already been mapped for the traced process, then the previously assigned trace event type identifier shall be returned. If the per-process user trace event name limit represented by {TRACE_USER_EVENT_MAX} has been reached, the pre-defined POSIX_TRACE_UNNAMED_USEREVENT (see Trace Option: User Trace Event ) user trace event shall be returned.

If the Trace Inherit option is supported, the posix_trace_eventid_open() function shall associate the user trace event name pointed to by the event_name argument with a trace event type identifier that is unique for all the processes being traced in this same trace stream, and is returned in the variable pointed to by the event_id argument. If the user trace event name has already been mapped for the traced processes, then the previously assigned trace event type identifier shall be returned. If the per-process user trace event name limit represented by {TRACE_USER_EVENT_MAX} has been reached, the pre-defined POSIX_TRACE_UNNAMED_USEREVENT ( Trace Option: User Trace Event ) user trace event shall be returned.

Note:
The above procedure, together with the fact that multiple processes can only be traced into the same trace stream by inheritance, ensure that all the processes that are traced into a trace stream have the same mapping of trace event names to trace event type identifiers.

If there is no trace stream created, the posix_trace_eventid_open() function shall store this information for future trace streams created for this process.

RETURN VALUE

No return value is defined for the posix_trace_event() function.

Upon successful completion, the posix_trace_eventid_open() function shall return a value of zero. Otherwise, it shall return the corresponding error number. The posix_trace_eventid_open() function stores the trace event type identifier value in the object pointed to by event_id, if successful.

ERRORS

The posix_trace_eventid_open() function shall fail if:

ENAMETOOLONG
The size of the name pointed to by the event_name argument was longer than the implementation-defined value {TRACE_EVENT_NAME_MAX}.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Trace Option: User Trace Event , posix_trace_start() , posix_trace_trid_eventid_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tcflush(3p)

TCFLUSH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcflush - flush non-transmitted output data, non-read input data, or both

SYNOPSIS

#include <termios.h>

int tcflush(int fildes, int queue_selector);

DESCRIPTION

Upon successful completion, tcflush() shall discard data written to the object referred to by fildes (an open file descriptor associated with a terminal) but not transmitted, or data received but not read, depending on the value of queue_selector:

*
If queue_selector is TCIFLUSH, it shall flush data received but not read.

*
If queue_selector is TCOFLUSH, it shall flush data written but not transmitted.

*
If queue_selector is TCIOFLUSH, it shall flush both data received but not read and data written but not transmitted.

Attempts to use tcflush() from a process which is a member of a background process group on a fildes associated with its controlling terminal shall cause the process group to be sent a SIGTTOU signal. If the calling process is blocking or ignoring SIGTTOU signals, the process shall be allowed to perform the operation, and no signal is sent.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcflush() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINVAL
The queue_selector argument is not a supported value.
ENOTTY
The file associated with fildes is not a terminal.

The tcflush() function may fail if:

EIO
The process group of the writing process is orphaned, and the writing process is not ignoring or blocking SIGTTOU.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

tcdrain() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigfillset(3p)

SIGFILLSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigfillset - initialize and fill a signal set

SYNOPSIS

#include <signal.h>

int sigfillset(sigset_t *set);

DESCRIPTION

The sigfillset() function shall initialize the signal set pointed to by set, such that all signals defined in this volume of IEEE Std 1003.1-2001 are included.

RETURN VALUE

Upon successful completion, sigfillset() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to sigemptyset() .

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , sigaction() , sigaddset() , sigdelset() , sigemptyset() , sigismember() , sigpending() , sigprocmask() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_trygetnext_event (3p)

 Continue to this page.


ecvt(3p)

ECVT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ecvt, fcvt, gcvt - convert a floating-point number to a string (LEGACY)

SYNOPSIS

#include <stdlib.h>

char *ecvt(double value, int ndigit, int *restrict decpt,
int *restrict sign);
char *fcvt(double value, int ndigit, int *restrict decpt,
int *restrict sign);
char *gcvt(double value, int ndigit, char *buf);

DESCRIPTION

The ecvt(), fcvt(), and gcvt() functions shall convert floating-point numbers to null-terminated strings.

The ecvt() function shall convert value to a null-terminated string of ndigit digits (where ndigit is reduced to an unspecified limit determined by the precision of a double) and return a pointer to the string. The high-order digit shall be non-zero, unless the value is 0. The low-order digit shall be rounded in an implementation-defined manner. The position of the radix character relative to the beginning of the string shall be stored in the integer pointed to by decpt (negative means to the left of the returned digits). If value is zero, it is unspecified whether the integer pointed to by decpt would be 0 or 1. The radix character shall not be included in the returned string. If the sign of the result is negative, the integer pointed to by sign shall be non-zero; otherwise, it shall be 0.

If the converted value is out of range or is not representable, the contents of the returned string are unspecified.

The fcvt() function shall be equivalent to ecvt(), except that ndigit specifies the number of digits desired after the radix character. The total number of digits in the result string is restricted to an unspecified limit as determined by the precision of a double.

The gcvt() function shall convert value to a null-terminated string (similar to that of the %g conversion specification format of printf()) in the array pointed to by buf and shall return buf. It shall produce ndigit significant digits (limited to an unspecified value determined by the precision of a double) in the %f conversion specification format of printf() if possible, or the %e conversion specification format of printf() (scientific notation) otherwise. A minus sign shall be included in the returned string if value is less than 0. A radix character shall be included in the returned string if value is not a whole number. Trailing zeros shall be suppressed where value is not a whole number. The radix character is determined by the current locale. If setlocale() has not been called successfully, the default locale, POSIX, is used. The default locale specifies a period ( '.' ) as the radix character. The LC_NUMERIC category determines the value of the radix character within the current locale.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The ecvt() and fcvt() functions shall return a pointer to a null-terminated string of digits.

The gcvt() function shall return buf.

The return values from ecvt() and fcvt() may point to static data which may be overwritten by subsequent calls to these functions.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sprintf() function is preferred over this function.

RATIONALE

None.

FUTURE DIRECTIONS

These functions may be withdrawn in a future version.

SEE ALSO

printf() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setservent (3p)

 Continue to this page.


pthread_rwlockattr_init(3p)

PTHREAD_RWLOCKATTR_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlockattr_destroy, pthread_rwlockattr_init - destroy and initialize the read-write lock attributes object

SYNOPSIS

#include <pthread.h>

int pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr);
int pthread_rwlockattr_init(pthread_rwlockattr_t *attr);

DESCRIPTION

The pthread_rwlockattr_destroy() function shall destroy a read-write lock attributes object. A destroyed attr attributes object can be reinitialized using pthread_rwlockattr_init(); the results of otherwise referencing the object after it has been destroyed are undefined. An implementation may cause pthread_rwlockattr_destroy() to set the object referenced by attr to an invalid value.

The pthread_rwlockattr_init() function shall initialize a read-write lock attributes object attr with the default value for all of the attributes defined by the implementation.

Results are undefined if pthread_rwlockattr_init() is called specifying an already initialized attr attributes object.

After a read-write lock attributes object has been used to initialize one or more read-write locks, any function affecting the attributes object (including destruction) shall not affect any previously initialized read-write locks.

RETURN VALUE

If successful, the pthread_rwlockattr_destroy() and pthread_rwlockattr_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_rwlockattr_destroy() function may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_rwlockattr_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the read-write lock attributes object.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_destroy() , pthread_rwlockattr_getpshared() , pthread_rwlockattr_setpshared() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventtypelist_getnext_id(3p)

POSIX_TRACE_EVENTTYPELIST_GETNEXT_ID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_eventtypelist_getnext_id, posix_trace_eventtypelist_rewind - iterate over a mapping of trace event types (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_eventtypelist_getnext_id(trace_id_t trid,
trace_event_id_t *restrict event, int *restrict unavailable);
int posix_trace_eventtypelist_rewind(trace_id_t trid);

DESCRIPTION

The first time posix_trace_eventtypelist_getnext_id() is called, the function shall return in the variable pointed to by event the first trace event type identifier of the list of trace events of the trace stream identified by the trid argument. Successive calls to posix_trace_eventtypelist_getnext_id() return in the variable pointed to by event the next trace event type identifier in that same list. Each time a trace event type identifier is successfully written into the variable pointed to by the event argument, the variable pointed to by the unavailable argument shall be set to zero. When no more trace event type identifiers are available, and so none is returned, the variable pointed to by the unavailable argument shall be set to a value different from zero.

The posix_trace_eventtypelist_rewind() function shall reset the next trace event type identifier to be read to the first trace event type identifier from the list of trace events used in the trace stream identified by trid.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

The posix_trace_eventtypelist_getnext_id() function stores the trace event type identifier value in the object pointed to by event, if successful.

ERRORS

These functions shall fail if:

EINVAL
The trid argument was not a valid trace stream identifier.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_event() , posix_trace_getnext_event() , posix_trace_trid_eventid_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getnameinfo(3p)

GETNAMEINFO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getnameinfo - get name information

SYNOPSIS

#include <sys/socket.h>
#include <netdb.h>

int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen,
char *restrict node, socklen_t nodelen, char *restrict service,
socklen_t servicelen, int flags);

DESCRIPTION

The getnameinfo() function shall translate a socket address to a node name and service location, all of which are defined as in getaddrinfo() .

The sa argument points to a socket address structure to be translated.

If the socket address structure contains an IPv4-mapped IPv6 address or an IPv4-compatible IPv6 address, the implementation shall extract the embedded IPv4 address and lookup the node name for that IPv4 address.

Note:
The IPv6 unspecified address ( "::" ) and the IPv6 loopback address ( "::1" ) are not IPv4-compatible addresses. If the address is the IPv6 unspecified address ( "::" ), a lookup is not performed, and the [EAI_NONAME] error is returned.

If the node argument is non-NULL and the nodelen argument is non-zero, then the node argument points to a buffer able to contain up to nodelen characters that receives the node name as a null-terminated string. If the node argument is NULL or the nodelen argument is zero, the node name shall not be returned. If the node's name cannot be located, the numeric form of the address contained in the socket address structure pointed to by the sa argument is returned instead of its name.

If the service argument is non-NULL and the servicelen argument is non-zero, then the service argument points to a buffer able to contain up to servicelen bytes that receives the service name as a null-terminated string. If the service argument is NULL or the servicelen argument is zero, the service name shall not be returned. If the service's name cannot be located, the numeric form of the service address (for example, its port number) shall be returned instead of its name.

The flags argument is a flag that changes the default actions of the function. By default the fully-qualified domain name (FQDN) for the host shall be returned, but:

*
If the flag bit NI_NOFQDN is set, only the node name portion of the FQDN shall be returned for local hosts.

*
If the flag bit NI_NUMERICHOST is set, the numeric form of the address contained in the socket address structure pointed to by the sa argument shall be returned instead of its name, under all circumstances.

*
If the flag bit NI_NAMEREQD is set, an error shall be returned if the host's name cannot be located.

*
If the flag bit NI_NUMERICSERV is set, the numeric form of the service address shall be returned (for example, its port number) instead of its name, under all circumstances.

*
If the flag bit NI_NUMERICSCOPE is set, the numeric form of the scope identifier shall be returned (for example, interface index) instead of its name. This flag shall be ignored if the sa argument is not an IPv6 address.

*
If the flag bit NI_DGRAM is set, this indicates that the service is a datagram service (SOCK_DGRAM). The default behavior shall assume that the service is a stream service (SOCK_STREAM).

Notes:
1.
The two NI_NUMERICxxx flags are required to support the -n flag that many commands provide.

2.
The NI_DGRAM flag is required for the few AF_INET and AF_INET6 port numbers (for example, [512,514]) that represent different services for UDP and TCP.

The getnameinfo() function shall be thread-safe.

RETURN VALUE

A zero return value for getnameinfo() indicates successful completion; a non-zero return value indicates failure. The possible values for the failures are listed in the ERRORS section.

Upon successful completion, getnameinfo() shall return the node and service names, if requested, in the buffers provided. The returned names are always null-terminated strings.

ERRORS

The getnameinfo() function shall fail and return the corresponding value if:

EAI_AGAIN
The name could not be resolved at this time. Future attempts may succeed.
EAI_BADFLAGS

The flags had an invalid value.

EAI_FAIL
A non-recoverable error occurred.
EAI_FAMILY
The address family was not recognized or the address length was invalid for the specified family.
EAI_MEMORY
There was a memory allocation failure.
EAI_NONAME
The name does not resolve for the supplied parameters.

NI_NAMEREQD is set and the host's name cannot be located, or both nodename and servname were null.

EAI_OVERFLOW

An argument buffer overflowed. The buffer pointed to by the node argument or the service argument was too small.

EAI_SYSTEM
A system error occurred. The error code can be found in errno.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the returned values are to be used as part of any further name resolution (for example, passed to getaddrinfo()), applications should provide buffers large enough to store any result possible on the system.

Given the IPv4-mapped IPv6 address "::ffff:1.2.3.4" , the implementation performs a lookup as if the socket address structure contains the IPv4 address "1.2.3.4" .

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

gai_strerror() , getaddrinfo() , getservbyname() , inet_ntop() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


msync(3p)

MSYNC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

msync - synchronize memory with physical storage

SYNOPSIS

#include <sys/mman.h>

int msync(void *addr, size_t len, int flags);

DESCRIPTION

The msync() function shall write all modified data to permanent storage locations, if any, in those whole pages containing any part of the address space of the process starting at address addr and continuing for len bytes. If no such storage exists, msync() need not have any effect. If requested, the msync() function shall then invalidate cached copies of data.

The implementation shall require that addr be a multiple of the page size as returned by sysconf().

For mappings to files, the msync() function shall ensure that all write operations are completed as defined for synchronized I/O data integrity completion. It is unspecified whether the implementation also writes out other file attributes. When the msync() function is called on MAP_PRIVATE mappings, any modified data shall not be written to the underlying object and shall not cause such data to be made visible to other processes. It is unspecified whether data in MAP_PRIVATE mappings has any permanent storage locations. The effect of msync() on a shared memory object or a typed memory object is unspecified. The behavior of this function is unspecified if the mapping was not established by a call to mmap().

The flags argument is constructed from the bitwise-inclusive OR of one or more of the following flags defined in the <sys/mman.h> header:
Symbolic Constant | Description
MS_ASYNC | Perform asynchronous writes.
MS_SYNC | Perform synchronous writes.
MS_INVALIDATE | Invalidate cached data.

When MS_ASYNC is specified, msync() shall return immediately once all the write operations are initiated or queued for servicing; when MS_SYNC is specified, msync() shall not return until all write operations are completed as defined for synchronized I/O data integrity completion. Either MS_ASYNC or MS_SYNC is specified, but not both.

When MS_INVALIDATE is specified, msync() shall invalidate all cached copies of mapped data that are inconsistent with the permanent storage locations such that subsequent references shall obtain data that was consistent with the permanent storage locations sometime between the call to msync() and the first subsequent memory reference to the data.

If msync() causes any write to a file, the file's st_ctime and st_mtime fields shall be marked for update.

RETURN VALUE

Upon successful completion, msync() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The msync() function shall fail if:

EBUSY
Some or all of the addresses in the range starting at addr and continuing for len bytes are locked, and MS_INVALIDATE is specified.
EINVAL
The value of flags is invalid.
EINVAL
The value of addr is not a multiple of the page size {PAGESIZE}.
ENOMEM
The addresses in the range starting at addr and continuing for len bytes are outside the range allowed for the address space of a process or specify one or more pages that are not mapped.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The msync() function is only supported if the Memory Mapped Files option and the Synchronized Input and Output option are supported, and thus need not be available on all implementations.

The msync() function should be used by programs that require a memory object to be in a known state; for example, in building transaction facilities.

Normal system activity can cause pages to be written to disk. Therefore, there are no guarantees that msync() is the only control over when pages are or are not written to disk.

RATIONALE

The msync() function writes out data in a mapped region to the permanent storage for the underlying object. The call to msync() ensures data integrity of the file.

After the data is written out, any cached data may be invalidated if the MS_INVALIDATE flag was specified. This is useful on systems that do not support read/write consistency.

FUTURE DIRECTIONS

None.

SEE ALSO

mmap() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


FD_SET (3p)

 Continue to this page.


feupdateenv(3p)

FEUPDATEENV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

feupdateenv - update floating-point environment

SYNOPSIS

#include <fenv.h>

int feupdateenv(const fenv_t *envp);

DESCRIPTION

The feupdateenv() function shall attempt to save the currently raised floating-point exceptions in its automatic storage, attempt to install the floating-point environment represented by the object pointed to by envp, and then attempt to raise the saved floating-point exceptions. The argument envp shall point to an object set by a call to feholdexcept() or fegetenv(), or equal a floating-point environment macro.

RETURN VALUE

The feupdateenv() function shall return a zero value if and only if all the required actions were successfully carried out.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following example shows sample code to hide spurious underflow floating-point exceptions:

#include <fenv.h>
double f(double x)
{
    #pragma STDC FENV_ACCESS ON
    double result;
    fenv_t save_env;
    feholdexcept(&save_env);
    // compute result
    if (/* test spurious underflow */)
    feclearexcept(FE_UNDERFLOW);
    feupdateenv(&save_env);
    return result;
}

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fegetenv() , feholdexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


_longjmp (3p)

 Continue to this page.


vwprintf(3p)

VFWPRINTF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

vfwprintf, vswprintf, vwprintf - wide-character formatted output of a stdarg argument list

SYNOPSIS

#include <stdarg.h>
#include <stdio.h>
#include <wchar.h>

int vfwprintf(FILE *restrict stream, const wchar_t *restrict format,
va_list arg);
int vswprintf(wchar_t *restrict ws, size_t n,
const wchar_t *restrict format, va_list arg);
int vwprintf(const wchar_t *restrict format, va_list arg);

DESCRIPTION

The vfwprintf(), vswprintf(), and vwprintf() functions shall be equivalent to fwprintf(), swprintf(), and wprintf() respectively, except that instead of being called with a variable number of arguments, they are called with an argument list as defined by <stdarg.h>.

These functions shall not invoke the va_end macro. However, as these functions do invoke the va_arg macro, the value of ap after the return is unspecified.

RETURN VALUE

Refer to fwprintf() .

ERRORS

Refer to fwprintf() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions should call va_end(ap) afterwards to clean up.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fwprintf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdarg.h>, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setreuid(3p)

SETREUID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setreuid - set real and effective user IDs

SYNOPSIS

#include <unistd.h>

int setreuid(uid_t ruid, uid_t euid);

DESCRIPTION

The setreuid() function shall set the real and effective user IDs of the current process to the values specified by the ruid and euid arguments. If ruid or euid is -1, the corresponding effective or real user ID of the current process shall be left unchanged.

A process with appropriate privileges can set either ID to any value. An unprivileged process can only set the effective user ID if the euid argument is equal to either the real, effective, or saved user ID of the process.

It is unspecified whether a process without appropriate privileges is permitted to change the real user ID to match the current real, effective, or saved set-user-ID of the process.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The setreuid() function shall fail if:

EINVAL
The value of the ruid or euid argument is invalid or out-of-range.
EPERM
The current process does not have appropriate privileges, and either an attempt was made to change the effective user ID to a value other than the real user ID or the saved set-user-ID or an attempt was made to change the real user ID to a value not permitted by the implementation.

The following sections are informative.

EXAMPLES

Setting the Effective User ID to the Real User ID

The following example sets the effective user ID of the calling process to the real user ID, so that files created later will be owned by the current user.

#include <unistd.h>
#include <sys/types.h>
...
setreuid(getuid(), getuid());
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getegid() , geteuid() , getgid() , getuid() , setegid() , seteuid() , setgid() , setregid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ldiv(3p)

LDIV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ldiv, lldiv - compute quotient and remainder of a long division

SYNOPSIS

#include <stdlib.h>

ldiv_t ldiv(long numer, long denom);
lldiv_t lldiv(long long numer, long long denom);

DESCRIPTION

These functions shall compute the quotient and remainder of the division of the numerator numer by the denominator denom. If the division is inexact, the resulting quotient is the long integer (for the ldiv() function) or long long integer (for the lldiv() function) of lesser magnitude that is the nearest to the algebraic quotient. If the result cannot be represented, the behavior is undefined; otherwise, quot * denom+rem shall equal numer.

RETURN VALUE

The ldiv() function shall return a structure of type ldiv_t, comprising both the quotient and the remainder. The structure shall include the following members, in any order:

long   quot;    /* Quotient */
long   rem;     /* Remainder */

The lldiv() function shall return a structure of type lldiv_t, comprising both the quotient and the remainder. The structure shall include the following members, in any order:

long long   quot;    /* Quotient */
long long   rem;     /* Remainder */

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

div() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vsprintf (3p)

 Continue to this page.


iswgraph(3p)

ISWGRAPH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswgraph - test for a visible wide-character code

SYNOPSIS

#include <wctype.h>

int iswgraph(wint_t wc);

DESCRIPTION

The iswgraph() function shall test whether wc is a wide-character code representing a character of class graph in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswgraph() function shall return non-zero if wc is a wide-character code with a visible representation; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_setsigdefault (3p)

 Continue to this page.


wcscat(3p)

WCSCAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcscat - concatenate two wide-character strings

SYNOPSIS

#include <wchar.h>

wchar_t *wcscat(wchar_t *restrict ws1, const wchar_t *restrict ws2);

DESCRIPTION

The wcscat() function shall append a copy of the wide-character string pointed to by ws2 (including the terminating null wide-character code) to the end of the wide-character string pointed to by ws1. The initial wide-character code of ws2 shall overwrite the null wide-character code at the end of ws1. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The wcscat() function shall return ws1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcsncat() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


recvfrom(3p)

RECVFROM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

recvfrom - receive a message from a socket

SYNOPSIS

#include <sys/socket.h>

ssize_t recvfrom(int socket, void *restrict buffer, size_t length,
int flags, struct sockaddr *restrict address,
socklen_t *restrict address_len);

DESCRIPTION

The recvfrom() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.

The recvfrom() function takes the following arguments:

socket
Specifies the socket file descriptor.
buffer
Points to the buffer where the message should be stored.
length
Specifies the length in bytes of the buffer pointed to by the buffer argument.
flags
Specifies the type of message reception. Values of this argument are formed by logically OR'ing zero or more of the following values:
MSG_PEEK
Peeks at an incoming message. The data is treated as unread and the next recvfrom() or similar function shall still return this data.
MSG_OOB
Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific.
MSG_WAITALL
On SOCK_STREAM sockets this requests that the function block until the full amount of data can be returned. The function may return the smaller amount of data if the socket is a message-based socket, if a signal is caught, if the connection is terminated, if MSG_PEEK was specified, or if an error is pending for the socket.

address
A null pointer, or points to a sockaddr structure in which the sending address is to be stored. The length and format of the address depend on the address family of the socket.
address_len
Specifies the length of the sockaddr structure pointed to by the address argument.

The recvfrom() function shall return the length of the message written to the buffer pointed to by the buffer argument. For message-based sockets, such as SOCK_RAW, SOCK_DGRAM, and SOCK_SEQPACKET, the entire message shall be read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument, the excess bytes shall be discarded. For stream-based sockets, such as SOCK_STREAM, message boundaries shall be ignored. In this case, data shall be returned to the user as soon as it becomes available, and no data shall be discarded.

If the MSG_WAITALL flag is not set, data shall be returned only up to the end of the first message.

Not all protocols provide the source address for messages. If the address argument is not a null pointer and the protocol provides the source address of messages, the source address of the received message shall be stored in the sockaddr structure pointed to by the address argument, and the length of this address shall be stored in the object pointed to by the address_len argument.

If the actual length of the address is greater than the length of the supplied sockaddr structure, the stored address shall be truncated.

If the address argument is not a null pointer and the protocol does not provide the source address of messages, the value stored in the object pointed to by address is unspecified.

If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, recvfrom() shall block until a message arrives. If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, recvfrom() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].

RETURN VALUE

Upon successful completion, recvfrom() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recvfrom() shall return 0. Otherwise, the function shall return -1 and set errno to indicate the error.

ERRORS

The recvfrom() function shall fail if:

EAGAIN or EWOULDBLOCK

The socket's file descriptor is marked O_NONBLOCK and no data is waiting to be received; or MSG_OOB is set and no out-of-band data is available and either the socket's file descriptor is marked O_NONBLOCK or the socket does not support blocking to await out-of-band data.

EBADF
The socket argument is not a valid file descriptor.
ECONNRESET
A connection was forcibly closed by a peer.
EINTR
A signal interrupted recvfrom() before any data was available.
EINVAL
The MSG_OOB flag is set and no out-of-band data is available.
ENOTCONN
A receive is attempted on a connection-mode socket that is not connected.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The specified flags are not supported for this socket type.
ETIMEDOUT
The connection timed out during connection establishment, or due to a transmission timeout on active connection.

The recvfrom() function may fail if:

EIO
An I/O error occurred while reading from or writing to the file system.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The select() and poll() functions can be used to determine when data is available to be received.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

poll() , read() , recv() , recvmsg() , select() , send() , sendmsg() , sendto() , shutdown() , socket() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcschr(3p)

WCSCHR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcschr - wide-character string scanning operation

SYNOPSIS

#include <wchar.h>

wchar_t *wcschr(const wchar_t *ws, wchar_t wc);

DESCRIPTION

The wcschr() function shall locate the first occurrence of wc in the wide-character string pointed to by ws. The application shall ensure that the value of wc is a character representable as a type wchar_t and a wide-character code corresponding to a valid character in the current locale. The terminating null wide-character code is considered to be part of the wide-character string.

RETURN VALUE

Upon completion, wcschr() shall return a pointer to the wide-character code, or a null pointer if the wide-character code is not found.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcsrchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


localeconv(3p)

LOCALECONV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

localeconv - return locale-specific information

SYNOPSIS

#include <locale.h>

struct lconv *localeconv(void);

DESCRIPTION

The localeconv() function shall set the components of an object with the type struct lconv with the values appropriate for the formatting of numeric quantities (monetary and otherwise) according to the rules of the current locale.

The members of the structure with type char * are pointers to strings, any of which (except decimal_point) can point to "" , to indicate that the value is not available in the current locale or is of zero length. The members with type char are non-negative numbers, any of which can be {CHAR_MAX} to indicate that the value is not available in the current locale.

The members include the following:

char *decimal_point

The radix character used to format non-monetary quantities.

char *thousands_sep

The character used to separate groups of digits before the decimal-point character in formatted non-monetary quantities.

char *grouping

A string whose elements taken as one-byte integer values indicate the size of each group of digits in formatted non-monetary quantities.

char *int_curr_symbol

The international currency symbol applicable to the current locale. The first three characters contain the alphabetic international currency symbol in accordance with those specified in the ISO 4217:1995 standard. The fourth character (immediately preceding the null byte) is the character used to separate the international currency symbol from the monetary quantity.

char *currency_symbol

The local currency symbol applicable to the current locale.

char *mon_decimal_point

The radix character used to format monetary quantities.

char *mon_thousands_sep

The separator for groups of digits before the decimal-point in formatted monetary quantities.

char *mon_grouping

A string whose elements taken as one-byte integer values indicate the size of each group of digits in formatted monetary quantities.

char *positive_sign

The string used to indicate a non-negative valued formatted monetary quantity.

char *negative_sign

The string used to indicate a negative valued formatted monetary quantity.

char int_frac_digits

The number of fractional digits (those after the decimal-point) to be displayed in an internationally formatted monetary quantity.

char frac_digits

The number of fractional digits (those after the decimal-point) to be displayed in a formatted monetary quantity.

char p_cs_precedes

Set to 1 if the currency_symbol precedes the value for a non-negative formatted monetary quantity. Set to 0 if the symbol succeeds the value.

char p_sep_by_space

Set to a value indicating the separation of the currency_symbol, the sign string, and the value for a non-negative formatted monetary quantity.

char n_cs_precedes

Set to 1 if the currency_symbol precedes the value for a negative formatted monetary quantity. Set to 0 if the symbol succeeds the value.

char n_sep_by_space

Set to a value indicating the separation of the currency_symbol, the sign string, and the value for a negative formatted monetary quantity.

char p_sign_posn

Set to a value indicating the positioning of the positive_sign for a non-negative formatted monetary quantity.

char n_sign_posn

Set to a value indicating the positioning of the negative_sign for a negative formatted monetary quantity.

char int_p_cs_precedes

Set to 1 or 0 if the int_curr_symbol respectively precedes or succeeds the value for a non-negative internationally formatted monetary quantity.

char int_n_cs_precedes

Set to 1 or 0 if the int_curr_symbol respectively precedes or succeeds the value for a negative internationally formatted monetary quantity.

char int_p_sep_by_space

Set to a value indicating the separation of the int_curr_symbol, the sign string, and the value for a non-negative internationally formatted monetary quantity.

char int_n_sep_by_space

Set to a value indicating the separation of the int_curr_symbol, the sign string, and the value for a negative internationally formatted monetary quantity.

char int_p_sign_posn

Set to a value indicating the positioning of the positive_sign for a non-negative internationally formatted monetary quantity.

char int_n_sign_posn

Set to a value indicating the positioning of the negative_sign for a negative internationally formatted monetary quantity.

The elements of grouping and mon_grouping are interpreted according to the following:

{CHAR_MAX}
No further grouping is to be performed.
0
The previous element is to be repeatedly used for the remainder of the digits.
other
The integer value is the number of digits that comprise the current group. The next element is examined to determine the size of the next group of digits before the current group.

The values of p_sep_by_space, n_sep_by_space, int_p_sep_by_space, and int_n_sep_by_space are interpreted according to the following:

0
No space separates the currency symbol and value.
1
If the currency symbol and sign string are adjacent, a space separates them from the value; otherwise, a space separates the currency symbol from the value.
2
If the currency symbol and sign string are adjacent, a space separates them; otherwise, a space separates the sign string from the value.

For int_p_sep_by_space and int_n_sep_by_space, the fourth character of int_curr_symbol is used instead of a space.

The values of p_sign_posn, n_sign_posn, int_p_sign_posn, and int_n_sign_posn are interpreted according to the following:

0
Parentheses surround the quantity and currency_symbol or int_curr_symbol.
1
The sign string precedes the quantity and currency_symbol or int_curr_symbol.
2
The sign string succeeds the quantity and currency_symbol or int_curr_symbol.
3
The sign string immediately precedes the currency_symbol or int_curr_symbol.
4
The sign string immediately succeeds the currency_symbol or int_curr_symbol.

The implementation shall behave as if no function in this volume of IEEE Std 1003.1-2001 calls localeconv().

The localeconv() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The localeconv() function shall return a pointer to the filled-in object. The application shall not modify the structure pointed to by the return value which may be overwritten by a subsequent call to localeconv(). In addition, calls to setlocale() with the categories LC_ALL , LC_MONETARY , or LC_NUMERIC may overwrite the contents of the structure.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The following table illustrates the rules which may be used by four countries to format monetary quantities.
Country | Positive Format | Negative Format | International Format
Italy | L.1.230 | -L.1.230 | ITL.1.230
Netherlands | F 1.234,56 | F -1.234,56 | NLG 1.234,56
Norway | kr1.234,56 | kr1.234,56- | NOK 1.234,56
Switzerland | SFrs.1,234.56 | SFrs.1,234.56C | CHF 1,234.56

For these four countries, the respective values for the monetary members of the structure returned by localeconv() are:
 | Italy | Netherlands | Norway | Switzerland
int_curr_symbol | "ITL." | "NLG " | "NOK " | "CHF "
currency_symbol | "L." | "F" | "kr" | "SFrs."
mon_decimal_point | "" | "," | "," | "."
mon_thousands_sep | "." | "." | "." | ","
mon_grouping | "\3" | "\3" | "\3" | "\3"
positive_sign | "" | "" | "" | ""
negative_sign | "-" | "-" | "-" | "C"
int_frac_digits | 0 | 2 | 2 | 2
frac_digits | 0 | 2 | 2 | 2
p_cs_precedes | 1 | 1 | 1 | 1
p_sep_by_space | 0 | 1 | 0 | 0
n_cs_precedes | 1 | 1 | 1 | 1
n_sep_by_space | 0 | 1 | 0 | 0
p_sign_posn | 1 | 1 | 1 | 1
n_sign_posn | 1 | 4 | 2 | 2
int_p_cs_precedes | 1 | 1 | 1 | 1
int_n_cs_precedes | 1 | 1 | 1 | 1
int_p_sep_by_space | 0 | 0 | 0 | 0
int_n_sep_by_space | 0 | 0 | 0 | 0
int_p_sign_posn | 1 | 1 | 1 | 1
int_n_sign_posn | 1 | 4 | 4 | 2

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalpha() , isascii() , nl_langinfo() , printf() , scanf() , setlocale() , strcat() , strchr() , strcmp() , strcoll() , strcpy() , strftime() , strlen() , strpbrk() , strspn() , strtok() , strxfrm() , strtod() , the Base Definitions volume of IEEE Std 1003.1-2001, <langinfo.h>, <locale.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_setinherited (3p)

 Continue to this page.


wcscmp(3p)

WCSCMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcscmp - compare two wide-character strings

SYNOPSIS

#include <wchar.h>

int wcscmp(const wchar_t *ws1, const wchar_t *ws2);

DESCRIPTION

The wcscmp() function shall compare the wide-character string pointed to by ws1 to the wide-character string pointed to by ws2.

The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of wide-character codes that differ in the objects being compared.

RETURN VALUE

Upon completion, wcscmp() shall return an integer greater than, equal to, or less than 0, if the wide-character string pointed to by ws1 is greater than, equal to, or less than the wide-character string pointed to by ws2, respectively.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcsncmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cfgetospeed(3p)

CFGETOSPEED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cfgetospeed - get output baud rate

SYNOPSIS

#include <termios.h>

speed_t cfgetospeed(const struct termios *termios_p);

DESCRIPTION

The cfgetospeed() function shall extract the output baud rate from the termios structure to which the termios_p argument points.

This function shall return exactly the value in the termios data structure, without interpretation.

RETURN VALUE

Upon successful completion, cfgetospeed() shall return a value of type speed_t representing the output baud rate.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to cfgetispeed() .

FUTURE DIRECTIONS

None.

SEE ALSO

cfgetispeed() , cfsetispeed() , cfsetospeed() , tcgetattr() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


htonl(3p)

HTONL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

htonl, htons, ntohl, ntohs - convert values between host and network byte order

SYNOPSIS

#include <arpa/inet.h>

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

DESCRIPTION

These functions shall convert 16-bit and 32-bit quantities between network byte order and host byte order.

On some implementations, these functions are defined as macros.

The uint32_t and uint16_t types are defined in <inttypes.h>.

RETURN VALUE

The htonl() and htons() functions shall return the argument value converted from host to network byte order.

The ntohl() and ntohs() functions shall return the argument value converted from network to host byte order.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are most often used in conjunction with IPv4 addresses and ports as returned by gethostent() and getservent().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

endhostent() , endservent() , the Base Definitions volume of IEEE Std 1003.1-2001, <inttypes.h>, <arpa/inet.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


htons (3p)

 Continue to this page.


wcscpy(3p)

WCSCPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcscpy - copy a wide-character string

SYNOPSIS

#include <wchar.h>

wchar_t *wcscpy(wchar_t *restrict ws1, const wchar_t *restrict ws2);

DESCRIPTION

The wcscpy() function shall copy the wide-character string pointed to by ws2 (including the terminating null wide-character code) into the array pointed to by ws1. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The wcscpy() function shall return ws1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcsncpy() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


scalb(3p)

SCALB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

scalb - load exponent of a radix-independent floating-point number

SYNOPSIS

#include <math.h>

double scalb(double x, double n);

DESCRIPTION

The scalb() function shall compute x*r**n, where r is the radix of the machine's floating-point arithmetic. When r is 2, scalb() shall be equivalent to ldexp() . The value of r is FLT_RADIX which is defined in <float.h>.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, the scalb() function shall return x*r**n.

If x or n is NaN, a NaN shall be returned.

If n is zero, x shall be returned.

If x is ±Inf and n is not -Inf, x shall be returned.

If x is ±0 and n is not +Inf, x shall be returned.

If x is ±0 and n is +Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is ±Inf and n is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If the result would cause an overflow, a range error shall occur and ±HUGE_VAL (according to the sign of x) shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

If the correct value would cause underflow, and is not representable, a range error may occur, and 0.0 shall be returned.

ERRORS

The scalb() function shall fail if:

Domain Error
If x is zero and n is +Inf, or x is Inf and n is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Range Error
The result would overflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The scalb() function may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications should use either scalbln(), scalblnf(), or scalblnl() in preference to this function.

IEEE Std 1003.1-2001 only defines the behavior for the scalb() function when the n argument is an integer, a NaN, or Inf. The behavior of other values for the n argument is unspecified.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , ilogb() , ldexp() , logb() , scalbln() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <float.h>, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setgrent (3p)

 Continue to this page.


pwrite (3p)

 Continue to this page.


gmtime(3p)

GMTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gmtime, gmtime_r - convert a time value to a broken-down UTC time

SYNOPSIS

#include <time.h>

struct tm *gmtime(const time_t *timer);

struct tm *gmtime_r(const time_t *restrict timer,
struct tm *restrict result);

DESCRIPTION

For gmtime(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The gmtime() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as Coordinated Universal Time (UTC).

The relationship between a time in seconds since the Epoch used as an argument to gmtime() and the tm structure (defined in the <time.h> header) is that the result shall be as specified in the expression given in the definition of seconds since the Epoch (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.14, Seconds Since the Epoch), where the names in the structure and in the expression correspond.

The same relationship shall apply for gmtime_r().

The gmtime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.

The gmtime_r() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time expressed as Coordinated Universal Time (UTC). The broken-down time is stored in the structure referred to by result. The gmtime_r() function shall also return the address of the same structure.

RETURN VALUE

Upon successful completion, the gmtime() function shall return a pointer to a struct tm. If an error is detected, gmtime() shall return a null pointer and set errno to indicate the error.

Upon successful completion, gmtime_r() shall return the address of the structure pointed to by the argument result. If an error is detected, gmtime_r() shall return a null pointer.

ERRORS

The gmtime() function shall fail if:

EOVERFLOW
The result cannot be represented.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The gmtime_r() function is thread-safe and returns values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asctime() , clock() , ctime() , difftime() , localtime() , mktime() , strftime() , strptime() , time() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


scanf(3p)

FSCANF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fscanf, scanf, sscanf - convert formatted input

SYNOPSIS

#include <stdio.h>

int fscanf(FILE *restrict stream, const char *restrict format, ... );
int scanf(const char *restrict format, ... );
int sscanf(const char *restrict s, const char *restrict format, ... );

DESCRIPTION

The fscanf() function shall read from the named input stream. The scanf() function shall read from the standard input stream stdin. The sscanf() function shall read from the string s. Each function reads bytes, interprets them according to a format, and stores the results in its arguments. Each expects, as arguments, a control string format described below, and a set of pointer arguments indicating where the converted input should be stored. The result is undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments shall be evaluated but otherwise ignored.

Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier character % (see below) is replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}]. This feature provides for the definition of format strings that select arguments in an order appropriate to specific languages. In format strings containing the "%n$" form of conversion specifications, it is unspecified whether numbered arguments in the argument list can be referenced from the format string more than once.

The format can contain either form of a conversion specification-that is, % or "%n$"-but the two forms cannot be mixed within a single format string. The only exception to this is that %% or %* can be mixed with the "%n$" form. When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the ( N-1)th, are pointers.

The fscanf() function in all its forms shall allow detection of a language-dependent radix character in the input string. The radix character is defined in the program's locale (category LC_NUMERIC ). In the POSIX locale, or in a locale where the radix character is not defined, the radix character shall default to a period ( '.' ).

The format is a character string, beginning and ending in its initial shift state, if any, composed of zero or more directives. Each directive is composed of one of the following: one or more white-space characters ( <space>s, <tab>s, <newline>s, <vertical-tab>s, or <form-feed>s); an ordinary character (neither '%' nor a white-space character); or a conversion specification. Each conversion specification is introduced by the character '%' or the character sequence "%n$", after which the following appear in sequence:

*
An optional assignment-suppressing character '*' .

*
An optional non-zero decimal integer that specifies the maximum field width.

*
An option length modifier that specifies the size of the receiving object.

*
A conversion specifier character that specifies the type of conversion to be applied. The valid conversion specifiers are described below.

The fscanf() functions shall execute each directive of the format in turn. If a directive fails, as detailed below, the function shall return. Failures are described as input failures (due to the unavailability of input bytes) or matching failures (due to inappropriate input).

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.

A directive that is an ordinary character shall be executed as follows: the next byte shall be read from the input and compared with the byte that comprises the directive; if the comparison shows that they are not equivalent, the directive shall fail, and the differing and subsequent bytes shall remain unread. Similarly, if end-of-file, an encoding error, or a read error prevents a character from being read, the directive shall fail.

A directive that is a conversion specification defines a set of matching input sequences, as described below for each conversion character. A conversion specification shall be executed in the following steps.

Input white-space characters (as specified by isspace() ) shall be skipped, unless the conversion specification includes a [ , c , C , or n conversion specifier.

An item shall be read from the input, unless the conversion specification includes an n conversion specifier. An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence. The first byte, if any, after the input item shall remain unread. If the length of the input item is 0, the execution of the conversion specification shall fail; this condition is a matching failure, unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.

Except in the case of a % conversion specifier, the input item (or, in the case of a %n conversion specification, the count of input bytes) shall be converted to a type appropriate to the conversion character. If the input item is not a matching sequence, the execution of the conversion specification fails; this condition is a matching failure. Unless assignment suppression was indicated by a '*' , the result of the conversion shall be placed in the object pointed to by the first argument following the format argument that has not already received a conversion result if the conversion specification is introduced by % , or in the nth argument if introduced by the character sequence "%n$". If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the space provided, the behavior is undefined.

The length modifiers and their meanings are:

hh
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to signed char or unsigned char.
h
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.
l (ell)
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to long or unsigned long; that a following a , A , e , E , f , F , g , or G conversion specifier applies to an argument with type pointer to double; or that a following c , s , or [ conversion specifier applies to an argument with type pointer to wchar_t.
ll (ell-ell)

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to long long or unsigned long long.

j
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to intmax_t or uintmax_t.
z
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to size_t or the corresponding signed integer type.
t
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to ptrdiff_t or the corresponding unsigned type.
L
Specifies that a following a , A , e , E , f , F , g , or G conversion specifier applies to an argument with type pointer to long double.

If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.

The following conversion specifiers are valid:

d
Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of strtol() with the value 10 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to int.
i
Matches an optionally signed integer, whose format is the same as expected for the subject sequence of strtol() with 0 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to int.
o
Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence of strtoul() with the value 8 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to unsigned.
u
Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of strtoul() with the value 10 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to unsigned.
x
Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of strtoul() with the value 16 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to unsigned.
a, e, f, g

Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of strtod(). In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to float.

If the fprintf() family of functions generates character string representations for infinity and NaN (a symbolic entity encoded in floating-point format) to support IEEE Std 754-1985, the fscanf() family of functions shall recognize them as input.

s
Matches a sequence of bytes that are not white-space characters. The application shall ensure that the corresponding argument is a pointer to the initial byte of an array of char, signed char, or unsigned char large enough to accept the sequence and a terminating null character code, which shall be added automatically.

If an l (ell) qualifier is present, the input is a sequence of characters that begins in the initial shift state. Each character shall be converted to a wide character as if by a call to the mbrtowc() function, with the conversion state described by an mbstate_t object initialized to zero before the first character is converted. The application shall ensure that the corresponding argument is a pointer to an array of wchar_t large enough to accept the sequence and the terminating null wide character, which shall be added automatically.

[
Matches a non-empty sequence of bytes from a set of expected bytes (the scanset). The normal skip over white-space characters shall be suppressed in this case. The application shall ensure that the corresponding argument is a pointer to the initial byte of an array of char, signed char, or unsigned char large enough to accept the sequence and a terminating null byte, which shall be added automatically.

If an l (ell) qualifier is present, the input is a sequence of characters that begins in the initial shift state. Each character in the sequence shall be converted to a wide character as if by a call to the mbrtowc() function, with the conversion state described by an mbstate_t object initialized to zero before the first character is converted. The application shall ensure that the corresponding argument is a pointer to an array of wchar_t large enough to accept the sequence and the terminating null wide character, which shall be added automatically.

The conversion specification includes all subsequent bytes in the format string up to and including the matching right square bracket ( ']' ). The bytes between the square brackets (the scanlist) comprise the scanset, unless the byte after the left square bracket is a circumflex ( '^' ), in which case the scanset contains all bytes that do not appear in the scanlist between the circumflex and the right square bracket. If the conversion specification begins with "[]" or "[^]" , the right square bracket is included in the scanlist and the next right square bracket is the matching right square bracket that ends the conversion specification; otherwise, the first right square bracket is the one that ends the conversion specification. If a '-' is in the scanlist and is not the first character, nor the second where the first character is a '^' , nor the last character, the behavior is implementation-defined.

c
Matches a sequence of bytes of the number specified by the field width (1 if no field width is present in the conversion specification). The application shall ensure that the corresponding argument is a pointer to the initial byte of an array of char, signed char, or unsigned char large enough to accept the sequence. No null byte is added. The normal skip over white-space characters shall be suppressed in this case.

If an l (ell) qualifier is present, the input shall be a sequence of characters that begins in the initial shift state. Each character in the sequence is converted to a wide character as if by a call to the mbrtowc() function, with the conversion state described by an mbstate_t object initialized to zero before the first character is converted. The application shall ensure that the corresponding argument is a pointer to an array of wchar_t large enough to accept the resulting sequence of wide characters. No null wide character is added.

p
Matches an implementation-defined set of sequences, which shall be the same as the set of sequences that is produced by the %p conversion specification of the corresponding fprintf() functions. The application shall ensure that the corresponding argument is a pointer to a pointer to void. The interpretation of the input item is implementation-defined. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise, the behavior of the %p conversion specification is undefined.
n
No input is consumed. The application shall ensure that the corresponding argument is a pointer to the integer into which shall be written the number of bytes read from the input so far by this call to the fscanf() functions. Execution of a %n conversion specification shall not increment the assignment count returned at the completion of execution of the function. No argument shall be converted, but one shall be consumed. If the conversion specification includes an assignment-suppressing character or a field width, the behavior is undefined.
C
Equivalent to lc .
S
Equivalent to ls .
%
Matches a single '%' character; no conversion or assignment occurs. The complete conversion specification shall be %% .

If a conversion specification is invalid, the behavior is undefined.

The conversion specifiers A , E , F , G , and X are also valid and shall be equivalent to a , e , f , g , and x , respectively.

If end-of-file is encountered during input, conversion shall be terminated. If end-of-file occurs before any bytes matching the current conversion specification (except for %n ) have been read (other than leading white-space characters, where permitted), execution of the current conversion specification shall terminate with an input failure. Otherwise, unless execution of the current conversion specification is terminated with a matching failure, execution of the following conversion specification (if any) shall be terminated with an input failure.

Reaching the end of the string in sscanf() shall be equivalent to encountering end-of-file for fscanf().

If conversion terminates on a conflicting input, the offending input is left unread in the input. Any trailing white space (including <newline>s) shall be left unread unless matched by a conversion specification. The success of literal matches and suppressed assignments is only directly determinable via the %n conversion specification.

The fscanf() and scanf() functions may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fread(), getc(), getchar(), gets(), fscanf(), or fscanf() using stream that returns data not supplied by a prior call to ungetc().

RETURN VALUE

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set to indicate the error.

ERRORS

For the conditions under which the fscanf() functions fail and may fail, refer to fgetc() or fgetwc() .

In addition, fscanf() may fail if:

EILSEQ
Input byte sequence does not form a valid character.
EINVAL
There are insufficient arguments.

The following sections are informative.

EXAMPLES

The call:

int i, n; float x; char name[50];
n = scanf("%d%f%s", &i, &x, name);

with the input line:

25 54.32E-1 Hamster

assigns to n the value 3, to i the value 25, to x the value 5.432, and name contains the string "Hamster" .

The call:

int i; float x; char name[50];
(void) scanf("%2d%f%*d %[0123456789]", &i, &x, name);

with input:

56789 0123 56a72

assigns 56 to i, 789.0 to x, skips 0123, and places the string "56\0" in name. The next call to getchar() shall return the character 'a' .

Reading Data into an Array

The following call uses fscanf() to read three floating-point numbers from standard input into the input array.

float input[3]; fscanf (stdin, "%f %f %f", input, input+1, input+2);

APPLICATION USAGE

If the application calling fscanf() has any objects of type wint_t or wchar_t, it must also include the <wchar.h> header to have these objects defined.

RATIONALE

This function is aligned with the ISO/IEC 9899:1999 standard, and in doing so a few "obvious" things were not included. Specifically, the set of characters allowed in a scanset is limited to single-byte characters. In other similar places, multi-byte characters have been permitted, but for alignment with the ISO/IEC 9899:1999 standard, it has not been done here. Applications needing this could use the corresponding wide-character functions to achieve the desired results.

FUTURE DIRECTIONS

None.

SEE ALSO

getc() , printf() , setlocale() , strtod() , strtol() , strtoul() , wcrtomb() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <langinfo.h>, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_getstreamsize (3p)

 Continue to this page.


rindex(3p)

RINDEX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rindex - character string operations (LEGACY)

SYNOPSIS

#include <strings.h>

char *rindex(const char *s, int c);

DESCRIPTION

The rindex() function shall be equivalent to strrchr() .

RETURN VALUE

Refer to strrchr() .

ERRORS

Refer to strrchr() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The strrchr() function is preferred over this function.

For maximum portability, it is recommended to replace the function call to rindex() as follows:

#define rindex(a,b) strrchr((a),(b))

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

strrchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nrand48 (3p)

 Continue to this page.


rewind(3p)

REWIND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rewind - reset the file position indicator in a stream

SYNOPSIS

#include <stdio.h>

void rewind(FILE *stream);

DESCRIPTION

The call:

rewind(stream)

shall be equivalent to:

(void) fseek(stream, 0L, SEEK_SET)

except that rewind() shall also clear the error indicator.

Since rewind() does not return a value, an application wishing to detect errors should clear errno, then call rewind(), and if errno is non-zero, assume an error has occurred.

RETURN VALUE

The rewind() function shall not return a value.

ERRORS

Refer to fseek() with the exception of [EINVAL] which does not apply.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fseek() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_condattr_setclock (3p)

 Continue to this page.


posix_madvise(3p)

POSIX_MADVISE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_madvise - memory advisory information and alignment control (ADVANCED REALTIME)

SYNOPSIS

#include <sys/mman.h>

int posix_madvise(void *addr, size_t len, int advice);

DESCRIPTION

The posix_madvise() function need only be supported if either the Memory Mapped Files or the Shared Memory Objects options are supported.

The posix_madvise() function shall advise the implementation on the expected behavior of the application with respect to the data in the memory starting at address addr, and continuing for len bytes. The implementation may use this information to optimize handling of the specified data. The posix_madvise() function shall have no effect on the semantics of access to memory in the specified range, although it may affect the performance of access.

The implementation may require that addr be a multiple of the page size, which is the value returned by sysconf() when the name value _SC_PAGESIZE is used.

The advice to be applied to the memory range is specified by the advice parameter and may be one of the following values:

POSIX_MADV_NORMAL

Specifies that the application has no advice to give on its behavior with respect to the specified range. It is the default characteristic if no advice is given for a range of memory.

POSIX_MADV_SEQUENTIAL

Specifies that the application expects to access the specified range sequentially from lower addresses to higher addresses.

POSIX_MADV_RANDOM

Specifies that the application expects to access the specified range in a random order.

POSIX_MADV_WILLNEED

Specifies that the application expects to access the specified range in the near future.

POSIX_MADV_DONTNEED

Specifies that the application expects that it will not access the specified range in the near future.

These values are defined in the <sys/mman.h> header.

RETURN VALUE

Upon successful completion, posix_madvise() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The posix_madvise() function shall fail if:

EINVAL
The value of advice is invalid.
ENOMEM
Addresses in the range starting at addr and continuing for len bytes are partly or completely outside the range allowed for the address space of the calling process.

The posix_madvise() function may fail if:

EINVAL
The value of addr is not a multiple of the value returned by sysconf() when the name value _SC_PAGESIZE is used.
EINVAL
The value of len is zero.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The posix_madvise() function is part of the Advisory Information option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mmap() , posix_fadvise() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


jrand48 (3p)

 Continue to this page.


pthread_equal(3p)

PTHREAD_EQUAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_equal - compare thread IDs

SYNOPSIS

#include <pthread.h>

int pthread_equal(pthread_t t1, pthread_t t2);

DESCRIPTION

This function shall compare the thread IDs t1 and t2.

RETURN VALUE

The pthread_equal() function shall return a non-zero value if t1 and t2 are equal; otherwise, zero shall be returned.

If either t1 or t2 are not valid thread IDs, the behavior is undefined.

ERRORS

No errors are defined.

The pthread_equal() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Implementations may choose to define a thread ID as a structure. This allows additional flexibility and robustness over using an int. For example, a thread ID could include a sequence number that allows detection of "dangling IDs" (copies of a thread ID that has been detached). Since the C language does not support comparison on structure types, the pthread_equal() function is provided to compare thread IDs.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_create() , pthread_self() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


acoshf (3p)

 Continue to this page.


acoshl (3p)

 Continue to this page.


llabs (3p)

 Continue to this page.


lrint(3p)

LRINT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lrint, lrintf, lrintl - round to nearest integer value using current rounding direction

SYNOPSIS

#include <math.h>

long lrint(double x);
long lrintf(float x);
long lrintl(long double x);

DESCRIPTION

These functions shall round their argument to the nearest integer value, rounding according to the current rounding direction.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the rounded integer value.

If x is NaN, a domain error shall occur and an unspecified value is returned.

If x is +Inf, a domain error shall occur and an unspecified value is returned.

If x is -Inf, a domain error shall occur and an unspecified value is returned.

If the correct value is positive and too large to represent as a long, a domain error shall occur and an unspecified value is returned.

If the correct value is negative and too large to represent as a long, a domain error shall occur and an unspecified value is returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is NaN or ±Inf, or the correct value is not representable as an integer.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

These functions provide floating-to-integer conversions. They round according to the current rounding direction. If the rounded value is outside the range of the return type, the numeric result is unspecified and the invalid floating-point exception is raised. When they raise no other floating-point exception and the result differs from the argument, they raise the inexact floating-point exception.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , llrint() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sscanf (3p)

 Continue to this page.


realpath(3p)

REALPATH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

realpath - resolve a pathname

SYNOPSIS

#include <stdlib.h>

char *realpath(const char *restrict file_name,
char *restrict resolved_name);

DESCRIPTION

The realpath() function shall derive, from the pathname pointed to by file_name, an absolute pathname that names the same file, whose resolution does not involve '.' , '..' , or symbolic links. The generated pathname shall be stored as a null-terminated string, up to a maximum of {PATH_MAX} bytes, in the buffer pointed to by resolved_name.

If resolved_name is a null pointer, the behavior of realpath() is implementation-defined.

RETURN VALUE

Upon successful completion, realpath() shall return a pointer to the resolved name. Otherwise, realpath() shall return a null pointer and set errno to indicate the error, and the contents of the buffer pointed to by resolved_name are undefined.

ERRORS

The realpath() function shall fail if:

EACCES
Read or search permission was denied for a component of file_name.
EINVAL
The file_name argument is a null pointer.
EIO
An error occurred while reading from the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the file_name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of file_name does not name an existing file or file_name points to an empty string.
ENOTDIR
A component of the path prefix is not a directory.

The realpath() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.
ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

Generating an Absolute Pathname

The following example generates an absolute pathname for the file identified by the symlinkpath argument. The generated pathname is stored in the actualpath array.

#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;

ptr = realpath(symlinkpath, actualpath);

APPLICATION USAGE

None.

RATIONALE

Since the maximum pathname length is arbitrary unless {PATH_MAX} is defined, an application generally cannot supply a resolved_name buffer with size {{PATH_MAX}+1}.

FUTURE DIRECTIONS

In the future, passing a null pointer to realpath() for the resolved_name argument may be defined to have realpath() allocate space for the generated pathname.

SEE ALSO

getcwd() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


send(3p)

SEND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

send - send a message on a socket

SYNOPSIS

#include <sys/socket.h>

ssize_t send(int socket, const void *buffer, size_t length, int flags);

DESCRIPTION

The send() function shall initiate transmission of a message from the specified socket to its peer. The send() function shall send a message only when the socket is connected (including when the peer of a connectionless socket has been set via connect()).

The send() function takes the following arguments:

socket
Specifies the socket file descriptor.
buffer
Points to the buffer containing the message to send.
length
Specifies the length of the message in bytes.
flags
Specifies the type of message transmission. Values of this argument are formed by logically OR'ing zero or more of the following flags:
MSG_EOR
Terminates a record (if supported by the protocol).
MSG_OOB
Sends out-of-band data on sockets that support out-of-band communications. The significance and semantics of out-of-band data are protocol-specific.

The length of the message to be sent is specified by the length argument. If the message is too long to pass through the underlying protocol, send() shall fail and no data shall be transmitted.

Successful completion of a call to send() does not guarantee delivery of the message. A return value of -1 indicates only locally-detected errors.

If space is not available at the sending socket to hold the message to be transmitted, and the socket file descriptor does not have O_NONBLOCK set, send() shall block until space is available. If space is not available at the sending socket to hold the message to be transmitted, and the socket file descriptor does have O_NONBLOCK set, send() shall fail. The select() and poll() functions can be used to determine when it is possible to send more data.

The socket in use may require the process to have appropriate privileges to use the send() function.

RETURN VALUE

Upon successful completion, send() shall return the number of bytes sent. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The send() function shall fail if:

EAGAIN or EWOULDBLOCK

The socket's file descriptor is marked O_NONBLOCK and the requested operation would block.

EBADF
The socket argument is not a valid file descriptor.
ECONNRESET
A connection was forcibly closed by a peer.
EDESTADDRREQ

The socket is not connection-mode and no peer address is set.

EINTR
A signal interrupted send() before any data was transmitted.
EMSGSIZE
The message is too large to be sent all at once, as the socket requires.
ENOTCONN
The socket is not connected or otherwise has not had the peer pre-specified.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The socket argument is associated with a socket that does not support one or more of the values set in flags.
EPIPE
The socket is shut down for writing, or the socket is connection-mode and is no longer connected. In the latter case, and if the socket is of type SOCK_STREAM, the SIGPIPE signal is generated to the calling thread.

The send() function may fail if:

EACCES
The calling process does not have the appropriate privileges.
EIO
An I/O error occurred while reading from or writing to the file system.
ENETDOWN
The local network interface used to reach the destination is down.
ENETUNREACH

No route to the network is present.

ENOBUFS
Insufficient resources were available in the system to perform the operation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The send() function is equivalent to sendto() with a null pointer dest_len argument, and to write() if no flags are used.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

connect() , getsockopt() , poll() , recv() , recvfrom() , recvmsg() , select() , sendmsg() , sendto() , setsockopt() , shutdown() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigwaitinfo(3p)

SIGTIMEDWAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigtimedwait, sigwaitinfo - wait for queued signals (REALTIME)

SYNOPSIS

#include <signal.h>

int sigtimedwait(const sigset_t *restrict set,
siginfo_t *restrict info,
const struct timespec *restrict timeout);
int sigwaitinfo(const sigset_t *restrict set,
siginfo_t *restrict info);

DESCRIPTION

The sigtimedwait() function shall be equivalent to sigwaitinfo() except that if none of the signals specified by set are pending, sigtimedwait() shall wait for the time interval specified in the timespec structure referenced by timeout. If the timespec structure pointed to by timeout is zero-valued and if none of the signals specified by set are pending, then sigtimedwait() shall return immediately with an error. If timeout is the NULL pointer, the behavior is unspecified. If the Monotonic Clock option is supported, the CLOCK_MONOTONIC clock shall be used to measure the time interval specified by the timeout argument.

The sigwaitinfo() function selects the pending signal from the set specified by set. Should any of multiple pending signals in the range SIGRTMIN to SIGRTMAX be selected, it shall be the lowest numbered one. The selection order between realtime and non-realtime signals, or between multiple pending non-realtime signals, is unspecified. If no signal in set is pending at the time of the call, the calling thread shall be suspended until one or more signals in set become pending or until it is interrupted by an unblocked, caught signal.

The sigwaitinfo() function shall be equivalent to the sigwait() function if the info argument is NULL. If the info argument is non-NULL, the sigwaitinfo() function shall be equivalent to sigwait(), except that the selected signal number shall be stored in the si_signo member, and the cause of the signal shall be stored in the si_code member. If any value is queued to the selected signal, the first such queued value shall be dequeued and, if the info argument is non-NULL, the value shall be stored in the si_value member of info. The system resource used to queue the signal shall be released and returned to the system for other use. If no value is queued, the content of the si_value member is undefined. If no further signals are queued for the selected signal, the pending indication for that signal shall be reset.

RETURN VALUE

Upon successful completion (that is, one of the signals specified by set is pending or is generated) sigwaitinfo() and sigtimedwait() shall return the selected signal number. Otherwise, the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sigtimedwait() function shall fail if:

EAGAIN
No signal specified by set was generated within the specified timeout period.

The sigtimedwait() and sigwaitinfo() functions may fail if:

EINTR
The wait was interrupted by an unblocked, caught signal. It shall be documented in system documentation whether this error causes these functions to fail.

The sigtimedwait() function may also fail if:

EINVAL
The timeout argument specified a tv_nsec value less than zero or greater than or equal to 1000 million.

An implementation only checks for this error if no signal is pending in set and it is necessary to wait.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sigtimedwait() function times out and returns an [EAGAIN] error. Application writers should note that this is inconsistent with other functions such as pthread_cond_timedwait() that return [ETIMEDOUT].

RATIONALE

Existing programming practice on realtime systems uses the ability to pause waiting for a selected set of events and handle the first event that occurs in-line instead of in a signal-handling function. This allows applications to be written in an event-directed style similar to a state machine. This style of programming is useful for largescale transaction processing in which the overall throughput of an application and the ability to clearly track states are more important than the ability to minimize the response time of individual event handling.

It is possible to construct a signal-waiting macro function out of the realtime signal function mechanism defined in this volume of IEEE Std 1003.1-2001. However, such a macro has to include the definition of a generalized handler for all signals to be waited on. A significant portion of the overhead of handler processing can be avoided if the signal-waiting function is provided by the kernel. This volume of IEEE Std 1003.1-2001 therefore provides two signal-waiting functions-one that waits indefinitely and one with a timeout-as part of the overall realtime signal function specification.

The specification of a function with a timeout allows an application to be written that can be broken out of a wait after a set period of time if no event has occurred. It was argued that setting a timer event before the wait and recognizing the timer event in the wait would also implement the same functionality, but at a lower performance level. Because of the performance degradation associated with the user-level specification of a timer event and the subsequent cancellation of that timer event after the wait completes for a valid event, and the complexity associated with handling potential race conditions associated with the user-level method, the separate function has been included.

Note that the semantics of the sigwaitinfo() function are nearly identical to that of the sigwait() function defined by this volume of IEEE Std 1003.1-2001. The only difference is that sigwaitinfo() returns the queued signal value in the value argument. The return of the queued value is required so that applications can differentiate between multiple events queued to the same signal number.

The two distinct functions are being maintained because some implementations may choose to implement the POSIX Threads Extension functions and not implement the queued signals extensions. Note, though, that sigwaitinfo() does not return the queued value if the value argument is NULL, so the POSIX Threads Extension sigwait() function can be implemented as a macro on sigwaitinfo().

The sigtimedwait() function was separated from the sigwaitinfo() function to address concerns regarding the overloading of the timeout pointer to indicate indefinite wait (no timeout), timed wait, and immediate return, and concerns regarding consistency with other functions where the conditional and timed waits were separate functions from the pure blocking function. The semantics of sigtimedwait() are specified such that sigwaitinfo() could be implemented as a macro with a NULL pointer for timeout.

The sigwait functions provide a synchronous mechanism for threads to wait for asynchronously-generated signals. One important question was how many threads that are suspended in a call to a sigwait() function for a signal should return from the call when the signal is sent. Four choices were considered:

1.
Return an error for multiple simultaneous calls to sigwait functions for the same signal.

2.
One or more threads return.

3.
All waiting threads return.

4.
Exactly one thread returns.

Prohibiting multiple calls to sigwait() for the same signal was felt to be overly restrictive. The "one or more" behavior made implementation of conforming packages easy at the expense of forcing POSIX threads clients to protect against multiple simultaneous calls to sigwait() in application code in order to achieve predictable behavior. There was concern that the "all waiting threads" behavior would result in "signal broadcast storms", consuming excessive CPU resources by replicating the signals in the general case. Furthermore, no convincing examples could be presented that delivery to all was either simpler or more powerful than delivery to one.

Thus, the consensus was that exactly one thread that was suspended in a call to a sigwait function for a signal should return when that signal occurs. This is not an onerous restriction as:

*
A multi-way signal wait can be built from the single-way wait.

*
Signals should only be handled by application-level code, as library routines cannot guess what the application wants to do with signals generated for the entire process.

*
Applications can thus arrange for a single thread to wait for any given signal and call any needed routines upon its arrival.

In an application that is using signals for interprocess communication, signal processing is typically done in one place. Alternatively, if the signal is being caught so that process cleanup can be done, the signal handler thread can call separate process cleanup routines for each portion of the application. Since the application main line started each portion of the application, it is at the right abstraction level to tell each portion of the application to clean up.

Certainly, there exist programming styles where it is logical to consider waiting for a single signal in multiple threads. A simple sigwait_multiple() routine can be constructed to achieve this goal. A possible implementation would be to have each sigwait_multiple() caller registered as having expressed interest in a set of signals. The caller then waits on a thread-specific condition variable. A single server thread calls a sigwait() function on the union of all registered signals. When the sigwait() function returns, the appropriate state is set and condition variables are broadcast. New sigwait_multiple() callers may cause the pending sigwait() call to be canceled and reissued in order to update the set of signals being waited for.

FUTURE DIRECTIONS

None.

SEE ALSO

Realtime Signals , pause() , pthread_sigmask() , sigaction() , sigpending() , sigsuspend() , sigwait() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigqueue(3p)

SIGQUEUE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigqueue - queue a signal to a process (REALTIME)

SYNOPSIS

#include <signal.h>

int sigqueue(pid_t pid, int signo, const union sigval value);

DESCRIPTION

The sigqueue() function shall cause the signal specified by signo to be sent with the value specified by value to the process specified by pid. If signo is zero (the null signal), error checking is performed but no signal is actually sent. The null signal can be used to check the validity of pid.

The conditions required for a process to have permission to queue a signal to another process are the same as for the kill() function.

The sigqueue() function shall return immediately. If SA_SIGINFO is set for signo and if the resources were available to queue the signal, the signal shall be queued and sent to the receiving process. If SA_SIGINFO is not set for signo, then signo shall be sent at least once to the receiving process; it is unspecified whether value shall be sent to the receiving process as a result of this call.

If the value of pid causes signo to be generated for the sending process, and if signo is not blocked for the calling thread and if no other thread has signo unblocked or is waiting in a sigwait() function for signo, either signo or at least the pending, unblocked signal shall be delivered to the calling thread before the sigqueue() function returns. Should any multiple pending signals in the range SIGRTMIN to SIGRTMAX be selected for delivery, it shall be the lowest numbered one. The selection order between realtime and non-realtime signals, or between multiple pending non-realtime signals, is unspecified.

RETURN VALUE

Upon successful completion, the specified signal shall have been queued, and the sigqueue() function shall return a value of zero. Otherwise, the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sigqueue() function shall fail if:

EAGAIN
No resources are available to queue the signal. The process has already queued {SIGQUEUE_MAX} signals that are still pending at the receiver(s), or a system-wide resource limit has been exceeded.
EINVAL
The value of the signo argument is an invalid or unsupported signal number.
EPERM
The process does not have the appropriate privilege to send the signal to the receiving process.
ESRCH
The process pid does not exist.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The sigqueue() function allows an application to queue a realtime signal to itself or to another process, specifying the application-defined value. This is common practice in realtime applications on existing realtime systems. It was felt that specifying another function in the sig... name space already carved out for signals was preferable to extending the interface to kill().

Such a function became necessary when the put/get event function of the message queues was removed. It should be noted that the sigqueue() function implies reduced performance in a security-conscious implementation as the access permissions between the sender and receiver have to be checked on each send when the pid is resolved into a target process. Such access checks were necessary only at message queue open in the previous interface.

The standard developers required that sigqueue() have the same semantics with respect to the null signal as kill(), and that the same permission checking be used. But because of the difficulty of implementing the "broadcast" semantic of kill() (for example, to process groups) and the interaction with resource allocation, this semantic was not adopted. The sigqueue() function queues a signal to a single process specified by the pid argument.

The sigqueue() function can fail if the system has insufficient resources to queue the signal. An explicit limit on the number of queued signals that a process could send was introduced. While the limit is "per-sender", this volume of IEEE Std 1003.1-2001 does not specify that the resources be part of the state of the sender. This would require either that the sender be maintained after exit until all signals that it had sent to other processes were handled or that all such signals that had not yet been acted upon be removed from the queue(s) of the receivers. This volume of IEEE Std 1003.1-2001 does not preclude this behavior, but an implementation that allocated queuing resources from a system-wide pool (with per-sender limits) and that leaves queued signals pending after the sender exits is also permitted.

FUTURE DIRECTIONS

None.

SEE ALSO

Realtime Signals , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getc_unlocked (3p)

 Continue to this page.


aio_read(3p)

AIO_READ

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio_read - asynchronous read from a file (REALTIME)

SYNOPSIS

#include <aio.h>

int aio_read(struct aiocb *aiocbp);

DESCRIPTION

The aio_read() function shall read aiocbp->aio_nbytes from the file associated with aiocbp->aio_fildes into the buffer pointed to by aiocbp->aio_buf. The function call shall return when the read request has been initiated or queued to the file or device (even when the data cannot be delivered immediately).

If prioritized I/O is supported for this file, then the asynchronous operation shall be submitted at a priority equal to the scheduling priority of the process minus aiocbp->aio_reqprio.

The aiocbp value may be used as an argument to aio_error() and aio_return() in order to determine the error status and return status, respectively, of the asynchronous operation while it is proceeding. If an error condition is encountered during queuing, the function call shall return without having initiated or queued the request. The requested operation takes place at the absolute position in the file as given by aio_offset, as if lseek() were called immediately prior to the operation with an offset equal to aio_offset and a whence equal to SEEK_SET. After a successful call to enqueue an asynchronous I/O operation, the value of the file offset for the file is unspecified.

The aiocbp->aio_lio_opcode field shall be ignored by aio_read().

The aiocbp argument points to an aiocb structure. If the buffer pointed to by aiocbp->aio_buf or the control block pointed to by aiocbp becomes an illegal address prior to asynchronous I/O completion, then the behavior is undefined.

Simultaneous asynchronous operations using the same aiocbp produce undefined results.

If synchronized I/O is enabled on the file associated with aiocbp->aio_fildes, the behavior of this function shall be according to the definitions of synchronized I/O data integrity completion and synchronized I/O file integrity completion.

For any system action that changes the process memory space while an asynchronous I/O is outstanding to the address range being changed, the result of that action is undefined.

For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with aiocbp->aio_fildes.

RETURN VALUE

The aio_read() function shall return the value zero to the calling process if the I/O operation is successfully queued; otherwise, the function shall return the value -1 and set errno to indicate the error.

ERRORS

The aio_read() function shall fail if:

EAGAIN
The requested asynchronous I/O operation was not queued due to system resource limitations.

Each of the following conditions may be detected synchronously at the time of the call to aio_read(), or asynchronously. If any of the conditions below are detected synchronously, the aio_read() function shall return -1 and set errno to the corresponding value. If any of the conditions below are detected asynchronously, the return status of the asynchronous operation is set to -1, and the error status of the asynchronous operation is set to the corresponding value.

EBADF
The aiocbp->aio_fildes argument is not a valid file descriptor open for reading.
EINVAL
The file offset value implied by aiocbp->aio_offset would be invalid, aiocbp->aio_reqprio is not a valid value, or aiocbp->aio_nbytes is an invalid value.

In the case that the aio_read() successfully queues the I/O operation but the operation is subsequently canceled or encounters an error, the return status of the asynchronous operation is one of the values normally returned by the read() function call. In addition, the error status of the asynchronous operation is set to one of the error statuses normally set by the read() function call, or one of the following values:

EBADF
The aiocbp->aio_fildes argument is not a valid file descriptor open for reading.
ECANCELED
The requested I/O was canceled before the I/O completed due to an explicit aio_cancel() request.
EINVAL
The file offset value implied by aiocbp->aio_offset would be invalid.

The following condition may be detected synchronously or asynchronously:

EOVERFLOW
The file is a regular file, aiobcp->aio_nbytes is greater than 0, and the starting offset in aiobcp->aio_offset is before the end-of-file and is at or beyond the offset maximum in the open file description associated with aiocbp->aio_fildes.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The aio_read() function is part of the Asynchronous Input and Output option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_cancel() , aio_error() , lio_listio() , aio_return() , aio_write() , close() , exec() , exit() , fork() , lseek() , read() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigsetjmp(3p)

SIGSETJMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigsetjmp - set jump point for a non-local goto

SYNOPSIS

#include <setjmp.h>

int sigsetjmp(sigjmp_buf env, int savemask);

DESCRIPTION

The sigsetjmp() function shall be equivalent to the setjmp() function, except as follows:

*
References to setjmp() are equivalent to sigsetjmp().

*
References to longjmp() are equivalent to siglongjmp().

*
If the value of the savemask argument is not 0, sigsetjmp() shall also save the current signal mask of the calling thread as part of the calling environment.

RETURN VALUE

If the return is from a successful direct invocation, sigsetjmp() shall return 0. If the return is from a call to siglongjmp(), sigsetjmp() shall return a non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The distinction between setjmp()/ longjmp() and sigsetjmp()/ siglongjmp() is only significant for programs which use sigaction(), sigprocmask(), or sigsuspend().

Note that since this function is defined in terms of setjmp(), if savemask is zero, it is unspecified whether the signal mask is saved.

RATIONALE

The ISO C standard specifies various restrictions on the usage of the setjmp() macro in order to permit implementors to recognize the name in the compiler and not implement an actual function. These same restrictions apply to the sigsetjmp() macro.

There are processors that cannot easily support these calls, but this was not considered a sufficient reason to exclude them.

4.2 BSD, 4.3 BSD, and XSI-conformant systems provide functions named _setjmp() and _longjmp() that, together with setjmp() and longjmp(), provide the same functionality as sigsetjmp() and siglongjmp(). On those systems, setjmp() and longjmp() save and restore signal masks, while _setjmp() and _longjmp() do not. On System V Release 3 and in corresponding issues of the SVID, setjmp() and longjmp() are explicitly defined not to save and restore signal masks. In order to permit existing practice in both cases, the relation of setjmp() and longjmp() to signal masks is not specified, and a new set of functions is defined instead.

The longjmp() and siglongjmp() functions operate as in the previous issue provided the matching setjmp() or sigsetjmp() has been performed in the same thread. Non-local jumps into contexts saved by other threads would be at best a questionable practice and were not considered worthy of standardization.

FUTURE DIRECTIONS

None.

SEE ALSO

siglongjmp() , signal() , sigprocmask() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <setjmp.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getegid(3p)

GETEGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getegid - get the effective group ID

SYNOPSIS

#include <unistd.h>

gid_t getegid(void);

DESCRIPTION

The getegid() function shall return the effective group ID of the calling process.

RETURN VALUE

The getegid() function shall always be successful and no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

geteuid() , getgid() , getuid() , setegid() , seteuid() , setgid() , setregid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawn_file_actions_adddup2(3p)

POSIX_SPAWN_FILE_ACTIONS_ADDDUP2

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawn_file_actions_adddup2 - add dup2 action to spawn file actions object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *
file_actions, int fildes, int newfildes);

DESCRIPTION

The posix_spawn_file_actions_adddup2() function shall add a dup2() action to the object referenced by file_actions that shall cause the file descriptor fildes to be duplicated as newfildes (as if dup2( fildes, newfildes) had been called) when a new process is spawned using this file actions object.

A spawn file actions object is as defined in posix_spawn_file_actions_addclose() .

RETURN VALUE

Upon successful completion, the posix_spawn_file_actions_adddup2() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The posix_spawn_file_actions_adddup2() function shall fail if:

EBADF
The value specified by fildes or newfildes is negative or greater than or equal to {OPEN_MAX}.
ENOMEM
Insufficient memory exists to add to the spawn file actions object.

The posix_spawn_file_actions_adddup2() function may fail if:

EINVAL
The value specified by file_actions is invalid.

It shall not be considered an error for the fildes argument passed to the posix_spawn_file_actions_adddup2() function to specify a file descriptor for which the specified operation could not be performed at the time of the call. Any such error will be detected when the associated file actions object is later used during a posix_spawn() or posix_spawnp() operation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The posix_spawn_file_actions_adddup2() function is part of the Spawn option and need not be provided on all implementations.

RATIONALE

Refer to the RATIONALE in posix_spawn_file_actions_addclose() .

FUTURE DIRECTIONS

None.

SEE ALSO

dup() , posix_spawn() , posix_spawn_file_actions_addclose() , posix_spawn_file_actions_destroy() , posix_spawnp() , the Base Definitions volume of IEEE Std 1003.1-2001, <spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tcgetsid(3p)

TCGETSID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcgetsid - get the process group ID for the session leader for the controlling terminal

SYNOPSIS

#include <termios.h>

pid_t tcgetsid(int fildes);

DESCRIPTION

The tcgetsid() function shall obtain the process group ID of the session for which the terminal specified by fildes is the controlling terminal.

RETURN VALUE

Upon successful completion, tcgetsid() shall return the process group ID associated with the terminal. Otherwise, a value of (pid_t)-1 shall be returned and errno set to indicate the error.

ERRORS

The tcgetsid() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
ENOTTY
The calling process does not have a controlling terminal, or the file is not the controlling terminal.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <termios.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ungetwc(3p)

UNGETWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ungetwc - push wide-character code back into the input stream

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

wint_t ungetwc(wint_t wc, FILE *stream);

DESCRIPTION

The ungetwc() function shall push the character corresponding to the wide-character code specified by wc back onto the input stream pointed to by stream. The pushed-back characters shall be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to by stream) to a file-positioning function ( fseek(), fsetpos(), or rewind()) discards any pushed-back characters for the stream. The external storage corresponding to the stream is unchanged.

At least one character of push-back shall be provided. If ungetwc() is called too many times on the same stream without an intervening read or file-positioning operation on that stream, the operation may fail.

If the value of wc equals that of the macro WEOF, the operation shall fail and the input stream shall be left unchanged.

A successful call to ungetwc() shall clear the end-of-file indicator for the stream. The value of the file-position indicator for the stream after reading or discarding all pushed-back characters shall be the same as it was before the characters were pushed back. The file-position indicator is decremented (by one or more) by each successful call to ungetwc(); if its value was 0 before a call, its value is unspecified after the call.

RETURN VALUE

Upon successful completion, ungetwc() shall return the wide-character code corresponding to the pushed-back character. Otherwise, it shall return WEOF.

ERRORS

The ungetwc() function may fail if:

EILSEQ
An invalid character sequence is detected, or a wide-character code does not correspond to a valid character.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fseek() , fsetpos() , read() , rewind() , setbuf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_setstreamfullpolicy (3p)

 Continue to this page.


sigismember(3p)

SIGISMEMBER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigismember - test for a signal in a signal set

SYNOPSIS

#include <signal.h>

int sigismember(const sigset_t *set, int signo);

DESCRIPTION

The sigismember() function shall test whether the signal specified by signo is a member of the set pointed to by set.

Applications should call either sigemptyset() or sigfillset() at least once for each object of type sigset_t prior to any other use of that object. If such an object is not initialized in this way, but is nonetheless supplied as an argument to any of pthread_sigmask(), sigaction(), sigaddset(), sigdelset(), sigismember(), sigpending(), sigprocmask(), sigsuspend(), sigtimedwait(), sigwait(), or sigwaitinfo(), the results are undefined.

RETURN VALUE

Upon successful completion, sigismember() shall return 1 if the specified signal is a member of the specified set, or 0 if it is not. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The sigismember() function may fail if:

EINVAL
The signo argument is not a valid signal number, or is an unsupported signal number.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , sigaction() , sigaddset() , sigdelset() , sigfillset() , sigemptyset() , sigpending() , sigprocmask() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_self(3p)

PTHREAD_SELF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_self - get the calling thread ID

SYNOPSIS

#include <pthread.h>

pthread_t pthread_self(void);

DESCRIPTION

The pthread_self() function shall return the thread ID of the calling thread.

RETURN VALUE

Refer to the DESCRIPTION.

ERRORS

No errors are defined.

The pthread_self() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The pthread_self() function provides a capability similar to the getpid() function for processes and the rationale is the same: the creation call does not provide the thread ID to the created thread.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_create() , pthread_equal() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sinhf (3p)

 Continue to this page.


fstatvfs (3p)

 Continue to this page.


sinhl (3p)

 Continue to this page.


putenv(3p)

PUTENV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

putenv - change or add a value to an environment

SYNOPSIS

#include <stdlib.h>

int putenv(char *string);

DESCRIPTION

The putenv() function shall use the string argument to set environment variable values. The string argument should point to a string of the form " name= value ". The putenv() function shall make the value of the environment variable name equal to value by altering an existing variable or creating a new one. In either case, the string pointed to by string shall become part of the environment, so altering the string shall change the environment. The space used by string is no longer used once a new string which defines name is passed to putenv().

The putenv() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, putenv() shall return 0; otherwise, it shall return a non-zero value and set errno to indicate the error.

ERRORS

The putenv() function may fail if:

ENOMEM
Insufficient memory was available.

The following sections are informative.

EXAMPLES

Changing the Value of an Environment Variable

The following example changes the value of the HOME environment variable to the value /usr/home.

#include <stdlib.h>
...
static char *var = "HOME=/usr/home";
int ret;

ret = putenv(var);

APPLICATION USAGE

The putenv() function manipulates the environment pointed to by environ, and can be used in conjunction with getenv().

See exec() , for restrictions on changing the environment in multi-threaded applications.

This routine may use malloc() to enlarge the environment.

A potential error is to call putenv() with an automatic variable as the argument, then return from the calling function while string is still part of the environment.

The setenv() function is preferred over this function.

RATIONALE

The standard developers noted that putenv() is the only function available to add to the environment without permitting memory leaks.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getenv() , malloc() , setenv() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


catgets(3p)

CATGETS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

catgets - read a program message

SYNOPSIS

#include <nl_types.h>

char *catgets(nl_catd catd, int s et_id, int msg_id, const char *s);

DESCRIPTION

The catgets() function shall attempt to read message msg_id, in set set_id, from the message catalog identified by catd. The catd argument is a message catalog descriptor returned from an earlier call to catopen(). The s argument points to a default message string which shall be returned by catgets() if it cannot retrieve the identified message.

The catgets() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

If the identified message is retrieved successfully, catgets() shall return a pointer to an internal buffer area containing the null-terminated message string. If the call is unsuccessful for any reason, s shall be returned and errno may be set to indicate the error.

ERRORS

The catgets() function may fail if:

EBADF
The catd argument is not a valid message catalog descriptor open for reading.
EBADMSG
The message identified by set_id and msg_id in the specified message catalog did not satisfy implementation-defined security criteria.
EINTR
The read operation was terminated due to the receipt of a signal, and no data was transferred.
EINVAL
The message catalog identified by catd is corrupted.
ENOMSG
The message identified by set_id and msg_id is not in the message catalog.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

catclose() , catopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <nl_types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strspn(3p)

STRSPN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strspn - get length of a substring

SYNOPSIS

#include <string.h>

size_t strspn(const char *s1, const char *s2);

DESCRIPTION

The strspn() function shall compute the length (in bytes) of the maximum initial segment of the string pointed to by s1 which consists entirely of bytes from the string pointed to by s2.

RETURN VALUE

The strspn() function shall return the length of s1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strcspn() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getgrnam_r (3p)

 Continue to this page.


mbstowcs(3p)

MBSTOWCS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mbstowcs - convert a character string to a wide-character string

SYNOPSIS

#include <stdlib.h>

size_t mbstowcs(wchar_t *restrict pwcs, const char *restrict s,
size_t n);

DESCRIPTION

The mbstowcs() function shall convert a sequence of characters that begins in the initial shift state from the array pointed to by s into a sequence of corresponding wide-character codes and shall store not more than n wide-character codes into the array pointed to by pwcs. No characters that follow a null byte (which is converted into a wide-character code with value 0) shall be examined or converted. Each character shall be converted as if by a call to mbtowc(), except that the shift state of mbtowc() is not affected.

No more than n elements shall be modified in the array pointed to by pwcs. If copying takes place between objects that overlap, the behavior is undefined.

The behavior of this function shall be affected by the LC_CTYPE category of the current locale. If pwcs is a null pointer, mbstowcs() shall return the length required to convert the entire array regardless of the value of n, but no values are stored.

RETURN VALUE

If an invalid character is encountered, mbstowcs() shall return (size_t)-1 and may set errno to indicate the error.

Otherwise, mbstowcs() shall return the number of the array elements modified (or required if pwcs is null), not including a terminating 0 code, if any. The array shall not be zero-terminated if the value returned is n.

ERRORS

The mbstowcs() function may fail if:

EILSEQ
Invalid byte sequence is detected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mblen() , mbtowc() , wctomb() , wcstombs() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_getspecific(3p)

PTHREAD_GETSPECIFIC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_getspecific, pthread_setspecific - thread-specific data management

SYNOPSIS

#include <pthread.h>

void *pthread_getspecific(pthread_key_t key);
int pthread_setspecific(pthread_key_t key, const void *value);

DESCRIPTION

The pthread_getspecific() function shall return the value currently bound to the specified key on behalf of the calling thread.

The pthread_setspecific() function shall associate a thread-specific value with a key obtained via a previous call to pthread_key_create(). Different threads may bind different values to the same key. These values are typically pointers to blocks of dynamically allocated memory that have been reserved for use by the calling thread.

The effect of calling pthread_getspecific() or pthread_setspecific() with a key value not obtained from pthread_key_create() or after key has been deleted with pthread_key_delete() is undefined.

Both pthread_getspecific() and pthread_setspecific() may be called from a thread-specific data destructor function. A call to pthread_getspecific() for the thread-specific data key being destroyed shall return the value NULL, unless the value is changed (after the destructor starts) by a call to pthread_setspecific(). Calling pthread_setspecific() from a thread-specific data destructor routine may result either in lost storage (after at least PTHREAD_DESTRUCTOR_ITERATIONS attempts at destruction) or in an infinite loop.

Both functions may be implemented as macros.

RETURN VALUE

The pthread_getspecific() function shall return the thread-specific data value associated with the given key. If no thread-specific data value is associated with key, then the value NULL shall be returned.

If successful, the pthread_setspecific() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

No errors are returned from pthread_getspecific().

The pthread_setspecific() function shall fail if:

ENOMEM
Insufficient memory exists to associate the value with the key.

The pthread_setspecific() function may fail if:

EINVAL
The key value is invalid.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Performance and ease-of-use of pthread_getspecific() are critical for functions that rely on maintaining state in thread-specific data. Since no errors are required to be detected by it, and since the only error that could be detected is the use of an invalid key, the function to pthread_getspecific() has been designed to favor speed and simplicity over error reporting.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_key_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dup2 (3p)

 Continue to this page.


semctl(3p)

SEMCTL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

semctl - XSI semaphore control operations

SYNOPSIS

#include <sys/sem.h>

int semctl(int semid, int semnum, int cmd, ...);

DESCRIPTION

The semctl() function operates on XSI semaphores (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.15, Semaphore). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The semctl() function provides a variety of semaphore control operations as specified by cmd. The fourth argument is optional and depends upon the operation requested. If required, it is of type union semun, which the application shall explicitly declare:

union semun {
    int val;
    struct semid_ds *buf;
    unsigned short  *array;
} arg;

The following semaphore control operations as specified by cmd are executed with respect to the semaphore specified by semid and semnum. The level of permission required for each operation is shown with each command; see XSI Interprocess Communication . The symbolic names for the values of cmd are defined in the <sys/sem.h> header:

GETVAL
Return the value of semval; see <sys/sem.h>. Requires read permission.
SETVAL
Set the value of semval to arg.val, where arg is the value of the fourth argument to semctl(). When this command is successfully executed, the semadj value corresponding to the specified semaphore in all processes is cleared. Requires alter permission; see XSI Interprocess Communication .
GETPID
Return the value of sempid. Requires read permission.
GETNCNT
Return the value of semncnt. Requires read permission.
GETZCNT
Return the value of semzcnt. Requires read permission.

The following values of cmd operate on each semval in the set of semaphores:

GETALL
Return the value of semval for each semaphore in the semaphore set and place into the array pointed to by arg.array, where arg is the fourth argument to semctl(). Requires read permission.
SETALL
Set the value of semval for each semaphore in the semaphore set according to the array pointed to by arg.array, where arg is the fourth argument to semctl(). When this command is successfully executed, the semadj values corresponding to each specified semaphore in all processes are cleared. Requires alter permission.

The following values of cmd are also available:

IPC_STAT
Place the current value of each member of the semid_ds data structure associated with semid into the structure pointed to by arg.buf, where arg is the fourth argument to semctl(). The contents of this structure are defined in <sys/sem.h>. Requires read permission.
IPC_SET
Set the value of the following members of the semid_ds data structure associated with semid to the corresponding value found in the structure pointed to by arg.buf, where arg is the fourth argument to semctl():

sem_perm.uid
sem_perm.gid
sem_perm.mode

The mode bits specified in IPC General Description are copied into the corresponding bits of the sem_perm.mode associated with semid. The stored values of any other bits are unspecified.

This command can only be executed by a process that has an effective user ID equal to either that of a process with appropriate privileges or to the value of sem_perm.cuid or sem_perm.uid in the semid_ds data structure associated with semid.

IPC_RMID
Remove the semaphore identifier specified by semid from the system and destroy the set of semaphores and semid_ds data structure associated with it. This command can only be executed by a process that has an effective user ID equal to either that of a process with appropriate privileges or to the value of sem_perm.cuid or sem_perm.uid in the semid_ds data structure associated with semid.

RETURN VALUE

If successful, the value returned by semctl() depends on cmd as follows:

GETVAL
The value of semval.
GETPID
The value of sempid.
GETNCNT
The value of semncnt.
GETZCNT
The value of semzcnt.
All others
0.

Otherwise, semctl() shall return -1 and set errno to indicate the error.

ERRORS

The semctl() function shall fail if:

EACCES
Operation permission is denied to the calling process; see XSI Interprocess Communication .
EINVAL
The value of semid is not a valid semaphore identifier, or the value of semnum is less than 0 or greater than or equal to sem_nsems, or the value of cmd is not a valid command.
EPERM
The argument cmd is equal to IPC_RMID or IPC_SET and the effective user ID of the calling process is not equal to that of a process with appropriate privileges and it is not equal to the value of sem_perm.cuid or sem_perm.uid in the data structure associated with semid.
ERANGE
The argument cmd is equal to SETVAL or SETALL and the value to which semval is to be set is greater than the system-imposed maximum.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The fourth parameter in the SYNOPSIS section is now specified as "..." in order to avoid a clash with the ISO C standard when referring to the union semun (as defined in Issue 3) and for backwards-compatibility.

The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , semget() , semop() , sem_close() , sem_destroy() , sem_getvalue() , sem_init() , sem_open() , sem_post() , sem_unlink() , sem_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/sem.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswpunct(3p)

ISWPUNCT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswpunct - test for a punctuation wide-character code

SYNOPSIS

#include <wctype.h>

int iswpunct(wint_t wc);

DESCRIPTION

The iswpunct() function shall test whether wc is a wide-character code representing a character of class punct in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswpunct() function shall return non-zero if wc is a punctuation wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strstr(3p)

STRSTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strstr - find a substring

SYNOPSIS

#include <string.h>

char *strstr(const char *s1, const char *s2);

DESCRIPTION

The strstr() function shall locate the first occurrence in the string pointed to by s1 of the sequence of bytes (excluding the terminating null byte) in the string pointed to by s2.

RETURN VALUE

Upon successful completion, strstr() shall return a pointer to the located string or a null pointer if the string is not found.

If s2 points to a string with zero length, the function shall return s1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sighold (3p)

 Continue to this page.


sigwait(3p)

SIGWAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigwait - wait for queued signals

SYNOPSIS

#include <signal.h>

int sigwait(const sigset_t *restrict set, int *restrict sig);

DESCRIPTION

The sigwait() function shall select a pending signal from set, atomically clear it from the system's set of pending signals, and return that signal number in the location referenced by sig. If prior to the call to sigwait() there are multiple pending instances of a single signal number, it is implementation-defined whether upon successful return there are any remaining pending signals for that signal number. If the implementation supports queued signals and there are multiple signals queued for the signal number selected, the first such queued signal shall cause a return from sigwait() and the remainder shall remain queued. If no signal in set is pending at the time of the call, the thread shall be suspended until one or more becomes pending. The signals defined by set shall have been blocked at the time of the call to sigwait(); otherwise, the behavior is undefined. The effect of sigwait() on the signal actions for the signals in set is unspecified.

If more than one thread is using sigwait() to wait for the same signal, no more than one of these threads shall return from sigwait() with the signal number. Which thread returns from sigwait() if more than a single thread is waiting is unspecified.

Should any of the multiple pending signals in the range SIGRTMIN to SIGRTMAX be selected, it shall be the lowest numbered one. The selection order between realtime and non-realtime signals, or between multiple pending non-realtime signals, is unspecified.

RETURN VALUE

Upon successful completion, sigwait() shall store the signal number of the received signal at the location referenced by sig and return zero. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The sigwait() function may fail if:

EINVAL
The set argument contains an invalid or unsupported signal number.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

To provide a convenient way for a thread to wait for a signal, this volume of IEEE Std 1003.1-2001 provides the sigwait() function. For most cases where a thread has to wait for a signal, the sigwait() function should be quite convenient, efficient, and adequate.

However, requests were made for a lower-level primitive than sigwait() and for semaphores that could be used by threads. After some consideration, threads were allowed to use semaphores and sem_post() was defined to be async-signal and async-cancel-safe.

In summary, when it is necessary for code run in response to an asynchronous signal to notify a thread, sigwait() should be used to handle the signal. Alternatively, if the implementation provides semaphores, they also can be used, either following sigwait() or from within a signal handling routine previously registered with sigaction().

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , Realtime Signals , pause() , pthread_sigmask() , sigaction() , sigpending() , sigsuspend() , sigwaitinfo() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mlockall(3p)

MLOCKALL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mlockall, munlockall - lock/unlock the address space of a process (REALTIME)

SYNOPSIS

#include <sys/mman.h>

int mlockall(int flags);
int munlockall(void);

DESCRIPTION

The mlockall() function shall cause all of the pages mapped by the address space of a process to be memory-resident until unlocked or until the process exits or execs another process image. The flags argument determines whether the pages to be locked are those currently mapped by the address space of the process, those that are mapped in the future, or both. The flags argument is constructed from the bitwise-inclusive OR of one or more of the following symbolic constants, defined in <sys/mman.h>:

MCL_CURRENT
Lock all of the pages currently mapped into the address space of the process.
MCL_FUTURE
Lock all of the pages that become mapped into the address space of the process in the future, when those mappings are established.

If MCL_FUTURE is specified, and the automatic locking of future mappings eventually causes the amount of locked memory to exceed the amount of available physical memory or any other implementation-defined limit, the behavior is implementation-defined. The manner in which the implementation informs the application of these situations is also implementation-defined.

The munlockall() function shall unlock all currently mapped pages of the address space of the process. Any pages that become mapped into the address space of the process after a call to munlockall() shall not be locked, unless there is an intervening call to mlockall() specifying MCL_FUTURE or a subsequent call to mlockall() specifying MCL_CURRENT. If pages mapped into the address space of the process are also mapped into the address spaces of other processes and are locked by those processes, the locks established by the other processes shall be unaffected by a call by this process to munlockall().

Upon successful return from the mlockall() function that specifies MCL_CURRENT, all currently mapped pages of the process' address space shall be memory-resident and locked. Upon return from the munlockall() function, all currently mapped pages of the process' address space shall be unlocked with respect to the process' address space. The memory residency of unlocked pages is unspecified.

The appropriate privilege is required to lock process memory with mlockall().

RETURN VALUE

Upon successful completion, the mlockall() function shall return a value of zero. Otherwise, no additional memory shall be locked, and the function shall return a value of -1 and set errno to indicate the error. The effect of failure of mlockall() on previously existing locks in the address space is unspecified.

If it is supported by the implementation, the munlockall() function shall always return a value of zero. Otherwise, the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The mlockall() function shall fail if:

EAGAIN
Some or all of the memory identified by the operation could not be locked when the call was made.
EINVAL
The flags argument is zero, or includes unimplemented flags.

The mlockall() function may fail if:

ENOMEM
Locking all of the pages currently mapped into the address space of the process would exceed an implementation-defined limit on the amount of memory that the process may lock.
EPERM
The calling process does not have the appropriate privilege to perform the requested operation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , exit() , fork() , mlock() , munmap() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dlopen(3p)

DLOPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dlopen - gain access to an executable object file

SYNOPSIS

#include <dlfcn.h>

void *dlopen(const char *file, int mode);

DESCRIPTION

The dlopen() function shall make an executable object file specified by file available to the calling program. The class of files eligible for this operation and the manner of their construction are implementation-defined, though typically such files are executable objects such as shared libraries, relocatable files, or programs. Note that some implementations permit the construction of dependencies between such objects that are embedded within files. In such cases, a dlopen() operation shall load such dependencies in addition to the object referenced by file. Implementations may also impose specific constraints on the construction of programs that can employ dlopen() and its related services.

A successful dlopen() shall return a handle which the caller may use on subsequent calls to dlsym() and dlclose(). The value of this handle should not be interpreted in any way by the caller.

The file argument is used to construct a pathname to the object file. If file contains a slash character, the file argument is used as the pathname for the file. Otherwise, file is used in an implementation-defined manner to yield a pathname.

If the value of file is 0, dlopen() shall provide a handle on a global symbol object. This object shall provide access to the symbols from an ordered set of objects consisting of the original program image file, together with any objects loaded at program start-up as specified by that process image file (for example, shared libraries), and the set of objects loaded using a dlopen() operation together with the RTLD_GLOBAL flag. As the latter set of objects can change during execution, the set identified by handle can also change dynamically.

Only a single copy of an object file is brought into the address space, even if dlopen() is invoked multiple times in reference to the file, and even if different pathnames are used to reference the file.

The mode parameter describes how dlopen() shall operate upon file with respect to the processing of relocations and the scope of visibility of the symbols provided within file. When an object is brought into the address space of a process, it may contain references to symbols whose addresses are not known until the object is loaded. These references shall be relocated before the symbols can be accessed. The mode parameter governs when these relocations take place and may have the following values:

RTLD_LAZY
Relocations shall be performed at an implementation-defined time, ranging from the time of the dlopen() call until the first reference to a given symbol occurs. Specifying RTLD_LAZY should improve performance on implementations supporting dynamic symbol binding as a process may not reference all of the functions in any given object. And, for systems supporting dynamic symbol resolution for normal process execution, this behavior mimics the normal handling of process execution.
RTLD_NOW
All necessary relocations shall be performed when the object is first loaded. This may waste some processing if relocations are performed for functions that are never referenced. This behavior may be useful for applications that need to know as soon as an object is loaded that all symbols referenced during execution are available.

Any object loaded by dlopen() that requires relocations against global symbols can reference the symbols in the original process image file, any objects loaded at program start-up, from the object itself as well as any other object included in the same dlopen() invocation, and any objects that were loaded in any dlopen() invocation and which specified the RTLD_GLOBAL flag. To determine the scope of visibility for the symbols loaded with a dlopen() invocation, the mode parameter should be a bitwise-inclusive OR with one of the following values:

RTLD_GLOBAL
The object's symbols shall be made available for the relocation processing of any other object. In addition, symbol lookup using dlopen(0, mode) and an associated dlsym() allows objects loaded with this mode to be searched.
RTLD_LOCAL
The object's symbols shall not be made available for the relocation processing of any other object.

If neither RTLD_GLOBAL nor RTLD_LOCAL are specified, then an implementation-defined default behavior shall be applied.

If a file is specified in multiple dlopen() invocations, mode is interpreted at each invocation. Note, however, that once RTLD_NOW has been specified all relocations shall have been completed rendering further RTLD_NOW operations redundant and any further RTLD_LAZY operations irrelevant. Similarly, note that once RTLD_GLOBAL has been specified the object shall maintain the RTLD_GLOBAL status regardless of any previous or future specification of RTLD_LOCAL, as long as the object remains in the address space (see dlclose() ).

Symbols introduced into a program through calls to dlopen() may be used in relocation activities. Symbols so introduced may duplicate symbols already defined by the program or previous dlopen() operations. To resolve the ambiguities such a situation might present, the resolution of a symbol reference to symbol definition is based on a symbol resolution order. Two such resolution orders are defined: load or dependency ordering. Load order establishes an ordering among symbol definitions, such that the definition first loaded (including definitions from the image file and any dependent objects loaded with it) has priority over objects added later (via dlopen()). Load ordering is used in relocation processing. Dependency ordering uses a breadth-first order starting with a given object, then all of its dependencies, then any dependents of those, iterating until all dependencies are satisfied. With the exception of the global symbol object obtained via a dlopen() operation on a file of 0, dependency ordering is used by the dlsym() function. Load ordering is used in dlsym() operations upon the global symbol object.

When an object is first made accessible via dlopen() it and its dependent objects are added in dependency order. Once all the objects are added, relocations are performed using load order. Note that if an object or its dependencies had been previously loaded, the load and dependency orders may yield different resolutions.

The symbols introduced by dlopen() operations and available through dlsym() are at a minimum those which are exported as symbols of global scope by the object. Typically such symbols shall be those that were specified in (for example) C source code as having extern linkage. The precise manner in which an implementation constructs the set of exported symbols for a dlopen() object is specified by that implementation.

RETURN VALUE

If file cannot be found, cannot be opened for reading, is not of an appropriate object format for processing by dlopen(), or if an error occurs during the process of loading file or relocating its symbolic references, dlopen() shall return NULL. More detailed diagnostic information shall be available through dlerror() .

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

dlclose() , dlerror() , dlsym() , the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_spin_unlock(3p)

PTHREAD_SPIN_UNLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_spin_unlock - unlock a spin lock object (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_spin_unlock(pthread_spinlock_t *lock);

DESCRIPTION

The pthread_spin_unlock() function shall release the spin lock referenced by lock which was locked via the pthread_spin_lock() or pthread_spin_trylock() functions. The results are undefined if the lock is not held by the calling thread. If there are threads spinning on the lock when pthread_spin_unlock() is called, the lock becomes available and an unspecified spinning thread shall acquire the lock.

The results are undefined if this function is called with an uninitialized thread spin lock.

RETURN VALUE

Upon successful completion, the pthread_spin_unlock() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_spin_unlock() function may fail if:

EINVAL
An invalid argument was specified.
EPERM
The calling thread does not hold the lock.

This function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_spin_unlock() function is part of the Spin Locks option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_spin_destroy() , pthread_spin_lock() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


link(3p)

LINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

link - link to a file

SYNOPSIS

#include <unistd.h>

int link(const char *path1, const char *path2);

DESCRIPTION

The link() function shall create a new link (directory entry) for the existing file, path1.

The path1 argument points to a pathname naming an existing file. The path2 argument points to a pathname naming the new directory entry to be created. The link() function shall atomically create a new link for the existing file and the link count of the file shall be incremented by one.

If path1 names a directory, link() shall fail unless the process has appropriate privileges and the implementation supports using link() on directories.

Upon successful completion, link() shall mark for update the st_ctime field of the file. Also, the st_ctime and st_mtime fields of the directory that contains the new entry shall be marked for update.

If link() fails, no link shall be created and the link count of the file shall remain unchanged.

The implementation may require that the calling process has permission to access the existing file.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The link() function shall fail if:

EACCES
A component of either path prefix denies search permission, or the requested link requires writing in a directory that denies write permission, or the calling process does not have permission to access the existing file and this is required by the implementation.
EEXIST
The path2 argument resolves to an existing file or refers to a symbolic link.
ELOOP
A loop exists in symbolic links encountered during resolution of the path1 or path2 argument.
EMLINK
The number of links to the file named by path1 would exceed {LINK_MAX}.
ENAMETOOLONG
The length of the path1 or path2 argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of either path prefix does not exist; the file named by path1 does not exist; or path1 or path2 points to an empty string.
ENOSPC
The directory to contain the link cannot be extended.
ENOTDIR
A component of either path prefix is not a directory.
EPERM
The file named by path1 is a directory and either the calling process does not have appropriate privileges or the implementation prohibits using link() on directories.
EROFS
The requested link requires writing in a directory on a read-only file system.
EXDEV
The link named by path2 and the file named by path1 are on different file systems and the implementation does not support links between file systems.
EXDEV
path1 refers to a named STREAM.

The link() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path1 or path2 argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path1 or path2 argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Creating a Link to a File

The following example shows how to create a link to a file named /home/cnd/mod1 by creating a new directory entry named /modules/pass1.

#include <unistd.h>

char *path1 = "/home/cnd/mod1";
char *path2 = "/modules/pass1";
int   status;
...
status = link (path1, path2);

Creating a Link to a File Within a Program

In the following program example, the link() function links the /etc/passwd file (defined as PASSWDFILE) to a file named /etc/opasswd (defined as SAVEFILE), which is used to save the current password file. Then, after removing the current password file (defined as PASSWDFILE), the new password file is saved as the current password file using the link() function again.

#include <unistd.h>

#define LOCKFILE "/etc/ptmp"
#define PASSWDFILE "/etc/passwd"
#define SAVEFILE "/etc/opasswd"
...
/* Save current password file */
link (PASSWDFILE, SAVEFILE);

/* Remove current password file. */
unlink (PASSWDFILE);

/* Save new password file as current password file. */
link (LOCKFILE,PASSWDFILE);

APPLICATION USAGE

Some implementations do allow links between file systems.

RATIONALE

Linking to a directory is restricted to the superuser in most historical implementations because this capability may produce loops in the file hierarchy or otherwise corrupt the file system. This volume of IEEE Std 1003.1-2001 continues that philosophy by prohibiting link() and unlink() from doing this. Other functions could do it if the implementor designed such an extension.

Some historical implementations allow linking of files on different file systems. Wording was added to explicitly allow this optional behavior.

The exception for cross-file system links is intended to apply only to links that are programmatically indistinguishable from "hard" links.

FUTURE DIRECTIONS

None.

SEE ALSO

symlink() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


trunc(3p)

TRUNC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

trunc, truncf, truncl - round to truncated integer value

SYNOPSIS

#include <math.h>

double trunc(double x);
float truncf(float x);
long double truncl(long double x);

DESCRIPTION

These functions shall round their argument to the integer value, in floating format, nearest to but no larger in magnitude than the argument.

RETURN VALUE

Upon successful completion, these functions shall return the truncated integer value.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strtod(3p)

STRTOD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strtod, strtof, strtold - convert a string to a double-precision number

SYNOPSIS

#include <stdlib.h>

double strtod(const char *restrict nptr, char **restrict endptr);
float strtof(const char *restrict nptr, char **restrict endptr);
long double strtold(const char *restrict nptr, char **restrict endptr);

DESCRIPTION

These functions shall convert the initial portion of the string pointed to by nptr to double, float, and long double representation, respectively. First, they decompose the input string into three parts:

1.
An initial, possibly empty, sequence of white-space characters (as specified by isspace())

2.
A subject sequence interpreted as a floating-point constant or representing infinity or NaN

3.
A final string of one or more unrecognized characters, including the terminating null byte of the input string

Then they shall attempt to convert the subject sequence to a floating-point number, and return the result.

The expected form of the subject sequence is an optional plus or minus sign, then one of the following:

*
A non-empty sequence of decimal digits optionally containing a radix character, then an optional exponent part

*
A 0x or 0X, then a non-empty sequence of hexadecimal digits optionally containing a radix character, then an optional binary exponent part

*
One of INF or INFINITY, ignoring case

*
One of NAN or NAN(n-char-sequence_opt), ignoring case in the NAN part, where:

n-char-sequence:
    digit
    nondigit
    n-char-sequence digit
    n-char-sequence nondigit

The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form. The subject sequence contains no characters if the input string is not of the expected form.

If the subject sequence has the expected form for a floating-point number, the sequence of characters starting with the first digit or the decimal-point character (whichever occurs first) shall be interpreted as a floating constant of the C language, except that the radix character shall be used in place of a period, and that if neither an exponent part nor a radix character appears in a decimal floating-point number, or if a binary exponent part does not appear in a hexadecimal floating-point number, an exponent part of the appropriate type with value zero is assumed to follow the last digit in the string. If the subject sequence begins with a minus sign, the sequence shall be interpreted as negated. A character sequence INF or INFINITY shall be interpreted as an infinity, if representable in the return type, else as if it were a floating constant that is too large for the range of the return type. A character sequence NAN or NAN(n-char-sequence_opt) shall be interpreted as a quiet NaN, if supported in the return type, else as if it were a subject sequence part that does not have the expected form; the meaning of the n-char sequences is implementation-defined. A pointer to the final string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

If the subject sequence has the hexadecimal form and FLT_RADIX is a power of 2, the value resulting from the conversion is correctly rounded.

The radix character is defined in the program's locale (category LC_NUMERIC ). In the POSIX locale, or in a locale where the radix character is not defined, the radix character shall default to a period ( '.' ).

In other than the C or POSIX locales, other implementation-defined subject sequences may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion shall be performed; the value of str is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

The strtod() function shall not change the setting of errno if successful.

Since 0 is returned on error and is also a valid return on success, an application wishing to check for error situations should set errno to 0, then call strtod(), strtof(), or strtold(), then check errno.

RETURN VALUE

Upon successful completion, these functions shall return the converted value. If no conversion could be performed, 0 shall be returned, and errno may be set to [EINVAL].

If the correct value is outside the range of representable values, ±HUGE_VAL, ±HUGE_VALF, or ±HUGE_VALL shall be returned (according to the sign of the value), and errno shall be set to [ERANGE].

If the correct value would cause an underflow, a value whose magnitude is no greater than the smallest normalized positive number in the return type shall be returned and errno set to [ERANGE].

ERRORS

These functions shall fail if:

ERANGE
The value to be returned would cause overflow or underflow.

These functions may fail if:

EINVAL
No conversion could be performed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the subject sequence has the hexadecimal form and FLT_RADIX is not a power of 2, and the result is not exactly representable, the result should be one of the two numbers in the appropriate internal format that are adjacent to the hexadecimal floating source value, with the extra stipulation that the error should have a correct sign for the current rounding direction.

If the subject sequence has the decimal form and at most DECIMAL_DIG (defined in <float.h>) significant digits, the result should be correctly rounded. If the subject sequence D has the decimal form and more than DECIMAL_DIG significant digits, consider the two bounding, adjacent decimal strings L and U, both having DECIMAL_DIG significant digits, such that the values of L, D, and U satisfy L <= D <= U. The result should be one of the (equal or adjacent) values that would be obtained by correctly rounding L and U according to the current rounding direction, with the extra stipulation that the error with respect to D should have a correct sign for the current rounding direction.

The changes to strtod() introduced by the ISO/IEC 9899:1999 standard can alter the behavior of well-formed applications complying with the ISO/IEC 9899:1990 standard and thus earlier versions of the base documents. One such example would be:

int
what_kind_of_number (char *s)
{
    char *endp;
    double d;
    long l;

    d = strtod(s, &endp);
    if (s != endp && *endp == `\0')
        printf("It's a float with value %g\n", d);
    else
    {
        l = strtol(s, &endp, 0);
        if (s != endp && *endp == `\0')
            printf("It's an integer with value %ld\n", 1);
        else
            return 1;
    }
    return 0;
}

If the function is called with:

what_kind_of_number ("0x10")

an ISO/IEC 9899:1990 standard-compliant library will result in the function printing:

It's an integer with value 16

With the ISO/IEC 9899:1999 standard, the result is:

It's a float with value 16

The change in behavior is due to the inclusion of floating-point numbers in hexadecimal notation without requiring that either a decimal point or the binary exponent be present.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isspace() , localeconv() , scanf() , setlocale() , strtol() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <float.h>, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strtof (3p)

 Continue to this page.


strtok(3p)

STRTOK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strtok, strtok_r - split string into tokens

SYNOPSIS

#include <string.h>

char *strtok(char *restrict s1, const char *restrict s2);

char *strtok_r(char *restrict s, const char *restrict sep,
char **restrict lasts);

DESCRIPTION

For strtok(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

A sequence of calls to strtok() breaks the string pointed to by s1 into a sequence of tokens, each of which is delimited by a byte from the string pointed to by s2. The first call in the sequence has s1 as its first argument, and is followed by calls with a null pointer as their first argument. The separator string pointed to by s2 may be different from call to call.

The first call in the sequence searches the string pointed to by s1 for the first byte that is not contained in the current separator string pointed to by s2. If no such byte is found, then there are no tokens in the string pointed to by s1 and strtok() shall return a null pointer. If such a byte is found, it is the start of the first token.

The strtok() function then searches from there for a byte that is contained in the current separator string. If no such byte is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token shall return a null pointer. If such a byte is found, it is overwritten by a null byte, which terminates the current token. The strtok() function saves a pointer to the following byte, from which the next search for a token shall start.

Each subsequent call, with a null pointer as the value of the first argument, starts searching from the saved pointer and behaves as described above.

The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls strtok().

The strtok() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The strtok_r() function considers the null-terminated string s as a sequence of zero or more text tokens separated by spans of one or more characters from the separator string sep. The argument lasts points to a user-provided pointer which points to stored information necessary for strtok_r() to continue scanning the same string.

In the first call to strtok_r(), s points to a null-terminated string, sep to a null-terminated string of separator characters, and the value pointed to by lasts is ignored. The strtok_r() function shall return a pointer to the first character of the first token, write a null character into s immediately following the returned token, and update the pointer to which lasts points.

In subsequent calls, s is a NULL pointer and lasts shall be unchanged from the previous call so that subsequent calls shall move through the string s, returning successive tokens until no tokens remain. The separator string sep may be different from call to call. When no token remains in s, a NULL pointer shall be returned.

RETURN VALUE

Upon successful completion, strtok() shall return a pointer to the first byte of a token. Otherwise, if there is no token, strtok() shall return a null pointer.

The strtok_r() function shall return a pointer to the token found, or a NULL pointer when no token is found.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Searching for Word Separators

The following example searches for tokens separated by <space>s.

#include <string.h>
...
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";

/* Token will point to "LINE". */
token = strtok(line, search);

/* Token will point to "TO". */
token = strtok(NULL, search);

Breaking a Line

The following example uses strtok() to break a line into two character strings separated by any combination of <space>s, <tab>s, or <newline>s.

#include <string.h>
...
struct element {
    char *key;
    char *data;
};
...
char line[LINE_MAX];
char *key, *data;
...
key = strtok(line, "    \n");
data = strtok(NULL, "   \n");
...

APPLICATION USAGE

The strtok_r() function is thread-safe and stores its state in a user-supplied buffer instead of possibly using a static data area that may be overwritten by an unrelated call from another thread.

RATIONALE

The strtok() function searches for a separator string within a larger string. It returns a pointer to the last substring between separator strings. This function uses static storage to keep track of the current string position between calls. The new function, strtok_r(), takes an additional argument, lasts, to keep track of the current position in the string.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strtol(3p)

STRTOL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strtol, strtoll - convert a string to a long integer

SYNOPSIS

#include <stdlib.h>

long strtol(const char *restrict str, char **restrict endptr, int base);
long long strtoll(const char *restrict str, char **restrict endptr,
int base)

DESCRIPTION

These functions shall convert the initial portion of the string pointed to by str to a type long and long long representation, respectively. First, they decompose the input string into three parts:

1.
An initial, possibly empty, sequence of white-space characters (as specified by isspace())

2.
A subject sequence interpreted as an integer represented in some radix determined by the value of base

3.
A final string of one or more unrecognized characters, including the terminating null byte of the input string.

Then they shall attempt to convert the subject sequence to an integer, and return the result.

If the value of base is 0, the expected form of the subject sequence is that of a decimal constant, octal constant, or hexadecimal constant, any of which may be preceded by a '+' or '-' sign. A decimal constant begins with a non-zero digit, and consists of a sequence of decimal digits. An octal constant consists of the prefix '0' optionally followed by a sequence of the digits '0' to '7' only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and letters 'a' (or 'A' ) to 'f' (or 'F' ) with values 10 to 15 respectively.

If the value of base is between 2 and 36, the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a '+' or '-' sign. The letters from 'a' (or 'A' ) to 'z' (or 'Z' ) inclusive are ascribed the values 10 to 35; only letters whose ascribed values are less than that of base are permitted. If the value of base is 16, the characters 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.

The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character that is of the expected form. The subject sequence shall contain no characters if the input string is empty or consists entirely of white-space characters, or if the first non-white-space character is other than a sign or a permissible letter or digit.

If the subject sequence has the expected form and the value of base is 0, the sequence of characters starting with the first digit shall be interpreted as an integer constant. If the subject sequence has the expected form and the value of base is between 2 and 36, it shall be used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion shall be negated. A pointer to the final string shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

In other than the C or POSIX locales, other implementation-defined subject sequences may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of str is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

The strtol() function shall not change the setting of errno if successful.

Since 0, {LONG_MIN} or {LLONG_MIN}, and {LONG_MAX} or {LLONG_MAX} are returned on error and are also valid returns on success, an application wishing to check for error situations should set errno to 0, then call strtol() or strtoll(), then check errno.

RETURN VALUE

Upon successful completion, these functions shall return the converted value, if any. If no conversion could be performed, 0 shall be returned and errno may be set to [EINVAL].

If the correct value is outside the range of representable values, {LONG_MIN}, {LONG_MAX}, {LLONG_MIN}, or {LLONG_MAX} shall be returned (according to the sign of the value), and errno set to [ERANGE].

ERRORS

These functions shall fail if:

ERANGE
The value to be returned is not representable.

These functions may fail if:

EINVAL
The value of base is not supported.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalpha() , scanf() , strtod() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcrtomb(3p)

WCRTOMB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcrtomb - convert a wide-character code to a character (restartable)

SYNOPSIS

#include <stdio.h>

size_t wcrtomb(char *restrict s, wchar_t wc, mbstate_t *restrict ps);

DESCRIPTION

If s is a null pointer, the wcrtomb() function shall be equivalent to the call:

wcrtomb(buf, L'\0', ps)

where buf is an internal buffer.

If s is not a null pointer, the wcrtomb() function shall determine the number of bytes needed to represent the character that corresponds to the wide character given by wc (including any shift sequences), and store the resulting bytes in the array whose first element is pointed to by s. At most {MB_CUR_MAX} bytes are stored. If wc is a null wide character, a null byte shall be stored, preceded by any shift sequence needed to restore the initial shift state. The resulting state described shall be the initial conversion state.

If ps is a null pointer, the wcrtomb() function shall use its own internal mbstate_t object, which is initialized at program start-up to the initial conversion state. Otherwise, the mbstate_t object pointed to by ps shall be used to completely describe the current conversion state of the associated character sequence. The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls wcrtomb().

If the application uses any of the _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS functions, the application shall ensure that the wcrtomb() function is called with a non-NULL ps argument.

The behavior of this function shall be affected by the LC_CTYPE category of the current locale.

RETURN VALUE

The wcrtomb() function shall return the number of bytes stored in the array object (including any shift sequences). When wc is not a valid wide character, an encoding error shall occur. In this case, the function shall store the value of the macro [EILSEQ] in errno and shall return (size_t)-1; the conversion state shall be undefined.

ERRORS

The wcrtomb() function may fail if:

EINVAL
ps points to an object that contains an invalid conversion state.
EILSEQ
Invalid wide-character code is detected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mbsinit() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setbuf(3p)

SETBUF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setbuf - assign buffering to a stream

SYNOPSIS

#include <stdio.h>

void setbuf(FILE *restrict stream, char *restrict buf);

DESCRIPTION

Except that it returns no value, the function call:

setbuf(stream, buf)

shall be equivalent to:

setvbuf(stream, buf, _IOFBF, BUFSIZ)

if buf is not a null pointer, or to:

setvbuf(stream, buf, _IONBF, BUFSIZ)

if buf is a null pointer.

RETURN VALUE

The setbuf() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

A common source of error is allocating buffer space as an "automatic" variable in a code block, and then failing to close the stream in the same block.

With setbuf(), allocating a buffer of BUFSIZ bytes does not necessarily imply that all of BUFSIZ bytes are used for the buffer area.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , setvbuf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_getschedparam(3p)

PTHREAD_ATTR_GETSCHEDPARAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getschedparam, pthread_attr_setschedparam - get and set the schedparam attribute

SYNOPSIS

#include <pthread.h>

int pthread_attr_getschedparam(const pthread_attr_t *restrict attr,
struct sched_param *restrict param);
int pthread_attr_setschedparam(pthread_attr_t *restrict attr,
const struct sched_param *restrict param);

DESCRIPTION

The pthread_attr_getschedparam(), and pthread_attr_setschedparam() functions, respectively, shall get and set the scheduling parameter attributes in the attr argument. The contents of the param structure are defined in the <sched.h> header. For the SCHED_FIFO and SCHED_RR policies, the only required member of param is sched_priority.

For the SCHED_SPORADIC policy, the required members of the param structure are sched_priority, sched_ss_low_priority, sched_ss_repl_period, sched_ss_init_budget, and sched_ss_max_repl. The specified sched_ss_repl_period must be greater than or equal to the specified sched_ss_init_budget for the function to succeed; if it is not, then the function shall fail. The value of sched_ss_max_repl shall be within the inclusive range [1, {SS_REPL_MAX}] for the function to succeed; if not, the function shall fail.

RETURN VALUE

If successful, the pthread_attr_getschedparam() and pthread_attr_setschedparam() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_attr_setschedparam() function may fail if:

EINVAL
The value of param is not valid.
ENOTSUP
An attempt was made to set the attribute to an unsupported value.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

After these attributes have been set, a thread can be created with the specified attributes using pthread_create(). Using these routines does not affect the current running thread.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_attr_getscope() , pthread_attr_getinheritsched() , pthread_attr_getschedpolicy() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fabs(3p)

FABS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fabs, fabsf, fabsl - absolute value function

SYNOPSIS

#include <math.h>

double fabs(double x);
float fabsf(float x);
long double fabsl(long double x);

DESCRIPTION

These functions shall compute the absolute value of their argument x,| x|.

RETURN VALUE

Upon successful completion, these functions shall return the absolute value of x.

If x is NaN, a NaN shall be returned.

If x is ±0, +0 shall be returned.

If x is ±Inf, +Inf shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


localtime(3p)

LOCALTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

localtime, localtime_r - convert a time value to a broken-down local time

SYNOPSIS

#include <time.h>

struct tm *localtime(const time_t *timer);

struct tm *localtime_r(const time_t *restrict timer,
struct tm *restrict result);

DESCRIPTION

For localtime(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The localtime() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as a local time. The function corrects for the timezone and any seasonal time adjustments. Local timezone information is used as though localtime() calls tzset().

The relationship between a time in seconds since the Epoch used as an argument to localtime() and the tm structure (defined in the <time.h> header) is that the result shall be as specified in the expression given in the definition of seconds since the Epoch (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.14, Seconds Since the Epoch) corrected for timezone and any seasonal time adjustments, where the names in the structure and in the expression correspond.

The same relationship shall apply for localtime_r().

The localtime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.

The localtime_r() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time stored in the structure to which result points. The localtime_r() function shall also return a pointer to that same structure.

Unlike localtime(), the reentrant version is not required to set tzname.

RETURN VALUE

Upon successful completion, the localtime() function shall return a pointer to the broken-down time structure. If an error is detected, localtime() shall return a null pointer and set errno to indicate the error.

Upon successful completion, localtime_r() shall return a pointer to the structure pointed to by the argument result.

ERRORS

The localtime() function shall fail if:

EOVERFLOW
The result cannot be represented.

The following sections are informative.

EXAMPLES

Getting the Local Date and Time

The following example uses the time() function to calculate the time elapsed, in seconds, since January 1, 1970 0:00 UTC (the Epoch), localtime() to convert that value to a broken-down time, and asctime() to convert the broken-down time values into a printable string.

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t result;

    result = time(NULL);
    printf("%s%ju secs since the Epoch\n",
        asctime(localtime(&result)),
            (uintmax_t)result);
    return(0);
}

This example writes the current time to stdout in a form like this:

Wed Jun 26 10:32:15 1996
835810335 secs since the Epoch

Getting the Modification Time for a File

The following example gets the modification time for a file. The localtime() function converts the time_t value of the last modification date, obtained by a previous call to stat(), into a tm structure that contains the year, month, day, and so on.

#include <time.h>
...
struct stat statbuf;
...
tm = localtime(&statbuf.st_mtime);
...

Timing an Event

The following example gets the current time, converts it to a string using localtime() and asctime(), and prints it to standard output using fputs(). It then prints the number of minutes to an event being timed.

#include <time.h>
#include <stdio.h>
...
time_t now;
int minutes_to_event;
...
time(&now);
printf("The time is ");
fputs(asctime(localtime(&now)), stdout);
printf("There are still %d minutes to the event.\n",
    minutes_to_event);
...

APPLICATION USAGE

The localtime_r() function is thread-safe and returns values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asctime() , clock() , ctime() , difftime() , getdate() , gmtime() , mktime() , strftime() , strptime() , time() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_create(3p)

POSIX_TRACE_CREATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_create, posix_trace_create_withlog, posix_trace_flush, posix_trace_shutdown - trace stream initialization, flush, and shutdown from a process (TRACING)

SYNOPSIS

#include <sys/types.h>
#include <trace.h>

int posix_trace_create(pid_t pid,
const trace_attr_t *restrict attr,
trace_id_t *restrict trid);

int posix_trace_create_withlog(pid_t pid,
const trace_attr_t *restrict attr, int file_desc,
trace_id_t *restrict trid);
int posix_trace_flush(trace_id_t trid);

int posix_trace_shutdown(trace_id_t trid);

DESCRIPTION

The posix_trace_create() function shall create an active trace stream. It allocates all the resources needed by the trace stream being created for tracing the process specified by pid in accordance with the attr argument. The attr argument represents the initial attributes of the trace stream and shall have been initialized by the function posix_trace_attr_init() prior to the posix_trace_create() call. If the argument attr is NULL, the default attributes shall be used. The attr attributes object shall be manipulated through a set of functions described in the posix_trace_attr family of functions. If the attributes of the object pointed to by attr are modified later, the attributes of the trace stream shall not be affected. The creation-time attribute of the newly created trace stream shall be set to the value of the system clock, if the Timers option is not supported, or to the value of the CLOCK_REALTIME clock, if the Timers option is supported.

The pid argument represents the target process to be traced. If the process executing this function does not have appropriate privileges to trace the process identified by pid, an error shall be returned. If the pid argument is zero, the calling process shall be traced.

The posix_trace_create() function shall store the trace stream identifier of the new trace stream in the object pointed to by the trid argument. This trace stream identifier shall be used in subsequent calls to control tracing. The trid argument may only be used by the following functions:

posix_trace_clear()
posix_trace_eventid_equal()
posix_trace_eventid_get_name()
posix_trace_eventtypelist_getnext_id()
posix_trace_eventtypelist_rewind()
posix_trace_get_attr()
posix_trace_get_status()

posix_trace_getnext_event()
posix_trace_shutdown()
posix_trace_start()
posix_trace_stop()
posix_trace_timedgetnext_event()
posix_trace_trid_eventid_open()
posix_trace_trygetnext_event()

If the Trace Event Filter option is supported, the following additional functions may use the trid argument:
posix_trace_get_filter() posix_trace_set_filter()

In particular, notice that the operations normally used by a trace analyzer process, such as posix_trace_rewind() or posix_trace_close(), cannot be invoked using the trace stream identifier returned by the posix_trace_create() function.

A trace stream shall be created in a suspended state. If the Trace Event Filter option is supported, its trace event type filter shall be empty.

The posix_trace_create() function may be called multiple times from the same or different processes, with the system-wide limit indicated by the runtime invariant value {TRACE_SYS_MAX}, which has the minimum value {_POSIX_TRACE_SYS_MAX}.

The trace stream identifier returned by the posix_trace_create() function in the argument pointed to by trid is valid only in the process that made the function call. If it is used from another process, that is a child process, in functions defined in IEEE Std 1003.1-2001, these functions shall return with the error [EINVAL].

The posix_trace_create_withlog() function shall be equivalent to posix_trace_create(), except that it associates a trace log with this stream. The file_desc argument shall be the file descriptor designating the trace log destination. The function shall fail if this file descriptor refers to a file with a file type that is not compatible with the log policy associated with the trace log. The list of the appropriate file types that are compatible with each log policy is implementation-defined.

The posix_trace_create_withlog() function shall return in the parameter pointed to by trid the trace stream identifier, which uniquely identifies the newly created trace stream, and shall be used in subsequent calls to control tracing. The trid argument may only be used by the following functions:

posix_trace_clear()
posix_trace_eventid_equal()
posix_trace_eventid_get_name()
posix_trace_eventtypelist_getnext_id()
posix_trace_eventtypelist_rewind()
posix_trace_flush()
posix_trace_get_attr()
posix_trace_get_status()

posix_trace_getnext_event()
posix_trace_shutdown()
posix_trace_start()
posix_trace_stop()
posix_trace_timedgetnext_event()
posix_trace_trid_eventid_open()
posix_trace_trygetnext_event()

If the Trace Event Filter option is supported, the following additional functions may use the trid argument:
posix_trace_get_filter() posix_trace_set_filter()

In particular, notice that the operations normally used by a trace analyzer process, such as posix_trace_rewind() or posix_trace_close(), cannot be invoked using the trace stream identifier returned by the posix_trace_create_withlog() function.

The posix_trace_flush() function shall initiate a flush operation which copies the contents of the trace stream identified by the argument trid into the trace log associated with the trace stream at the creation time. If no trace log has been associated with the trace stream pointed to by trid, this function shall return an error. The termination of the flush operation can be polled by the posix_trace_get_status() function. During the flush operation, it shall be possible to trace new trace events up to the point when the trace stream becomes full. After flushing is completed, the space used by the flushed trace events shall be available for tracing new trace events.

If flushing the trace stream causes the resulting trace log to become full, the trace log full policy shall be applied. If the trace log-full-policy attribute is set, the following occurs:

POSIX_TRACE_UNTIL_FULL

The trace events that have not yet been flushed shall be discarded.

POSIX_TRACE_LOOP

The trace events that have not yet been flushed shall be written to the beginning of the trace log, overwriting previous trace events stored there.

POSIX_TRACE_APPEND

The trace events that have not yet been flushed shall be appended to the trace log.

The posix_trace_shutdown() function shall stop the tracing of trace events in the trace stream identified by trid, as if posix_trace_stop() had been invoked. The posix_trace_shutdown() function shall free all the resources associated with the trace stream.

The posix_trace_shutdown() function shall not return until all the resources associated with the trace stream have been freed. When the posix_trace_shutdown() function returns, the trid argument becomes an invalid trace stream identifier. A call to this function shall unconditionally deallocate the resources regardless of whether all trace events have been retrieved by the analyzer process. Any thread blocked on one of the trace_getnext_event() functions (which specified this trid) before this call is unblocked with the error [EINVAL].

If the process exits, invokes a member of the exec family of functions, or is terminated, the trace streams that the process had created and that have not yet been shut down, shall be automatically shut down as if an explicit call were made to the posix_trace_shutdown() function.

For an active trace stream with log, when the posix_trace_shutdown() function is called, all trace events that have not yet been flushed to the trace log shall be flushed, as in the posix_trace_flush() function, and the trace log shall be closed.

When a trace log is closed, all the information that may be retrieved later from the trace log through the trace interface shall have been written to the trace log. This information includes the trace attributes, the list of trace event types (with the mapping between trace event names and trace event type identifiers), and the trace status.

In addition, unspecified information shall be written to the trace log to allow detection of a valid trace log during the posix_trace_open() operation.

The posix_trace_shutdown() function shall not return until all trace events have been flushed.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

The posix_trace_create() and posix_trace_create_withlog() functions store the trace stream identifier value in the object pointed to by trid, if successful.

ERRORS

The posix_trace_create() and posix_trace_create_withlog() functions shall fail if:

EAGAIN
No more trace streams can be started now. {TRACE_SYS_MAX} has been exceeded.
EINTR
The operation was interrupted by a signal. No trace stream was created.
EINVAL
One or more of the trace parameters specified by the attr parameter is invalid.
ENOMEM
The implementation does not currently have sufficient memory to create the trace stream with the specified parameters.
EPERM
The caller does not have appropriate privilege to trace the process specified by pid.
ESRCH
The pid argument does not refer to an existing process.

The posix_trace_create_withlog() function shall fail if:

EBADF
The file_desc argument is not a valid file descriptor open for writing.
EINVAL
The file_desc argument refers to a file with a file type that does not support the log policy associated with the trace log.
ENOSPC
No space left on device. The device corresponding to the argument file_desc does not contain the space required to create this trace log.

The posix_trace_flush() and posix_trace_shutdown() functions shall fail if:

EINVAL
The value of the trid argument does not correspond to an active trace stream with log.
EFBIG
The trace log file has attempted to exceed an implementation-defined maximum file size.
ENOSPC
No space left on device.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clock_getres() , exec() , posix_trace_attr_init()
, posix_trace_clear() , posix_trace_close() , posix_trace_eventid_equal()
, posix_trace_eventtypelist_getnext_id() , posix_trace_flush()
, posix_trace_get_attr() ,
posix_trace_get_filter() , posix_trace_get_status() ,
posix_trace_getnext_event() , posix_trace_open() , posix_trace_set_filter()
,
posix_trace_shutdown() , posix_trace_start() , posix_trace_timedgetnext_event()
, posix_trace_trid_eventid_open() , posix_trace_start()
, time() , the Base Definitions volume of
IEEE Std 1003.1-2001, <sys/types.h>, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


endprotoent (3p)

 Continue to this page.


lldiv (3p)

 Continue to this page.


endpwent (3p)

 Continue to this page.


dbm_open(3p)

DBM_CLEARERR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dbm_clearerr, dbm_close, dbm_delete, dbm_error, dbm_fetch, dbm_firstkey, dbm_nextkey, dbm_open, dbm_store - database functions

SYNOPSIS

#include <ndbm.h>

int dbm_clearerr(DBM *db);
void dbm_close(DBM *db);
int dbm_delete(DBM *db, datum key);
int dbm_error(DBM *db);
datum dbm_fetch(DBM *db, datum key);
datum dbm_firstkey(DBM *db);
datum dbm_nextkey(DBM *db);
DBM *dbm_open(const char *file, int open_flags,
mode_t file_mode);
int dbm_store(DBM *db, datum key, datum
content, int
store_mode);

DESCRIPTION

These functions create, access, and modify a database.

A datum consists of at least two members, dptr and dsize. The dptr member points to an object that is dsize bytes in length. Arbitrary binary data, as well as character strings, may be stored in the object pointed to by dptr.

The database is stored in two files. One file is a directory containing a bitmap of keys and has .dir as its suffix. The second file contains all data and has .pag as its suffix.

The dbm_open() function shall open a database. The file argument to the function is the pathname of the database. The function opens two files named file.dir and file.pag. The open_flags argument has the same meaning as the flags argument of open() except that a database opened for write-only access opens the files for read and write access and the behavior of the O_APPEND flag is unspecified. The file_mode argument has the same meaning as the third argument of open().

The dbm_close() function shall close a database. The application shall ensure that argument db is a pointer to a dbm structure that has been returned from a call to dbm_open().

These database functions shall support an internal block size large enough to support key/content pairs of at least 1023 bytes.

The dbm_fetch() function shall read a record from a database. The argument db is a pointer to a database structure that has been returned from a call to dbm_open(). The argument key is a datum that has been initialized by the application to the value of the key that matches the key of the record the program is fetching.

The dbm_store() function shall write a record to a database. The argument db is a pointer to a database structure that has been returned from a call to dbm_open(). The argument key is a datum that has been initialized by the application to the value of the key that identifies (for subsequent reading, writing, or deleting) the record the application is writing. The argument content is a datum that has been initialized by the application to the value of the record the program is writing. The argument store_mode controls whether dbm_store() replaces any pre-existing record that has the same key that is specified by the key argument. The application shall set store_mode to either DBM_INSERT or DBM_REPLACE. If the database contains a record that matches the key argument and store_mode is DBM_REPLACE, the existing record shall be replaced with the new record. If the database contains a record that matches the key argument and store_mode is DBM_INSERT, the existing record shall be left unchanged and the new record ignored. If the database does not contain a record that matches the key argument and store_mode is either DBM_INSERT or DBM_REPLACE, the new record shall be inserted in the database.

If the sum of a key/content pair exceeds the internal block size, the result is unspecified. Moreover, the application shall ensure that all key/content pairs that hash together fit on a single block. The dbm_store() function shall return an error in the event that a disk block fills with inseparable data.

The dbm_delete() function shall delete a record and its key from the database. The argument db is a pointer to a database structure that has been returned from a call to dbm_open(). The argument key is a datum that has been initialized by the application to the value of the key that identifies the record the program is deleting.

The dbm_firstkey() function shall return the first key in the database. The argument db is a pointer to a database structure that has been returned from a call to dbm_open().

The dbm_nextkey() function shall return the next key in the database. The argument db is a pointer to a database structure that has been returned from a call to dbm_open(). The application shall ensure that the dbm_firstkey() function is called before calling dbm_nextkey(). Subsequent calls to dbm_nextkey() return the next key until all of the keys in the database have been returned.

The dbm_error() function shall return the error condition of the database. The argument db is a pointer to a database structure that has been returned from a call to dbm_open().

The dbm_clearerr() function shall clear the error condition of the database. The argument db is a pointer to a database structure that has been returned from a call to dbm_open().

The dptr pointers returned by these functions may point into static storage that may be changed by subsequent calls.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The dbm_store() and dbm_delete() functions shall return 0 when they succeed and a negative value when they fail.

The dbm_store() function shall return 1 if it is called with a flags value of DBM_INSERT and the function finds an existing record with the same key.

The dbm_error() function shall return 0 if the error condition is not set and return a non-zero value if the error condition is set.

The return value of dbm_clearerr() is unspecified.

The dbm_firstkey() and dbm_nextkey() functions shall return a key datum. When the end of the database is reached, the dptr member of the key is a null pointer. If an error is detected, the dptr member of the key shall be a null pointer and the error condition of the database shall be set.

The dbm_fetch() function shall return a content datum. If no record in the database matches the key or if an error condition has been detected in the database, the dptr member of the content shall be a null pointer.

The dbm_open() function shall return a pointer to a database structure. If an error is detected during the operation, dbm_open() shall return a ( DBM *)0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The following code can be used to traverse the database:

for(key = dbm_firstkey(db); key.dptr != NULL; key = dbm_nextkey(db))

The dbm_* functions provided in this library should not be confused in any way with those of a general-purpose database management system. These functions do not provide for multiple search keys per entry, they do not protect against multi-user access (in other words they do not lock records or files), and they do not provide the many other useful database functions that are found in more robust database management systems. Creating and updating databases by use of these functions is relatively slow because of data copies that occur upon hash collisions. These functions are useful for applications requiring fast lookup of relatively static information that is to be indexed by a single key.

Note that a strictly conforming application is extremely limited by these functions: since there is no way to determine that the keys in use do not all hash to the same value (although that would be rare), a strictly conforming application cannot be guaranteed that it can store more than one block's worth of data in the database. As long as a key collision does not occur, additional data may be stored, but because there is no way to determine whether an error is due to a key collision or some other error condition ( dbm_error() being effectively a Boolean), once an error is detected, the application is effectively limited to guessing what the error might be if it wishes to continue using these functions.

The dbm_delete() function need not physically reclaim file space, although it does make it available for reuse by the database.

After calling dbm_store() or dbm_delete() during a pass through the keys by dbm_firstkey() and dbm_nextkey(), the application should reset the database by calling dbm_firstkey() before again calling dbm_nextkey(). The contents of these files are unspecified and may not be portable.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

open() , the Base Definitions volume of IEEE Std 1003.1-2001, <ndbm.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strpbrk(3p)

STRPBRK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strpbrk - scan a string for a byte

SYNOPSIS

#include <string.h>

char *strpbrk(const char *s1, const char *s2);

DESCRIPTION

The strpbrk() function shall locate the first occurrence in the string pointed to by s1 of any byte from the string pointed to by s2.

RETURN VALUE

Upon successful completion, strpbrk() shall return a pointer to the byte or a null pointer if no byte from s2 occurs in s1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strchr() , strrchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fopen(3p)

FOPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fopen - open a stream

SYNOPSIS

#include <stdio.h>

FILE *fopen(const char *restrict filename, const char *restrict mode);

DESCRIPTION

The fopen() function shall open the file whose pathname is the string pointed to by filename, and associates a stream with it.

The mode argument points to a string. If the string is one of the following, the file shall be opened in the indicated mode. Otherwise, the behavior is undefined.

r or rb
Open file for reading.
w or wb
Truncate to zero length or create file for writing.
a or ab
Append; open or create file for writing at end-of-file.
r+ or rb+ or r+b
Open file for update (reading and writing).
w+ or wb+ or w+b
Truncate to zero length or create file for update.
a+ or ab+ or a+b
Append; open or create file for update, writing at end-of-file.

The character 'b' shall have no effect, but is allowed for ISO C standard conformance. Opening a file with read mode (r as the first character in the mode argument) shall fail if the file does not exist or cannot be read.

Opening a file with append mode (a as the first character in the mode argument) shall cause all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to fseek().

When a file is opened with update mode ( '+' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, the application shall ensure that output is not directly followed by input without an intervening call to fflush() or to a file positioning function ( fseek(), fsetpos(), or rewind()), and input is not directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device. The error and end-of-file indicators for the stream shall be cleared.

If mode is w, wb, a, ab, w+, wb+, w+b, a+, ab+, or a+b, and the file did not previously exist, upon successful completion, the fopen() function shall mark for update the st_atime, st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.

If mode is w, wb, w+, wb+, or w+b, and the file did previously exist, upon successful completion, fopen() shall mark for update the st_ctime and st_mtime fields of the file. The fopen() function shall allocate a file descriptor as open() does.

After a successful call to the fopen() function, the orientation of the stream shall be cleared, the encoding rule shall be cleared, and the associated mbstate_t object shall be set to describe an initial conversion state.

The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description.

RETURN VALUE

Upon successful completion, fopen() shall return a pointer to the object controlling the stream. Otherwise, a null pointer shall be returned, and errno shall be set to indicate the error.

ERRORS

The fopen() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created.
EINTR
A signal was caught during fopen().
EISDIR
The named file is a directory and mode requires write access.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG

The length of the filename argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

ENFILE
The maximum allowable number of files is currently open in the system.
ENOENT
A component of filename does not name an existing file or filename is an empty string.
ENOSPC
The directory or file system that would contain the new file cannot be expanded, the file does not exist, and the file was to be created.
ENOTDIR
A component of the path prefix is not a directory.
ENXIO
The named file is a character special or block special file, and the device associated with this special file does not exist.
EOVERFLOW
The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only file system and mode requires write access.

The fopen() function may fail if:

EINVAL
The value of the mode argument is not valid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
EMFILE
{FOPEN_MAX} streams are currently open in the calling process.
EMFILE
{STREAM_MAX} streams are currently open in the calling process.
ENAMETOOLONG

Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

ENOMEM
Insufficient storage space is available.
ETXTBSY
The file is a pure procedure (shared text) file that is being executed and mode requires write access.

The following sections are informative.

EXAMPLES

Opening a File

The following example tries to open the file named file for reading. The fopen() function returns a file pointer that is used in subsequent fgets() and fclose() calls. If the program cannot open the file, it just ignores it.

#include <stdio.h>
...
FILE *fp;
...
void rgrep(const char *file)
{
...
    if ((fp = fopen(file, "r")) == NULL)
        return;
...
}

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fclose() , fdopen() , freopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sinf (3p)

 Continue to this page.


sinh(3p)

SINH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sinh, sinhf, sinhl - hyperbolic sine functions

SYNOPSIS

#include <math.h>

double sinh(double x);
float sinhf(float x);
long double sinhl(long double x);

DESCRIPTION

These functions shall compute the hyperbolic sine of their argument x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the hyperbolic sine of x.

If the result would cause an overflow, a range error shall occur and ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (with the same sign as x) shall be returned as appropriate for the type of the function.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions shall fail if:

Range Error
The result would cause an overflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The value x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asinh() , cosh() , feclearexcept() , fetestexcept() , isnan() , tanh() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sinl (3p)

 Continue to this page.


cabsf (3p)

 Continue to this page.


inet_pton (3p)

 Continue to this page.


cabsl (3p)

 Continue to this page.


syslog(3p)

CLOSELOG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

closelog, openlog, setlogmask, syslog - control system log

SYNOPSIS

#include <syslog.h>

void closelog(void);
void openlog(const char *ident, int logopt, int facility);
int setlogmask(int maskpri);
void syslog(int priority, const char *message, ... /* arguments */);

DESCRIPTION

The syslog() function shall send a message to an implementation-defined logging facility, which may log it in an implementation-defined system log, write it to the system console, forward it to a list of users, or forward it to the logging facility on another host over the network. The logged message shall include a message header and a message body. The message header contains at least a timestamp and a tag string.

The message body is generated from the message and following arguments in the same manner as if these were arguments to printf(), except that the additional conversion specification %m shall be recognized; it shall convert no arguments, shall cause the output of the error message string associated with the value of errno on entry to syslog(), and may be mixed with argument specifications of the "%n$" form. If a complete conversion specification with the m conversion specifier character is not just %m , the behavior is undefined. A trailing <newline> may be added if needed.

Values of the priority argument are formed by OR'ing together a severity-level value and an optional facility value. If no facility value is specified, the current default facility value is used.

Possible values of severity level include:

LOG_EMERG
A panic condition.
LOG_ALERT
A condition that should be corrected immediately, such as a corrupted system database.
LOG_CRIT
Critical conditions, such as hard device errors.
LOG_ERR
Errors.
LOG_WARNING

Warning messages.

LOG_NOTICE
Conditions that are not error conditions, but that may require special handling.
LOG_INFO
Informational messages.
LOG_DEBUG
Messages that contain information normally of use only when debugging a program.

The facility indicates the application or system component generating the message. Possible facility values include:

LOG_USER
Messages generated by arbitrary processes. This is the default facility identifier if none is specified.
LOG_LOCAL0
Reserved for local use.
LOG_LOCAL1
Reserved for local use.
LOG_LOCAL2
Reserved for local use.
LOG_LOCAL3
Reserved for local use.
LOG_LOCAL4
Reserved for local use.
LOG_LOCAL5
Reserved for local use.
LOG_LOCAL6
Reserved for local use.
LOG_LOCAL7
Reserved for local use.

The openlog() function shall set process attributes that affect subsequent calls to syslog(). The ident argument is a string that is prepended to every message. The logopt argument indicates logging options. Values for logopt are constructed by a bitwise-inclusive OR of zero or more of the following:

LOG_PID
Log the process ID with each message. This is useful for identifying specific processes.
LOG_CONS
Write messages to the system console if they cannot be sent to the logging facility. The syslog() function ensures that the process does not acquire the console as a controlling terminal in the process of writing the message.
LOG_NDELAY
Open the connection to the logging facility immediately. Normally the open is delayed until the first message is logged. This is useful for programs that need to manage the order in which file descriptors are allocated.
LOG_ODELAY
Delay open until syslog() is called.
LOG_NOWAIT
Do not wait for child processes that may have been created during the course of logging the message. This option should be used by processes that enable notification of child termination using SIGCHLD, since syslog() may otherwise block waiting for a child whose exit status has already been collected.

The facility argument encodes a default facility to be assigned to all messages that do not have an explicit facility already encoded. The initial default facility is LOG_USER.

The openlog() and syslog() functions may allocate a file descriptor. It is not necessary to call openlog() prior to calling syslog().

The closelog() function shall close any open file descriptors allocated by previous calls to openlog() or syslog().

The setlogmask() function shall set the log priority mask for the current process to maskpri and return the previous mask. If the maskpri argument is 0, the current log mask is not modified. Calls by the current process to syslog() with a priority not set in maskpri shall be rejected. The default log mask allows all priorities to be logged. A call to openlog() is not required prior to calling setlogmask().

Symbolic constants for use as values of the logopt, facility, priority, and maskpri arguments are defined in the <syslog.h> header.

RETURN VALUE

The setlogmask() function shall return the previous log priority mask. The closelog(), openlog(), and syslog() functions shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Using openlog()

The following example causes subsequent calls to syslog() to log the process ID with each message, and to write messages to the system console if they cannot be sent to the logging facility.

#include <syslog.h>

char *ident = "Process demo";
int logopt = LOG_PID | LOG_CONS;
int facility = LOG_USER;
...
openlog(ident, logopt, facility);

Using setlogmask()

The following example causes subsequent calls to syslog() to accept error messages, and to reject all other messages.

#include <syslog.h>

int result;
int mask = LOG_MASK (LOG_ERR);
...
result = setlogmask(mask);

Using syslog

The following example sends the message "This is a message" to the default logging facility, marking the message as an error message generated by random processes.

#include <syslog.h>

char *message = "This is a message";
int priority = LOG_ERR | LOG_USER;
...
syslog(priority, message);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

printf() , the Base Definitions volume of IEEE Std 1003.1-2001, <syslog.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fetestexcept(3p)

FETESTEXCEPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fetestexcept - test floating-point exception flags

SYNOPSIS

#include <fenv.h>

int fetestexcept(int excepts);

DESCRIPTION

The fetestexcept() function shall determine which of a specified subset of the floating-point exception flags are currently set. The excepts argument specifies the floating-point status flags to be queried.

RETURN VALUE

The fetestexcept() function shall return the value of the bitwise-inclusive OR of the floating-point exception macros corresponding to the currently set floating-point exceptions included in excepts.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following example calls function f() if an invalid exception is set, and then function g() if an overflow exception is set:

#include <fenv.h>
/* ... */
{
    #pragma STDC FENV_ACCESS ON
    int set_excepts;
    feclearexcept(FE_INVALID | FE_OVERFLOW);
    // maybe raise exceptions
    set_excepts = fetestexcept(FE_INVALID | FE_OVERFLOW);
    if (set_excepts & FE_INVALID) f();
    if (set_excepts & FE_OVERFLOW) g();
    /* ... */
}

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fegetexceptflag() , feraiseexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_start(3p)

POSIX_TRACE_START

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_start, posix_trace_stop - trace start and stop (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_start(trace_id_t trid);
int posix_trace_stop (trace_id_t trid);

DESCRIPTION

The posix_trace_start() and posix_trace_stop() functions, respectively, shall start and stop the trace stream identified by the argument trid.

The effect of calling the posix_trace_start() function shall be recorded in the trace stream as the POSIX_TRACE_START system trace event and the status of the trace stream shall become POSIX_TRACE_RUNNING. If the trace stream is in progress when this function is called, the POSIX_TRACE_START system trace event shall not be recorded and the trace stream shall continue to run. If the trace stream is full, the POSIX_TRACE_START system trace event shall not be recorded and the status of the trace stream shall not be changed.

The effect of calling the posix_trace_stop() function shall be recorded in the trace stream as the POSIX_TRACE_STOP system trace event and the status of the trace stream shall become POSIX_TRACE_SUSPENDED. If the trace stream is suspended when this function is called, the POSIX_TRACE_STOP system trace event shall not be recorded and the trace stream shall remain suspended. If the trace stream is full, the POSIX_TRACE_STOP system trace event shall not be recorded and the status of the trace stream shall not be changed.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

ERRORS

These functions shall fail if:

EINVAL
The value of the argument trid does not correspond to an active trace stream and thus no trace stream was started or stopped.
EINTR
The operation was interrupted by a signal and thus the trace stream was not necessarily started or stopped.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


semget(3p)

SEMGET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

semget - get set of XSI semaphores

SYNOPSIS

#include <sys/sem.h>

int semget(key_t key, int nsems, int semflg);

DESCRIPTION

The semget() function operates on XSI semaphores (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.15, Semaphore). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The semget() function shall return the semaphore identifier associated with key.

A semaphore identifier with its associated semid_ds data structure and its associated set of nsems semaphores (see <sys/sem.h>) is created for key if one of the following is true:

*
The argument key is equal to IPC_PRIVATE.

*
The argument key does not already have a semaphore identifier associated with it and (semflg &IPC_CREAT) is non-zero.

Upon creation, the semid_ds data structure associated with the new semaphore identifier is initialized as follows:

*
In the operation permissions structure sem_perm.cuid, sem_perm.uid, sem_perm.cgid, and sem_perm.gid shall be set equal to the effective user ID and effective group ID, respectively, of the calling process.

*
The low-order 9 bits of sem_perm.mode shall be set equal to the low-order 9 bits of semflg.

*
The variable sem_nsems shall be set equal to the value of nsems.

*
The variable sem_otime shall be set equal to 0 and sem_ctime shall be set equal to the current time.

*
The data structure associated with each semaphore in the set shall not be initialized. The semctl() function with the command SETVAL or SETALL can be used to initialize each semaphore.

RETURN VALUE

Upon successful completion, semget() shall return a non-negative integer, namely a semaphore identifier; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The semget() function shall fail if:

EACCES
A semaphore identifier exists for key, but operation permission as specified by the low-order 9 bits of semflg would not be granted; see XSI Interprocess Communication .
EEXIST
A semaphore identifier exists for the argument key but ((semflg &IPC_CREAT) &&(semflg &IPC_EXCL)) is non-zero.
EINVAL
The value of nsems is either less than or equal to 0 or greater than the system-imposed limit, or a semaphore identifier exists for the argument key, but the number of semaphores in the set associated with it is less than nsems and nsems is not equal to 0.
ENOENT
A semaphore identifier does not exist for the argument key and (semflg &IPC_CREAT) is equal to 0.
ENOSPC
A semaphore identifier is to be created but the system-imposed limit on the maximum number of allowed semaphores system-wide would be exceeded.

The following sections are informative.

EXAMPLES

Creating a Semaphore Identifier

The following example gets a unique semaphore key using the ftok() function, then gets a semaphore ID associated with that key using the semget() function (the first call also tests to make sure the semaphore exists). If the semaphore does not exist, the program creates it, as shown by the second call to semget(). In creating the semaphore for the queuing process, the program attempts to create one semaphore with read/write permission for all. It also uses the IPC_EXCL flag, which forces semget() to fail if the semaphore already exists.

After creating the semaphore, the program uses a call to semop() to initialize it to the values in the sbuf array. The number of processes that can execute concurrently without queuing is initially set to 2. The final call to semget() creates a semaphore identifier that can be used later in the program.

#include <sys/types.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <fcntl.h>
#include <limits.h>
...
key_t semkey;
int semid, pfd, fv;
struct sembuf sbuf;
char *lgn;
char filename[PATH_MAX+1];
struct stat outstat;
struct passwd *pw;
...
/* Get unique key for semaphore. */
if ((semkey = ftok("/tmp", 'a')) == (key_t) -1) {
    perror("IPC error: ftok"); exit(1);
}

/* Get semaphore ID associated with this key. */
if ((semid = semget(semkey, 0, 0)) == -1) {

    /* Semaphore does not exist - Create. */
    if ((semid = semget(semkey, 1, IPC_CREAT | IPC_EXCL | S_IRUSR |
        S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) != -1)
    {
        /* Initialize the semaphore. */
        sbuf.sem_num = 0;
        sbuf.sem_op = 2;  /* This is the number of runs
                             without queuing. */
        sbuf.sem_flg = 0;
        if (semop(semid, &sbuf, 1) == -1) {
            perror("IPC error: semop"); exit(1);
        }
    }
    else if (errno == EEXIST) {
        if ((semid = semget(semkey, 0, 0)) == -1) {
            perror("IPC error 1: semget"); exit(1);
        }
    }
    else {
        perror("IPC error 2: semget"); exit(1);
    }
}
...

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , semctl() , semop() , sem_close() , sem_destroy() , sem_getvalue() , sem_init() , sem_open() , sem_post() , sem_unlink() , sem_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/sem.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstoimax(3p)

WCSTOIMAX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcstoimax, wcstoumax - convert a wide-character string to an integer type

SYNOPSIS

#include <stddef.h>
#include <inttypes.h>

intmax_t wcstoimax(const wchar_t *restrict nptr,
wchar_t **restrict endptr, int base);
uintmax_t wcstoumax(const wchar_t *restrict nptr,
wchar_t **restrict endptr, int base);

DESCRIPTION

These functions shall be equivalent to the wcstol(), wcstoll(), wcstoul(), and wcstoull() functions, respectively, except that the initial portion of the wide string shall be converted to intmax_t and uintmax_t representation, respectively.

RETURN VALUE

These functions shall return the converted value, if any.

If no conversion could be performed, zero shall be returned. If the correct value is outside the range of representable values, {INTMAX_MAX}, {INTMAX_MIN}, or {UINTMAX_MAX} shall be returned (according to the return type and sign of the value, if any), and errno shall be set to [ERANGE].

ERRORS

These functions shall fail if:

EINVAL
The value of base is not supported.
ERANGE
The value to be returned is not representable.

These functions may fail if:

EINVAL
No conversion could be performed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcstol() , wcstoul() , the Base Definitions volume of IEEE Std 1003.1-2001, <inttypes.h>, <stddef.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fesetenv (3p)

 Continue to this page.


getservent(3p)

ENDSERVENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

endservent, getservbyname, getservbyport, getservent, setservent - network services database functions

SYNOPSIS

#include <netdb.h>

void endservent(void);
struct servent *getservbyname(const char *name, const
char *proto);
struct servent *getservbyport(int port, const char *proto);
struct servent *getservent(void);
void setservent(int stayopen);

DESCRIPTION

These functions shall retrieve information about network services. This information is considered to be stored in a database that can be accessed sequentially or randomly. The implementation of this database is unspecified.

The setservent() function shall open a connection to the database, and set the next entry to the first entry. If the stayopen argument is non-zero, the net database shall not be closed after each call to the getservent() function (either directly, or indirectly through one of the other getserv*() functions), and the implementation may maintain an open file descriptor for the database.

The getservent() function shall read the next entry of the database, opening and closing a connection to the database as necessary.

The getservbyname() function shall search the database from the beginning and find the first entry for which the service name specified by name matches the s_name member and the protocol name specified by proto matches the s_proto member, opening and closing a connection to the database as necessary. If proto is a null pointer, any value of the s_proto member shall be matched.

The getservbyport() function shall search the database from the beginning and find the first entry for which the port specified by port matches the s_port member and the protocol name specified by proto matches the s_proto member, opening and closing a connection to the database as necessary. If proto is a null pointer, any value of the s_proto member shall be matched. The port argument shall be in network byte order.

The getservbyname(), getservbyport(), and getservent() functions shall each return a pointer to a servent structure, the members of which shall contain the fields of an entry in the network services database.

The endservent() function shall close the database, releasing any open file descriptor.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, getservbyname(), getservbyport(), and getservent() return a pointer to a servent structure if the requested entry was found, and a null pointer if the end of the database was reached or the requested entry was not found. Otherwise, a null pointer is returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The port argument of getservbyport() need not be compatible with the port values of all address families.

The getservbyname(), getservbyport(), and getservent() functions may return pointers to static data, which may be overwritten by subsequent calls to any of these functions.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

endhostent() , endprotoent() , htonl() , inet_addr() , the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


assert(3p)

ASSERT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

assert - insert program diagnostics

SYNOPSIS

#include <assert.h>

void assert(scalar expression);

DESCRIPTION

The assert() macro shall insert diagnostics into programs; it shall expand to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), assert() shall write information about the particular call that failed on stderr and shall call abort().

The information written about the call that failed shall include the text of the argument, the name of the source file, the source file line number, and the name of the enclosing function; the latter are, respectively, the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__.

Forcing a definition of the name NDEBUG, either from the compiler command line or with the preprocessor control statement #define NDEBUG ahead of the #include <assert.h> statement, shall stop assertions from being compiled into the program.

RETURN VALUE

The assert() macro shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

abort() , stderr, the Base Definitions volume of IEEE Std 1003.1-2001, <assert.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cacos(3p)

CACOS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cacos, cacosf, cacosl - complex arc cosine functions

SYNOPSIS

#include <complex.h>

double complex cacos(double complex z);
float complex cacosf(float complex z);
long double complex cacosl(long double complex z);

DESCRIPTION

These functions shall compute the complex arc cosine of z, with branch cuts outside the interval [-1, +1] along the real axis.

RETURN VALUE

These functions shall return the complex arc cosine value, in the range of a strip mathematically unbounded along the imaginary axis and in the interval [0, pi] along the real axis.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ccos() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


towctrans(3p)

TOWCTRANS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

towctrans - wide-character transliteration

SYNOPSIS

#include <wctype.h>

wint_t towctrans(wint_t wc, wctrans_t desc);

DESCRIPTION

The towctrans() function shall transliterate the wide-character code wc using the mapping described by desc. The current setting of the LC_CTYPE category should be the same as during the call to wctrans() that returned the value desc. If the value of desc is invalid (that is, not obtained by a call to wctrans() or desc is invalidated by a subsequent call to setlocale() that has affected category LC_CTYPE ), the result is unspecified.

An application wishing to check for error situations should set errno to 0 before calling towctrans(). If errno is non-zero on return, an error has occurred.

RETURN VALUE

If successful, the towctrans() function shall return the mapped value of wc using the mapping described by desc. Otherwise, it shall return wc unchanged.

ERRORS

The towctrans() function may fail if:

EINVAL
desc contains an invalid transliteration descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The strings "tolower" and "toupper" are reserved for the standard mapping names. In the table below, the functions in the left column are equivalent to the functions in the right column.

towlower(wc)    towctrans(wc, wctrans("tolower"))
towupper(wc)    towctrans(wc, wctrans("toupper"))

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

towlower() , towupper() , wctrans() , the Base Definitions volume of IEEE Std 1003.1-2001, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lroundf (3p)

 Continue to this page.


pthread_attr_setschedpolicy (3p)

 Continue to this page.


setenv(3p)

SETENV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setenv - add or change environment variable

SYNOPSIS

#include <stdlib.h>

int setenv(const char *envname, const char *envval, int overwrite);

DESCRIPTION

The setenv() function shall update or add a variable in the environment of the calling process. The envname argument points to a string containing the name of an environment variable to be added or altered. The environment variable shall be set to the value to which envval points. The function shall fail if envname points to a string which contains an '=' character. If the environment variable named by envname already exists and the value of overwrite is non-zero, the function shall return success and the environment shall be updated. If the environment variable named by envname already exists and the value of overwrite is zero, the function shall return success and the environment shall remain unchanged.

If the application modifies environ or the pointers to which it points, the behavior of setenv() is undefined. The setenv() function shall update the list of pointers to which environ points.

The strings described by envname and envval are copied by this function.

The setenv() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, zero shall be returned. Otherwise, -1 shall be returned, errno set to indicate the error, and the environment shall be unchanged.

ERRORS

The setenv() function shall fail if:

EINVAL
The name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
ENOMEM
Insufficient memory was available to add a variable or its value to the environment.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

See exec() , for restrictions on changing the environment in multi-threaded applications.

RATIONALE

Unanticipated results may occur if setenv() changes the external variable environ. In particular, if the optional envp argument to main() is present, it is not changed, and thus may point to an obsolete copy of the environment (as may any other copy of environ). However, other than the aforementioned restriction, the developers of IEEE Std 1003.1-2001 intended that the traditional method of walking through the environment by way of the environ pointer must be supported.

It was decided that setenv() should be required by this revision because it addresses a piece of missing functionality, and does not impose a significant burden on the implementor.

There was considerable debate as to whether the System V putenv() function or the BSD setenv() function should be required as a mandatory function. The setenv() function was chosen because it permitted the implementation of the unsetenv() function to delete environmental variables, without specifying an additional interface. The putenv() function is available as an XSI extension.

The standard developers considered requiring that setenv() indicate an error when a call to it would result in exceeding {ARG_MAX}. The requirement was rejected since the condition might be temporary, with the application eventually reducing the environment size. The ultimate success or failure depends on the size at the time of a call to exec, which returns an indication of this error condition.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getenv() , unsetenv() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fsetpos(3p)

FSETPOS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fsetpos - set current file position

SYNOPSIS

#include <stdio.h>

int fsetpos(FILE *stream, const fpos_t *pos);

DESCRIPTION

The fsetpos() function shall set the file position and state indicators for the stream pointed to by stream according to the value of the object pointed to by pos, which the application shall ensure is a value obtained from an earlier call to fgetpos() on the same stream. If a read or write error occurs, the error indicator for the stream shall be set and fsetpos() fails.

A successful call to the fsetpos() function shall clear the end-of-file indicator for the stream and undo any effects of ungetc() on the same stream. After an fsetpos() call, the next operation on an update stream may be either input or output.

The behavior of fsetpos() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined.

RETURN VALUE

The fsetpos() function shall return 0 if it succeeds; otherwise, it shall return a non-zero value and set errno to indicate the error.

ERRORS

The fsetpos() function shall fail if, either the stream is unbuffered or the stream's buffer needed to be flushed, and the call to fsetpos() causes an underlying lseek() or write() to be invoked, and:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor and the process would be delayed in the write operation.
EBADF
The file descriptor underlying the stream file is not open for writing or the stream's buffer needed to be flushed and the file is not open.
EFBIG
An attempt was made to write a file that exceeds the maximum file size.
EFBIG
An attempt was made to write a file that exceeds the process' file size limit.
EFBIG
The file is a regular file and an attempt was made to write at or beyond the offset maximum associated with the corresponding stream.
EINTR
The write operation was terminated due to the receipt of a signal, and no data was transferred.
EIO
A physical I/O error has occurred, or the process is a member of a background process group attempting to perform a write() to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the process group of the process is orphaned. This error may also be returned under implementation-defined conditions.
ENOSPC
There was no free space remaining on the device containing the file.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.
EPIPE
The file descriptor underlying stream is associated with a pipe or FIFO.
EPIPE
An attempt was made to write to a pipe or FIFO that is not open for reading by any process; a SIGPIPE signal shall also be sent to the thread.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , ftell() , lseek() , rewind() , ungetc() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lroundl (3p)

 Continue to this page.


pthread_testcancel(3p)

PTHREAD_SETCANCELSTATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_setcancelstate, pthread_setcanceltype, pthread_testcancel - set cancelability state

SYNOPSIS

#include <pthread.h>

int pthread_setcancelstate(int state, int *oldstate);
int pthread_setcanceltype(int type, int *oldtype);
void pthread_testcancel(void);

DESCRIPTION

The pthread_setcancelstate() function shall atomically both set the calling thread's cancelability state to the indicated state and return the previous cancelability state at the location referenced by oldstate. Legal values for state are PTHREAD_CANCEL_ENABLE and PTHREAD_CANCEL_DISABLE.

The pthread_setcanceltype() function shall atomically both set the calling thread's cancelability type to the indicated type and return the previous cancelability type at the location referenced by oldtype. Legal values for type are PTHREAD_CANCEL_DEFERRED and PTHREAD_CANCEL_ASYNCHRONOUS.

The cancelability state and type of any newly created threads, including the thread in which main() was first invoked, shall be PTHREAD_CANCEL_ENABLE and PTHREAD_CANCEL_DEFERRED respectively.

The pthread_testcancel() function shall create a cancellation point in the calling thread. The pthread_testcancel() function shall have no effect if cancelability is disabled.

RETURN VALUE

If successful, the pthread_setcancelstate() and pthread_setcanceltype() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_setcancelstate() function may fail if:

EINVAL
The specified state is not PTHREAD_CANCEL_ENABLE or PTHREAD_CANCEL_DISABLE.

The pthread_setcanceltype() function may fail if:

EINVAL
The specified type is not PTHREAD_CANCEL_DEFERRED or PTHREAD_CANCEL_ASYNCHRONOUS.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The pthread_setcancelstate() and pthread_setcanceltype() functions control the points at which a thread may be asynchronously canceled. For cancellation control to be usable in modular fashion, some rules need to be followed.

An object can be considered to be a generalization of a procedure. It is a set of procedures and global variables written as a unit and called by clients not known by the object. Objects may depend on other objects.

First, cancelability should only be disabled on entry to an object, never explicitly enabled. On exit from an object, the cancelability state should always be restored to its value on entry to the object.

This follows from a modularity argument: if the client of an object (or the client of an object that uses that object) has disabled cancelability, it is because the client does not want to be concerned about cleaning up if the thread is canceled while executing some sequence of actions. If an object is called in such a state and it enables cancelability and a cancellation request is pending for that thread, then the thread is canceled, contrary to the wish of the client that disabled.

Second, the cancelability type may be explicitly set to either deferred or asynchronous upon entry to an object. But as with the cancelability state, on exit from an object the cancelability type should always be restored to its value on entry to the object.

Finally, only functions that are cancel-safe may be called from a thread that is asynchronously cancelable.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cancel() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_setcanceltype (3p)

 Continue to this page.


modff (3p)

 Continue to this page.


modfl (3p)

 Continue to this page.


setitimer (3p)

 Continue to this page.


pthread_spin_init(3p)

PTHREAD_SPIN_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_spin_destroy, pthread_spin_init - destroy or initialize a spin lock object (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_spin_destroy(pthread_spinlock_t *lock);
int pthread_spin_init(pthread_spinlock_t *lock, int pshared);

DESCRIPTION

The pthread_spin_destroy() function shall destroy the spin lock referenced by lock and release any resources used by the lock. The effect of subsequent use of the lock is undefined until the lock is reinitialized by another call to pthread_spin_init(). The results are undefined if pthread_spin_destroy() is called when a thread holds the lock, or if this function is called with an uninitialized thread spin lock.

The pthread_spin_init() function shall allocate any resources required to use the spin lock referenced by lock and initialize the lock to an unlocked state.

If the Thread Process-Shared Synchronization option is supported and the value of pshared is PTHREAD_PROCESS_SHARED, the implementation shall permit the spin lock to be operated upon by any thread that has access to the memory where the spin lock is allocated, even if it is allocated in memory that is shared by multiple processes.

If the Thread Process-Shared Synchronization option is supported and the value of pshared is PTHREAD_PROCESS_PRIVATE, or if the option is not supported, the spin lock shall only be operated upon by threads created within the same process as the thread that initialized the spin lock. If threads of differing processes attempt to operate on such a spin lock, the behavior is undefined.

The results are undefined if pthread_spin_init() is called specifying an already initialized spin lock. The results are undefined if a spin lock is used without first being initialized.

If the pthread_spin_init() function fails, the lock is not initialized and the contents of lock are undefined.

Only the object referenced by lock may be used for performing synchronization.

The result of referring to copies of that object in calls to pthread_spin_destroy(), pthread_spin_lock(), pthread_spin_trylock(), or pthread_spin_unlock() is undefined.

RETURN VALUE

Upon successful completion, these functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EBUSY
The implementation has detected an attempt to initialize or destroy a spin lock while it is in use (for example, while being used in a pthread_spin_lock() call) by another thread.
EINVAL
The value specified by lock is invalid.

The pthread_spin_init() function shall fail if:

EAGAIN
The system lacks the necessary resources to initialize another spin lock.
ENOMEM
Insufficient memory exists to initialize the lock.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_spin_destroy() and pthread_spin_init() functions are part of the Spin Locks option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_spin_lock() , pthread_spin_unlock() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setegid(3p)

SETEGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setegid - set the effective group ID

SYNOPSIS

#include <unistd.h>

int setegid(gid_t gid);

DESCRIPTION

If gid is equal to the real group ID or the saved set-group-ID, or if the process has appropriate privileges, setegid() shall set the effective group ID of the calling process to gid; the real group ID, saved set-group-ID, and any supplementary group IDs shall remain unchanged.

The setegid() function shall not affect the supplementary group list in any way.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The setegid() function shall fail if:

EINVAL
The value of the gid argument is invalid and is not supported by the implementation.
EPERM
The process does not have appropriate privileges and gid does not match the real group ID or the saved set-group-ID.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to the RATIONALE section in setuid() .

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getegid() , geteuid() , getgid() , getuid() , seteuid() , setgid() , setregid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tcgetattr(3p)

TCGETATTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcgetattr - get the parameters associated with the terminal

SYNOPSIS

#include <termios.h>

int tcgetattr(int fildes, struct termios *termios_p);

DESCRIPTION

The tcgetattr() function shall get the parameters associated with the terminal referred to by fildes and store them in the termios structure referenced by termios_p. The fildes argument is an open file descriptor associated with a terminal.

The termios_p argument is a pointer to a termios structure.

The tcgetattr() operation is allowed from any process.

If the terminal device supports different input and output baud rates, the baud rates stored in the termios structure returned by tcgetattr() shall reflect the actual baud rates, even if they are equal. If differing baud rates are not supported, the rate returned as the output baud rate shall be the actual baud rate. If the terminal device does not support split baud rates, the input baud rate stored in the termios structure shall be the output rate (as one of the symbolic values).

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcgetattr() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
ENOTTY
The file associated with fildes is not a terminal.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Care must be taken when changing the terminal attributes. Applications should always do a tcgetattr(), save the termios structure values returned, and then do a tcsetattr(), changing only the necessary fields. The application should use the values saved from the tcgetattr() to reset the terminal state whenever it is done with the terminal. This is necessary because terminal attributes apply to the underlying port and not to each individual open instance; that is, all processes that have used the terminal see the latest attribute changes.

A program that uses these functions should be written to catch all signals and take other appropriate actions to ensure that when the program terminates, whether planned or not, the terminal device's state is restored to its original state.

Existing practice dealing with error returns when only part of a request can be honored is based on calls to the ioctl() function. In historical BSD and System V implementations, the corresponding ioctl() returns zero if the requested actions were semantically correct, even if some of the requested changes could not be made. Many existing applications assume this behavior and would no longer work correctly if the return value were changed from zero to -1 in this case.

Note that either specification has a problem. When zero is returned, it implies everything succeeded even if some of the changes were not made. When -1 is returned, it implies everything failed even though some of the changes were made.

Applications that need all of the requested changes made to work properly should follow tcsetattr() with a call to tcgetattr() and compare the appropriate field values.

FUTURE DIRECTIONS

None.

SEE ALSO

tcsetattr() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_stop (3p)

 Continue to this page.


putwc(3p)

PUTWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

putwc - put a wide character on a stream

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

wint_t putwc(wchar_t wc, FILE *stream);

DESCRIPTION

The putwc() function shall be equivalent to fputwc(), except that if it is implemented as a macro it may evaluate stream more than once, so the argument should never be an expression with side effects.

RETURN VALUE

Refer to fputwc() .

ERRORS

Refer to fputwc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Since it may be implemented as a macro, putwc() may treat a stream argument with side effects incorrectly. In particular, putwc(wc,*f++) need not work correctly. Therefore, use of this function is not recommended; fputwc() should be used instead.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fputwc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


accept(3p)

ACCEPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

accept - accept a new connection on a socket

SYNOPSIS

#include <sys/socket.h>

int accept(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);

DESCRIPTION

The accept() function shall extract the first connection on the queue of pending connections, create a new socket with the same socket type protocol and address family as the specified socket, and allocate a new file descriptor for that socket.

The accept() function takes the following arguments:

socket
Specifies a socket that was created with socket(), has been bound to an address with bind(), and has issued a successful call to listen().
address
Either a null pointer, or a pointer to a sockaddr structure where the address of the connecting socket shall be returned.
address_len
Points to a socklen_t structure which on input specifies the length of the supplied sockaddr structure, and on output specifies the length of the stored address.

If address is not a null pointer, the address of the peer for the accepted connection shall be stored in the sockaddr structure pointed to by address, and the length of this address shall be stored in the object pointed to by address_len.

If the actual length of the address is greater than the length of the supplied sockaddr structure, the stored address shall be truncated.

If the protocol permits connections by unbound clients, and the peer is not bound, then the value stored in the object pointed to by address is unspecified.

If the listen queue is empty of connection requests and O_NONBLOCK is not set on the file descriptor for the socket, accept() shall block until a connection is present. If the listen() queue is empty of connection requests and O_NONBLOCK is set on the file descriptor for the socket, accept() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].

The accepted socket cannot itself accept more connections. The original socket remains open and can accept more connections.

RETURN VALUE

Upon successful completion, accept() shall return the non-negative file descriptor of the accepted socket. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The accept() function shall fail if:

EAGAIN or EWOULDBLOCK

O_NONBLOCK is set for the socket file descriptor and no connections are present to be accepted.

EBADF
The socket argument is not a valid file descriptor.
ECONNABORTED

A connection has been aborted.

EINTR
The accept() function was interrupted by a signal that was caught before a valid connection arrived.
EINVAL
The socket is not accepting connections.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum number of file descriptors in the system are already open.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The socket type of the specified socket does not support accepting connections.

The accept() function may fail if:

ENOBUFS
No buffer space is available.
ENOMEM
There was insufficient memory available to complete the operation.
EPROTO
A protocol error has occurred; for example, the STREAMS protocol stack has not been initialized.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

When a connection is available, select() indicates that the file descriptor for the socket is ready for reading.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

bind() , connect() , listen() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lseek(3p)

LSEEK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lseek - move the read/write file offset

SYNOPSIS

#include <unistd.h>

off_t lseek(int fildes, off_t offset, int whence);

DESCRIPTION

The lseek() function shall set the file offset for the open file description associated with the file descriptor fildes, as follows:

*
If whence is SEEK_SET, the file offset shall be set to offset bytes.

*
If whence is SEEK_CUR, the file offset shall be set to its current location plus offset.

*
If whence is SEEK_END, the file offset shall be set to the size of the file plus offset.

The symbolic constants SEEK_SET, SEEK_CUR, and SEEK_END are defined in <unistd.h>.

The behavior of lseek() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined.

The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

The lseek() function shall not, by itself, extend the size of a file.

If fildes refers to a shared memory object, the result of the lseek() function is unspecified.

If fildes refers to a typed memory object, the result of the lseek() function is unspecified.

RETURN VALUE

Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned. Otherwise, (off_t)-1 shall be returned, errno shall be set to indicate the error, and the file offset shall remain unchanged.

ERRORS

The lseek() function shall fail if:

EBADF
The fildes argument is not an open file descriptor.
EINVAL
The whence argument is not a proper value, or the resulting file offset would be negative for a regular file, block special file, or directory.
EOVERFLOW
The resulting file offset would be a value which cannot be represented correctly in an object of type off_t.
ESPIPE
The fildes argument is associated with a pipe, FIFO, or socket.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The ISO C standard includes the functions fgetpos() and fsetpos(), which work on very large files by use of a special positioning type.

Although lseek() may position the file offset beyond the end of the file, this function does not itself extend the size of the file. While the only function in IEEE Std 1003.1-2001 that may directly extend the size of the file is write(), truncate(), and ftruncate(), several functions originally derived from the ISO C standard, such as fwrite(), fprintf(), and so on, may do so (by causing calls on write()).

An invalid file offset that would cause [EINVAL] to be returned may be both implementation-defined and device-dependent (for example, memory may have few invalid values). A negative file offset may be valid for some devices in some implementations.

The POSIX.1-1990 standard did not specifically prohibit lseek() from returning a negative offset. Therefore, an application was required to clear errno prior to the call and check errno upon return to determine whether a return value of ( off_t)-1 is a negative offset or an indication of an error condition. The standard developers did not wish to require this action on the part of a conforming application, and chose to require that errno be set to [EINVAL] when the resulting file offset would be negative for a regular file, block special file, or directory.

FUTURE DIRECTIONS

None.

SEE ALSO

open() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atan2f (3p)

 Continue to this page.


sem_unlink(3p)

SEM_UNLINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_unlink - remove a named semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

int sem_unlink(const char *name);

DESCRIPTION

The sem_unlink() function shall remove the semaphore named by the string name. If the semaphore named by name is currently referenced by other processes, then sem_unlink() shall have no effect on the state of the semaphore. If one or more processes have the semaphore open when sem_unlink() is called, destruction of the semaphore is postponed until all references to the semaphore have been destroyed by calls to sem_close(), _exit(), or exec. Calls to sem_open() to recreate or reconnect to the semaphore refer to a new semaphore after sem_unlink() is called. The sem_unlink() call shall not block until all references have been destroyed; it shall return immediately.

RETURN VALUE

Upon successful completion, the sem_unlink() function shall return a value of 0. Otherwise, the semaphore shall not be changed and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sem_unlink() function shall fail if:

EACCES
Permission is denied to unlink the named semaphore.
ENAMETOOLONG
The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
The named semaphore does not exist.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sem_unlink() function is part of the Semaphores option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

semctl() , semget() , semop() , sem_close() , sem_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setutxent (3p)

 Continue to this page.


atan2l (3p)

 Continue to this page.


access(3p)

ACCESS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

access - determine accessibility of a file

SYNOPSIS

#include <unistd.h>

int access(const char *path, int amode);

DESCRIPTION

The access() function shall check the file named by the pathname pointed to by the path argument for accessibility according to the bit pattern contained in amode, using the real user ID in place of the effective user ID and the real group ID in place of the effective group ID.

The value of amode is either the bitwise-inclusive OR of the access permissions to be checked (R_OK, W_OK, X_OK) or the existence test (F_OK).

If any access permissions are checked, each shall be checked individually, as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 3, Definitions. If the process has appropriate privileges, an implementation may indicate success for X_OK even if none of the execute file permission bits are set.

RETURN VALUE

If the requested access is permitted, access() succeeds and shall return 0; otherwise, -1 shall be returned and errno shall be set to indicate the error.

ERRORS

The access() function shall fail if:

EACCES
Permission bits of the file mode do not permit the requested access, or search permission is denied on a component of the path prefix.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
EROFS
Write access is requested for a file on a read-only file system.

The access() function may fail if:

EINVAL
The value of the amode argument is invalid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ETXTBSY
Write access is requested for a pure procedure (shared text) file that is being executed.

The following sections are informative.

EXAMPLES

Testing for the Existence of a File

The following example tests whether a file named myfile exists in the /tmp directory.

#include <unistd.h>
...
int result;
const char *filename = "/tmp/myfile";

result = access (filename, F_OK);

APPLICATION USAGE

Additional values of amode other than the set defined in the description may be valid; for example, if a system has extended access controls.

RATIONALE

In early proposals, some inadequacies in the access() function led to the creation of an eaccess() function because:

1.
Historical implementations of access() do not test file access correctly when the process' real user ID is superuser. In particular, they always return zero when testing execute permissions without regard to whether the file is executable.

2.
The superuser has complete access to all files on a system. As a consequence, programs started by the superuser and switched to the effective user ID with lesser privileges cannot use access() to test their file access permissions.

However, the historical model of eaccess() does not resolve problem (1), so this volume of IEEE Std 1003.1-2001 now allows access() to behave in the desired way because several implementations have corrected the problem. It was also argued that problem (2) is more easily solved by using open(), chdir(), or one of the exec functions as appropriate and responding to the error, rather than creating a new function that would not be as reliable. Therefore, eaccess() is not included in this volume of IEEE Std 1003.1-2001.

The sentence concerning appropriate privileges and execute permission bits reflects the two possibilities implemented by historical implementations when checking superuser access for X_OK.

New implementations are discouraged from returning X_OK unless at least one execution permission bit is set.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , stat() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getdate_err (3p)

 Continue to this page.


pthread_mutexattr_init(3p)

PTHREAD_MUTEXATTR_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutexattr_destroy, pthread_mutexattr_init - destroy and initialize the mutex attributes object

SYNOPSIS

#include <pthread.h>

int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
int pthread_mutexattr_init(pthread_mutexattr_t *attr);

DESCRIPTION

The pthread_mutexattr_destroy() function shall destroy a mutex attributes object; the object becomes, in effect, uninitialized. An implementation may cause pthread_mutexattr_destroy() to set the object referenced by attr to an invalid value. A destroyed attr attributes object can be reinitialized using pthread_mutexattr_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

The pthread_mutexattr_init() function shall initialize a mutex attributes object attr with the default value for all of the attributes defined by the implementation.

Results are undefined if pthread_mutexattr_init() is called specifying an already initialized attr attributes object.

After a mutex attributes object has been used to initialize one or more mutexes, any function affecting the attributes object (including destruction) shall not affect any previously initialized mutexes.

RETURN VALUE

Upon successful completion, pthread_mutexattr_destroy() and pthread_mutexattr_init() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_mutexattr_destroy() function may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_mutexattr_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the mutex attributes object.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

See pthread_attr_init() for a general explanation of attributes. Attributes objects allow implementations to experiment with useful extensions and permit extension of this volume of IEEE Std 1003.1-2001 without changing the existing functions. Thus, they provide for future extensibility of this volume of IEEE Std 1003.1-2001 and reduce the temptation to standardize prematurely on semantics that are not yet widely implemented or understood.

Examples of possible additional mutex attributes that have been discussed are spin_only, limited_spin, no_spin, recursive, and metered. (To explain what the latter attributes might mean: recursive mutexes would allow for multiple re-locking by the current owner; metered mutexes would transparently keep records of queue length, wait time, and so on.) Since there is not yet wide agreement on the usefulness of these resulting from shared implementation and usage experience, they are not yet specified in this volume of IEEE Std 1003.1-2001. Mutex attributes objects, however, make it possible to test out these concepts for possible standardization at a later time.

Mutex Attributes and Performance

Care has been taken to ensure that the default values of the mutex attributes have been defined such that mutexes initialized with the defaults have simple enough semantics so that the locking and unlocking can be done with the equivalent of a test-and-set instruction (plus possibly a few other basic instructions).

There is at least one implementation method that can be used to reduce the cost of testing at lock-time if a mutex has non-default attributes. One such method that an implementation can employ (and this can be made fully transparent to fully conforming POSIX applications) is to secretly pre-lock any mutexes that are initialized to non-default attributes. Any later attempt to lock such a mutex causes the implementation to branch to the "slow path" as if the mutex were unavailable; then, on the slow path, the implementation can do the "real work" to lock a non-default mutex. The underlying unlock operation is more complicated since the implementation never really wants to release the pre-lock on this kind of mutex. This illustrates that, depending on the hardware, there may be certain optimizations that can be used so that whatever mutex attributes are considered "most frequently used" can be processed most efficiently.

Process Shared Memory and Synchronization

The existence of memory mapping functions in this volume of IEEE Std 1003.1-2001 leads to the possibility that an application may allocate the synchronization objects from this section in memory that is accessed by multiple processes (and therefore, by threads of multiple processes).

In order to permit such usage, while at the same time keeping the usual case (that is, usage within a single process) efficient, a process-shared option has been defined.

If an implementation supports the _POSIX_THREAD_PROCESS_SHARED option, then the process-shared attribute can be used to indicate that mutexes or condition variables may be accessed by threads of multiple processes.

The default setting of PTHREAD_PROCESS_PRIVATE has been chosen for the process-shared attribute so that the most efficient forms of these synchronization objects are created by default.

Synchronization variables that are initialized with the PTHREAD_PROCESS_PRIVATE process-shared attribute may only be operated on by threads in the process that initialized them. Synchronization variables that are initialized with the PTHREAD_PROCESS_SHARED process-shared attribute may be operated on by any thread in any process that has access to it. In particular, these processes may exist beyond the lifetime of the initializing process. For example, the following code implements a simple counting semaphore in a mapped file that may be used by many processes.

/* sem.h */
struct semaphore {
    pthread_mutex_t lock;
    pthread_cond_t nonzero;
    unsigned count;
};
typedef struct semaphore semaphore_t;

semaphore_t *semaphore_create(char *semaphore_name);
semaphore_t *semaphore_open(char *semaphore_name);
void semaphore_post(semaphore_t *semap);
void semaphore_wait(semaphore_t *semap);
void semaphore_close(semaphore_t *semap);

/* sem.c */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include "sem.h"

semaphore_t *
semaphore_create(char *semaphore_name)
{
int fd;
    semaphore_t *semap;
    pthread_mutexattr_t psharedm;
    pthread_condattr_t psharedc;

    fd = open(semaphore_name, O_RDWR | O_CREAT | O_EXCL, 0666);
    if (fd < 0)
        return (NULL);
    (void) ftruncate(fd, sizeof(semaphore_t));
    (void) pthread_mutexattr_init(&psharedm);
    (void) pthread_mutexattr_setpshared(&psharedm,
        PTHREAD_PROCESS_SHARED);
    (void) pthread_condattr_init(&psharedc);
    (void) pthread_condattr_setpshared(&psharedc,
        PTHREAD_PROCESS_SHARED);
    semap = (semaphore_t *) mmap(NULL, sizeof(semaphore_t),
            PROT_READ | PROT_WRITE, MAP_SHARED,
            fd, 0);
    close (fd);
    (void) pthread_mutex_init(&semap->lock, &psharedm);
    (void) pthread_cond_init(&semap->nonzero, &psharedc);
    semap->count = 0;
    return (semap);
}

semaphore_t *
semaphore_open(char *semaphore_name)
{
    int fd;
    semaphore_t *semap;

    fd = open(semaphore_name, O_RDWR, 0666);
    if (fd < 0)
        return (NULL);
    semap = (semaphore_t *) mmap(NULL, sizeof(semaphore_t),
            PROT_READ | PROT_WRITE, MAP_SHARED,
            fd, 0);
    close (fd);
    return (semap);
}

void
semaphore_post(semaphore_t *semap)
{
    pthread_mutex_lock(&semap->lock);
    if (semap->count == 0)
        pthread_cond_signal(&semapx->nonzero);
    semap->count++;
    pthread_mutex_unlock(&semap->lock);
}

void
semaphore_wait(semaphore_t *semap)
{
    pthread_mutex_lock(&semap->lock);
    while (semap->count == 0)
        pthread_cond_wait(&semap->nonzero, &semap->lock);
    semap->count--;
    pthread_mutex_unlock(&semap->lock);
}

void
semaphore_close(semaphore_t *semap)
{
    munmap((void *) semap, sizeof(semaphore_t));
}

The following code is for three separate processes that create, post, and wait on a semaphore in the file /tmp/semaphore. Once the file is created, the post and wait programs increment and decrement the counting semaphore (waiting and waking as required) even though they did not initialize the semaphore.

/* create.c */
#include "pthread.h"
#include "sem.h"

int
main()
{
    semaphore_t *semap;

    semap = semaphore_create("/tmp/semaphore");
    if (semap == NULL)
        exit(1);
    semaphore_close(semap);
    return (0);
}

/* post */
#include "pthread.h"
#include "sem.h"

int
main()
{
    semaphore_t *semap;

    semap = semaphore_open("/tmp/semaphore");
    if (semap == NULL)
        exit(1);
    semaphore_post(semap);
    semaphore_close(semap);
    return (0);
}

/* wait */
#include "pthread.h"
#include "sem.h"

int
main()
{
    semaphore_t *semap;

    semap = semaphore_open("/tmp/semaphore");
    if (semap == NULL)
        exit(1);
    semaphore_wait(semap);
    semaphore_close(semap);
    return (0);
}

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_destroy() , pthread_create() , pthread_mutex_destroy() , pthread_mutexattr_destroy , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcslen(3p)

WCSLEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcslen - get wide-character string length

SYNOPSIS

#include <wchar.h>

size_t wcslen(const wchar_t *ws);

DESCRIPTION

The wcslen() function shall compute the number of wide-character codes in the wide-character string to which ws points, not including the terminating null wide-character code.

RETURN VALUE

The wcslen() function shall return the length of ws; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_memalign(3p)

POSIX_MEMALIGN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_memalign - aligned memory allocation (ADVANCED REALTIME)

SYNOPSIS

#include <stdlib.h>

int posix_memalign(void **memptr, size_t alignment, size_t size);

DESCRIPTION

The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment, and shall return a pointer to the allocated memory in memptr. The value of alignment shall be a multiple of sizeof( void *), that is also a power of two. Upon successful completion, the value pointed to by memptr shall be a multiple of alignment.

The free() function shall deallocate memory that has previously been allocated by posix_memalign().

RETURN VALUE

Upon successful completion, posix_memalign() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The posix_memalign() function shall fail if:

EINVAL
The value of the alignment parameter is not a power of two multiple of sizeof( void *).
ENOMEM
There is insufficient memory available with the requested alignment.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The posix_memalign() function is part of the Advisory Information option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

free() , malloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


csqrtf (3p)

 Continue to this page.


csqrtl (3p)

 Continue to this page.


tcgetpgrp(3p)

TCGETPGRP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcgetpgrp - get the foreground process group ID

SYNOPSIS

#include <unistd.h>

pid_t tcgetpgrp(int fildes);

DESCRIPTION

The tcgetpgrp() function shall return the value of the process group ID of the foreground process group associated with the terminal.

If there is no foreground process group, tcgetpgrp() shall return a value greater than 1 that does not match the process group ID of any existing process group.

The tcgetpgrp() function is allowed from a process that is a member of a background process group; however, the information may be subsequently changed by a process that is a member of a foreground process group.

RETURN VALUE

Upon successful completion, tcgetpgrp() shall return the value of the process group ID of the foreground process associated with the terminal. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcgetpgrp() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
ENOTTY
The calling process does not have a controlling terminal, or the file is not the controlling terminal.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

setsid() , setpgid() , tcsetpgrp() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fdim(3p)

FDIM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fdim, fdimf, fdiml - compute positive difference between two floating-point numbers

SYNOPSIS

#include <math.h>

double fdim(double x, double y);
float fdimf(float x, float y);
long double fdiml(long double x, long double y);

DESCRIPTION

These functions shall determine the positive difference between their arguments. If x is greater than y, x- y is returned. If x is less than or equal to y, +0 is returned.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the positive difference value.

If x- y is positive and overflows, a range error shall occur and fdim(), fdimf(), and fdiml() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.

If x- y is positive and underflows, a range error may occur, and either ( x- y) (if representable), or 0.0 (if supported), or an implementation-defined value shall be returned.

If x or y is NaN, a NaN shall be returned.

ERRORS

The fdim() function shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The fdim() function may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On implementations supporting IEEE Std 754-1985, x- y cannot underflow, and hence the 0.0 return value is shaded as an extension for implementations supporting the XSI extension rather than an MX extension.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , fmax() , fmin() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setgid(3p)

SETGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setgid - set-group-ID

SYNOPSIS

#include <unistd.h>

int setgid(gid_t gid);

DESCRIPTION

If the process has appropriate privileges, setgid() shall set the real group ID, effective group ID, and the saved set-group-ID of the calling process to gid.

If the process does not have appropriate privileges, but gid is equal to the real group ID or the saved set-group-ID, setgid() shall set the effective group ID to gid; the real group ID and saved set-group-ID shall remain unchanged.

The setgid() function shall not affect the supplementary group list in any way.

Any supplementary group IDs of the calling process shall remain unchanged.

RETURN VALUE

Upon successful completion, 0 is returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The setgid() function shall fail if:

EINVAL
The value of the gid argument is invalid and is not supported by the implementation.
EPERM
The process does not have appropriate privileges and gid does not match the real group ID or the saved set-group-ID.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to the RATIONALE section in setuid() .

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getegid() , geteuid() , getgid() , getuid() , setegid() , seteuid() , setregid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctime_r (3p)

 Continue to this page.


chdir(3p)

CHDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

chdir - change working directory

SYNOPSIS

#include <unistd.h>

int chdir(const char *path);

DESCRIPTION

The chdir() function shall cause the directory named by the pathname pointed to by the path argument to become the current working directory; that is, the starting point for path searches for pathnames not beginning with '/' .

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned, the current working directory shall remain unchanged, and errno shall be set to indicate the error.

ERRORS

The chdir() function shall fail if:

EACCES
Search permission is denied for any component of the pathname.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing directory or path is an empty string.
ENOTDIR
A component of the pathname is not a directory.

The chdir() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Changing the Current Working Directory

The following example makes the value pointed to by directory, /tmp, the current working directory.

#include <unistd.h>
...
char *directory = "/tmp";
int ret;

ret = chdir (directory);

APPLICATION USAGE

None.

RATIONALE

The chdir() function only affects the working directory of the current process.

FUTURE DIRECTIONS

None.

SEE ALSO

getcwd() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fcvt (3p)

 Continue to this page.


iswblank(3p)

ISWBLANK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswblank - test for a blank wide-character code

SYNOPSIS

#include <wctype.h>

int iswblank(wint_t wc);

DESCRIPTION

The iswblank() function shall test whether wc is a wide-character code representing a character of class blank in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswblank() function shall return non-zero if wc is a blank wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <stdio.h>, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tanf (3p)

 Continue to this page.


log2(3p)

LOG2

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

log2, log2f, log2l - compute base 2 logarithm functions

SYNOPSIS

#include <math.h>

double log2(double x);
float log2f(float x);
long double log2l(long double x);

DESCRIPTION

These functions shall compute the base 2 logarithm of their argument x, log_2(x).

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the base 2 logarithm of x.

If x is ±0, a pole error shall occur and log2(), log2f(), and log2l() shall return -HUGE_VAL, -HUGE_VALF, and -HUGE_VALL, respectively.

For finite values of x that are less than 0, or if x is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is 1, +0 shall be returned.

If x is +Inf, x shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The finite value of x is less than zero, or x is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Pole Error
The value of x is zero.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , log() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tanh(3p)

TANH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tanh, tanhf, tanhl - hyperbolic tangent functions

SYNOPSIS

#include <math.h>

double tanh(double x);
float tanhf(float x);
long double tanhl(long double x);

DESCRIPTION

These functions shall compute the hyperbolic tangent of their argument x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the hyperbolic tangent of x.

If x is NaN, a NaN shall be returned.

If x is ±0, x shall be returned.

If x is ±Inf, ±1 shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions may fail if:

Range Error
The value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

atanh() , feclearexcept() , fetestexcept() , isnan() , tan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tanl (3p)

 Continue to this page.


malloc(3p)

MALLOC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

malloc - a memory allocator

SYNOPSIS

#include <stdlib.h>

void *malloc(size_t size);

DESCRIPTION

The malloc() function shall allocate unused space for an object whose size in bytes is specified by size and whose value is unspecified.

The order and contiguity of storage allocated by successive calls to malloc() is unspecified. The pointer returned if the allocation succeeds shall be suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object in the space allocated (until the space is explicitly freed or reallocated). Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer shall be returned. If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer.

RETURN VALUE

Upon successful completion with size not equal to 0, malloc() shall return a pointer to the allocated space. If size is 0, either a null pointer or a unique pointer that can be successfully passed to free() shall be returned. Otherwise, it shall return a null pointer and set errno to indicate the error.

ERRORS

The malloc() function shall fail if:

ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

calloc() , free() , realloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iconv(3p)

ICONV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iconv - codeset conversion function

SYNOPSIS

#include <iconv.h>

size_t iconv(iconv_t cd, char **restrict inbuf,
size_t *restrict inbytesleft, char **restrict outbuf,
size_t *restrict outbytesleft);

DESCRIPTION

The iconv() function shall convert the sequence of characters from one codeset, in the array specified by inbuf, into a sequence of corresponding characters in another codeset, in the array specified by outbuf. The codesets are those specified in the iconv_open() call that returned the conversion descriptor, cd. The inbuf argument points to a variable that points to the first character in the input buffer and inbytesleft indicates the number of bytes to the end of the buffer to be converted. The outbuf argument points to a variable that points to the first available byte in the output buffer and outbytesleft indicates the number of the available bytes to the end of the buffer.

For state-dependent encodings, the conversion descriptor cd is placed into its initial shift state by a call for which inbuf is a null pointer, or for which inbuf points to a null pointer. When iconv() is called in this way, and if outbuf is not a null pointer or a pointer to a null pointer, and outbytesleft points to a positive value, iconv() shall place, into the output buffer, the byte sequence to change the output buffer to its initial shift state. If the output buffer is not large enough to hold the entire reset sequence, iconv() shall fail and set errno to [E2BIG]. Subsequent calls with inbuf as other than a null pointer or a pointer to a null pointer cause the conversion to take place from the current state of the conversion descriptor.

If a sequence of input bytes does not form a valid character in the specified codeset, conversion shall stop after the previous successfully converted character. If the input buffer ends with an incomplete character or shift sequence, conversion shall stop after the previous successfully converted bytes. If the output buffer is not large enough to hold the entire converted input, conversion shall stop just prior to the input bytes that would cause the output buffer to overflow. The variable pointed to by inbuf shall be updated to point to the byte following the last byte successfully used in the conversion. The value pointed to by inbytesleft shall be decremented to reflect the number of bytes still not converted in the input buffer. The variable pointed to by outbuf shall be updated to point to the byte following the last byte of converted output data. The value pointed to by outbytesleft shall be decremented to reflect the number of bytes still available in the output buffer. For state-dependent encodings, the conversion descriptor shall be updated to reflect the shift state in effect at the end of the last successfully converted byte sequence.

If iconv() encounters a character in the input buffer that is valid, but for which an identical character does not exist in the target codeset, iconv() shall perform an implementation-defined conversion on this character.

RETURN VALUE

The iconv() function shall update the variables pointed to by the arguments to reflect the extent of the conversion and return the number of non-identical conversions performed. If the entire string in the input buffer is converted, the value pointed to by inbytesleft shall be 0. If the input conversion is stopped due to any conditions mentioned above, the value pointed to by inbytesleft shall be non-zero and errno shall be set to indicate the condition. If an error occurs, iconv() shall return (size_t)-1 and set errno to indicate the error.

ERRORS

The iconv() function shall fail if:

EILSEQ
Input conversion stopped due to an input byte that does not belong to the input codeset.
E2BIG
Input conversion stopped due to lack of space in the output buffer.
EINVAL
Input conversion stopped due to an incomplete character or shift sequence at the end of the input buffer.

The iconv() function may fail if:

EBADF
The cd argument is not a valid open conversion descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The inbuf argument indirectly points to the memory area which contains the conversion input data. The outbuf argument indirectly points to the memory area which is to contain the result of the conversion. The objects indirectly pointed to by inbuf and outbuf are not restricted to containing data that is directly representable in the ISO C standard language char data type. The type of inbuf and outbuf, char **, does not imply that the objects pointed to are interpreted as null-terminated C strings or arrays of characters. Any interpretation of a byte sequence that represents a character in a given character set encoding scheme is done internally within the codeset converters. For example, the area pointed to indirectly by inbuf and/or outbuf can contain all zero octets that are not interpreted as string terminators but as coded character data according to the respective codeset encoding scheme. The type of the data ( char, short, long, and so on) read or stored in the objects is not specified, but may be inferred for both the input and output data by the converters determined by the fromcode and tocode arguments of iconv_open().

Regardless of the data type inferred by the converter, the size of the remaining space in both input and output objects (the intbytesleft and outbytesleft arguments) is always measured in bytes.

For implementations that support the conversion of state-dependent encodings, the conversion descriptor must be able to accurately reflect the shift-state in effect at the end of the last successful conversion. It is not required that the conversion descriptor itself be updated, which would require it to be a pointer type. Thus, implementations are free to implement the descriptor as a handle (other than a pointer type) by which the conversion information can be accessed and updated.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iconv_open() , iconv_close() , the Base Definitions volume of IEEE Std 1003.1-2001, <iconv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setsockopt(3p)

SETSOCKOPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setsockopt - set the socket options

SYNOPSIS

#include <sys/socket.h>

int setsockopt(int socket, int level, int option_name,
const void *option_value, socklen_t option_len);

DESCRIPTION

The setsockopt() function shall set the option specified by the option_name argument, at the protocol level specified by the level argument, to the value pointed to by the option_value argument for the socket associated with the file descriptor specified by the socket argument.

The level argument specifies the protocol level at which the option resides. To set options at the socket level, specify the level argument as SOL_SOCKET. To set options at other levels, supply the appropriate level identifier for the protocol controlling the option. For example, to indicate that an option is interpreted by the TCP (Transport Control Protocol), set level to IPPROTO_TCP as defined in the <netinet/in.h> header.

The option_name argument specifies a single option to set. The option_name argument and any specified options are passed uninterpreted to the appropriate protocol module for interpretations. The <sys/socket.h> header defines the socket-level options. The options are as follows:

SO_DEBUG
Turns on recording of debugging information. This option enables or disables debugging in the underlying protocol modules. This option takes an int value. This is a Boolean option.
SO_BROADCAST
Permits sending of broadcast messages, if this is supported by the protocol. This option takes an int value. This is a Boolean option.
SO_REUSEADDR
Specifies that the rules used in validating addresses supplied to bind() should allow reuse of local addresses, if this is supported by the protocol. This option takes an int value. This is a Boolean option.
SO_KEEPALIVE
Keeps connections active by enabling the periodic transmission of messages, if this is supported by the protocol. This option takes an int value.

If the connected socket fails to respond to these messages, the connection is broken and threads writing to that socket are notified with a SIGPIPE signal. This is a Boolean option.

SO_LINGER
Lingers on a close() if data is present. This option controls the action taken when unsent messages queue on a socket and close() is performed. If SO_LINGER is set, the system shall block the process during close() until it can transmit the data or until the time expires. If SO_LINGER is not specified, and close() is issued, the system handles the call in a way that allows the process to continue as quickly as possible. This option takes a linger structure, as defined in the <sys/socket.h> header, to specify the state of the option and linger interval.
SO_OOBINLINE
Leaves received out-of-band data (data marked urgent) inline. This option takes an int value. This is a Boolean option.
SO_SNDBUF
Sets send buffer size. This option takes an int value.
SO_RCVBUF
Sets receive buffer size. This option takes an int value.
SO_DONTROUTE
Requests that outgoing messages bypass the standard routing facilities. The destination shall be on a directly-connected network, and messages are directed to the appropriate network interface according to the destination address. The effect, if any, of this option depends on what protocol is in use. This option takes an int value. This is a Boolean option.
SO_RCVLOWAT
Sets the minimum number of bytes to process for socket input operations. The default value for SO_RCVLOWAT is 1. If SO_RCVLOWAT is set to a larger value, blocking receive calls normally wait until they have received the smaller of the low water mark value or the requested amount. (They may return less than the low water mark if an error occurs, a signal is caught, or the type of data next in the receive queue is different from that returned; for example, out-of-band data.) This option takes an int value. Note that not all implementations allow this option to be set.
SO_RCVTIMEO
Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.
SO_SNDLOWAT
Sets the minimum number of bytes to process for socket output operations. Non-blocking output operations shall process no data if flow control does not allow the smaller of the send low water mark value or the entire request to be processed. This option takes an int value. Note that not all implementations allow this option to be set.
SO_SNDTIMEO
Sets the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent. If a send operation has blocked for this time, it shall return with a partial count or with errno set to [EAGAIN] or [EWOULDBLOCK] if no data is sent. The default for this option is zero, which indicates that a send operation shall not time out. This option stores a timeval structure. Note that not all implementations allow this option to be set.

For Boolean options, 0 indicates that the option is disabled and 1 indicates that the option is enabled.

Options at other protocol levels vary in format and name.

RETURN VALUE

Upon successful completion, setsockopt() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The setsockopt() function shall fail if:

EBADF
The socket argument is not a valid file descriptor.
EDOM
The send and receive timeout values are too big to fit into the timeout fields in the socket structure.
EINVAL
The specified option is invalid at the specified socket level or the socket has been shut down.
EISCONN
The socket is already connected, and a specified option cannot be set while the socket is connected.
ENOPROTOOPT

The option is not supported by the protocol.

ENOTSOCK
The socket argument does not refer to a socket.

The setsockopt() function may fail if:

ENOMEM
There was insufficient memory available for the operation to complete.
ENOBUFS
Insufficient resources are available in the system to complete the call.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The setsockopt() function provides an application program with the means to control socket behavior. An application program can use setsockopt() to allocate buffer space, control timeouts, or permit socket data broadcasts. The <sys/socket.h> header defines the socket-level options available to setsockopt().

Options may exist at multiple protocol levels. The SO_ options are always present at the uppermost socket level.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Sockets , bind() , endprotoent() , getsockopt() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <netinet/in.h>, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


endhostent (3p)

 Continue to this page.


logb(3p)

LOGB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

logb, logbf, logbl - radix-independent exponent

SYNOPSIS

#include <math.h>

double logb(double x);
float logbf(float x);
long double logbl(long double x);

DESCRIPTION

These functions shall compute the exponent of x, which is the integral part of log_r |x|, as a signed floating-point value, for non-zero x, where r is the radix of the machine's floating-point arithmetic, which is the value of FLT_RADIX defined in the <float.h> header.

If x is subnormal it is treated as though it were normalized; thus for finite positive x:

1 <= x * FLT_RADIX**-logb(x) < FLT_RADIX

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the exponent of x.

If x is ±0, a pole error shall occur and logb(), logbf(), and logbl() shall return -HUGE_VAL, -HUGE_VALF, and -HUGE_VALL, respectively.

If x is NaN, a NaN shall be returned.

If x is ±Inf, +Inf shall be returned.

ERRORS

These functions shall fail if:

Pole Error
The value of x is ±0.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , ilogb() , scalb() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <float.h>, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isprint(3p)

ISPRINT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isprint - test for a printable character

SYNOPSIS

#include <ctype.h>

int isprint(int c);

DESCRIPTION

The isprint() function shall test whether c is a character of class print in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isprint() function shall return non-zero if c is a printable character; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , isgraph() , islower() , ispunct() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


logf (3p)

 Continue to this page.


cacoshf (3p)

 Continue to this page.


logl (3p)

 Continue to this page.


cacoshl (3p)

 Continue to this page.


wcsxfrm(3p)

WCSXFRM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsxfrm - wide-character string transformation

SYNOPSIS

#include <wchar.h>

size_t wcsxfrm(wchar_t *restrict ws1, const wchar_t *restrict ws2,
size_t n);

DESCRIPTION

The wcsxfrm() function shall transform the wide-character string pointed to by ws2 and place the resulting wide-character string into the array pointed to by ws1. The transformation shall be such that if wcscmp() is applied to two transformed wide strings, it shall return a value greater than, equal to, or less than 0, corresponding to the result of wcscoll() applied to the same two original wide-character strings. No more than n wide-character codes shall be placed into the resulting array pointed to by ws1, including the terminating null wide-character code. If n is 0, ws1 is permitted to be a null pointer. If copying takes place between objects that overlap, the behavior is undefined.

The wcsxfrm() function shall not change the setting of errno if successful.

Since no return value is reserved to indicate an error, an application wishing to check for error situations should set errno to 0, then call wcsxfrm(), then check errno.

RETURN VALUE

The wcsxfrm() function shall return the length of the transformed wide-character string (not including the terminating null wide-character code). If the value returned is n or more, the contents of the array pointed to by ws1 are unspecified.

On error, the wcsxfrm() function may set errno, but no return value is reserved to indicate an error.

ERRORS

The wcsxfrm() function may fail if:

EINVAL
The wide-character string pointed to by ws2 contains wide-character codes outside the domain of the collating sequence.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The transformation function is such that two transformed wide-character strings can be ordered by wcscmp() as appropriate to collating sequence information in the program's locale (category LC_COLLATE ).

The fact that when n is 0 ws1 is permitted to be a null pointer is useful to determine the size of the ws1 array prior to making the transformation.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcscmp() , wcscoll() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_setlogfullpolicy (3p)

 Continue to this page.


isascii(3p)

ISASCII

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isascii - test for a 7-bit US-ASCII character

SYNOPSIS

#include <ctype.h>

int isascii(int c);

DESCRIPTION

The isascii() function shall test whether c is a 7-bit US-ASCII character code.

The isascii() function is defined on all integer values.

RETURN VALUE

The isascii() function shall return non-zero if c is a 7-bit US-ASCII character code between 0 and octal 0177 inclusive; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


msgctl(3p)

MSGCTL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

msgctl - XSI message control operations

SYNOPSIS

#include <sys/msg.h>

int msgctl(int msqid, int cmd, struct msqid_ds *buf);

DESCRIPTION

The msgctl() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The msgctl() function shall provide message control operations as specified by cmd. The following values for cmd, and the message control operations they specify, are:

IPC_STAT
Place the current value of each member of the msqid_ds data structure associated with msqid into the structure pointed to by buf. The contents of this structure are defined in <sys/msg.h>.
IPC_SET
Set the value of the following members of the msqid_ds data structure associated with msqid to the corresponding value found in the structure pointed to by buf:

msg_perm.uid
msg_perm.gid
msg_perm.mode
msg_qbytes

IPC_SET can only be executed by a process with appropriate privileges or that has an effective user ID equal to the value of msg_perm.cuid or msg_perm.uid in the msqid_ds data structure associated with msqid. Only a process with appropriate privileges can raise the value of msg_qbytes.

IPC_RMID
Remove the message queue identifier specified by msqid from the system and destroy the message queue and msqid_ds data structure associated with it. IPC_RMD can only be executed by a process with appropriate privileges or one that has an effective user ID equal to the value of msg_perm.cuid or msg_perm.uid in the msqid_ds data structure associated with msqid.

RETURN VALUE

Upon successful completion, msgctl() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The msgctl() function shall fail if:

EACCES
The argument cmd is IPC_STAT and the calling process does not have read permission; see XSI Interprocess Communication .
EINVAL
The value of msqid is not a valid message queue identifier; or the value of cmd is not a valid command.
EPERM
The argument cmd is IPC_RMID or IPC_SET and the effective user ID of the calling process is not equal to that of a process with appropriate privileges and it is not equal to the value of msg_perm.cuid or msg_perm.uid in the data structure associated with msqid.
EPERM
The argument cmd is IPC_SET, an attempt is being made to increase to the value of msg_qbytes, and the effective user ID of the calling process does not have appropriate privileges.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication (IPC). Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , mq_close() , mq_getattr() , mq_notify() , mq_open() , mq_receive() , mq_send() , mq_setattr() , mq_unlink() , msgget() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/msg.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


feof(3p)

FEOF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

feof - test end-of-file indicator on a stream

SYNOPSIS

#include <stdio.h>

int feof(FILE *stream);

DESCRIPTION

The feof() function shall test the end-of-file indicator for the stream pointed to by stream.

RETURN VALUE

The feof() function shall return non-zero if and only if the end-of-file indicator is set for stream.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clearerr() , ferror() , fopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_getclockres (3p)

 Continue to this page.


feclearexcept(3p)

FECLEAREXCEPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

feclearexcept - clear floating-point exception

SYNOPSIS

#include <fenv.h>

int feclearexcept(int excepts);

DESCRIPTION

The feclearexcept() function shall attempt to clear the supported floating-point exceptions represented by excepts.

RETURN VALUE

If the argument is zero or if all the specified exceptions were successfully cleared, feclearexcept() shall return zero. Otherwise, it shall return a non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fegetexceptflag() , feraiseexcept() , fesetexceptflag() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sem_timedwait(3p)

SEM_TIMEDWAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_timedwait - lock a semaphore (ADVANCED REALTIME)

SYNOPSIS

#include <semaphore.h>
#include <time.h>

int sem_timedwait(sem_t *restrict sem,
const struct timespec *restrict abs_timeout);

DESCRIPTION

The sem_timedwait() function shall lock the semaphore referenced by sem as in the sem_wait() function. However, if the semaphore cannot be locked without waiting for another process or thread to unlock the semaphore by performing a sem_post() function, this wait shall be terminated when the specified timeout expires.

The timeout shall expire when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call.

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock. If the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function. The resolution of the timeout shall be the resolution of the clock on which it is based. The timespec data type is defined as a structure in the <time.h> header.

Under no circumstance shall the function fail with a timeout if the semaphore can be locked immediately. The validity of the abs_timeout need not be checked if the semaphore can be locked immediately.

RETURN VALUE

The sem_timedwait() function shall return zero if the calling process successfully performed the semaphore lock operation on the semaphore designated by sem. If the call was unsuccessful, the state of the semaphore shall be unchanged, and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sem_timedwait() function shall fail if:

EINVAL
The sem argument does not refer to a valid semaphore.
EINVAL
The process or thread would have blocked, and the abs_timeout parameter specified a nanoseconds field value less than zero or greater than or equal to 1000 million.
ETIMEDOUT
The semaphore could not be locked before the specified timeout expired.

The sem_timedwait() function may fail if:

EDEADLK
A deadlock condition was detected.
EINTR
A signal interrupted this function.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

The sem_timedwait() function is part of the Semaphores and Timeouts options and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sem_post() , sem_trywait() , sem_wait() , semctl() , semget() , semop() , time() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sethostent (3p)

 Continue to this page.


pthread_setconcurrency (3p)

 Continue to this page.


tfind (3p)

 Continue to this page.


popen(3p)

POPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

popen - initiate pipe streams to or from a process

SYNOPSIS

#include <stdio.h>

FILE *popen(const char *command, const char *mode);

DESCRIPTION

The popen() function shall execute the command specified by the string command. It shall create a pipe between the calling program and the executed command, and shall return a pointer to a stream that can be used to either read from or write to the pipe.

The environment of the executed command shall be as if a child process were created within the popen() call using the fork() function, and the child invoked the sh utility using the call:

execl(shell path, "sh", "-c", command, (char *)0);

where shell path is an unspecified pathname for the sh utility.

The popen() function shall ensure that any streams from previous popen() calls that remain open in the parent process are closed in the new child process.

The mode argument to popen() is a string that specifies I/O mode:

1.
If mode is r, when the child process is started, its file descriptor STDOUT_FILENO shall be the writable end of the pipe, and the file descriptor fileno(stream) in the calling process, where stream is the stream pointer returned by popen(), shall be the readable end of the pipe.

2.
If mode is w, when the child process is started its file descriptor STDIN_FILENO shall be the readable end of the pipe, and the file descriptor fileno(stream) in the calling process, where stream is the stream pointer returned by popen(), shall be the writable end of the pipe.

3.
If mode is any other value, the result is undefined.

After popen(), both the parent and the child process shall be capable of executing independently before either terminates.

Pipe streams are byte-oriented.

RETURN VALUE

Upon successful completion, popen() shall return a pointer to an open stream that can be used to read or write to the pipe. Otherwise, it shall return a null pointer and may set errno to indicate the error.

ERRORS

The popen() function may fail if:

EMFILE
{FOPEN_MAX} or {STREAM_MAX} streams are currently open in the calling process.
EINVAL
The mode argument is invalid.

The popen() function may also set errno values as described by fork() or pipe() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Since open files are shared, a mode r command can be used as an input filter and a mode w command as an output filter.

Buffered reading before opening an input filter may leave the standard input of that filter mispositioned. Similar problems with an output filter may be prevented by careful buffer flushing; for example, with fflush() .

A stream opened by popen() should be closed by pclose().

The behavior of popen() is specified for values of mode of r and w. Other modes such as rb and wb might be supported by specific implementations, but these would not be portable features. Note that historical implementations of popen() only check to see if the first character of mode is r. Thus, a mode of robert the robot would be treated as mode r, and a mode of anything else would be treated as mode w.

If the application calls waitpid() or waitid() with a pid argument greater than 0, and it still has a stream that was called with popen() open, it must ensure that pid does not refer to the process started by popen().

To determine whether or not the environment specified in the Shell and Utilities volume of IEEE Std 1003.1-2001 is present, use the function call:

sysconf(_SC_2_VERSION)

(See sysconf() ).

RATIONALE

The popen() function should not be used by programs that have set user (or group) ID privileges. The fork() and exec family of functions (except execlp() and execvp()), should be used instead. This prevents any unforeseen manipulation of the environment of the user that could cause execution of commands not anticipated by the calling program.

If the original and popen()ed processes both intend to read or write or read and write a common file, and either will be using FILE-type C functions ( fread(), fwrite(), and so on), the rules for sharing file handles must be observed (see Interaction of File Descriptors and Standard I/O Streams ).

FUTURE DIRECTIONS

None.

SEE ALSO

pclose() , pipe() , sysconf() , system() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, sh

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dlclose(3p)

DLCLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dlclose - close a dlopen object

SYNOPSIS

#include <dlfcn.h>

int dlclose(void *handle);

DESCRIPTION

The dlclose() function shall inform the system that the object referenced by a handle returned from a previous dlopen() invocation is no longer needed by the application.

The use of dlclose() reflects a statement of intent on the part of the process, but does not create any requirement upon the implementation, such as removal of the code or symbols referenced by handle. Once an object has been closed using dlclose() an application should assume that its symbols are no longer available to dlsym(). All objects loaded automatically as a result of invoking dlopen() on the referenced object shall also be closed if this is the last reference to it.

Although a dlclose() operation is not required to remove structures from an address space, neither is an implementation prohibited from doing so. The only restriction on such a removal is that no object shall be removed to which references have been relocated, until or unless all such references are removed. For instance, an object that had been loaded with a dlopen() operation specifying the RTLD_GLOBAL flag might provide a target for dynamic relocations performed in the processing of other objects-in such environments, an application may assume that no relocation, once made, shall be undone or remade unless the object requiring the relocation has itself been removed.

RETURN VALUE

If the referenced object was successfully closed, dlclose() shall return 0. If the object could not be closed, or if handle does not refer to an open object, dlclose() shall return a non-zero value. More detailed diagnostic information shall be available through dlerror().

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following example illustrates use of dlopen() and dlclose():

...
/* Open a dynamic library and then close it ... */

#include <dlfcn.h>
void *mylib;
int eret;

mylib = dlopen("mylib.so", RTLD_LOCAL | RTLD_LAZY);
...
eret = dlclose(mylib);
...

APPLICATION USAGE

A conforming application should employ a handle returned from a dlopen() invocation only within a given scope bracketed by the dlopen() and dlclose() operations. Implementations are free to use reference counting or other techniques such that multiple calls to dlopen() referencing the same object may return the same object for handle. Implementations are also free to reuse a handle. For these reasons, the value of a handle must be treated as an opaque object by the application, used only in calls to dlsym() and dlclose().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

dlerror() , dlopen() , dlsym() , the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


munlock (3p)

 Continue to this page.


erfc(3p)

ERFC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

erfc, erfcf, erfcl - complementary error functions

SYNOPSIS

#include <math.h>

double erfc(double x);
float erfcf(float x);
long double erfcl(long double x);

DESCRIPTION

These functions shall compute the complementary error function 1.0 - erf(x).

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the value of the complementary error function.

If the correct value would cause underflow and is not representable, a range error may occur and either 0.0 (if representable), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0, +1 shall be returned.

If x is -Inf, +2 shall be returned.

If x is +Inf, +0 shall be returned.

If the correct value would cause underflow and is representable, a range error may occur and the correct value shall be returned.

ERRORS

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The erfc() function is provided because of the extreme loss of relative accuracy if erf(x) is called for large x and the result subtracted from 1.0.

Note for IEEE Std 754-1985 double, 26.55 < x implies erfc( x) has underflowed.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

erf() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fwscanf (3p)

 Continue to this page.


erff (3p)

 Continue to this page.


erfl (3p)

 Continue to this page.


pthread_attr_getstack(3p)

PTHREAD_ATTR_GETSTACK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getstack, pthread_attr_setstack - get and set stack attributes

SYNOPSIS

#include <pthread.h>

int pthread_attr_getstack(const pthread_attr_t *restrict attr,
void **restrict stackaddr, size_t *restrict stacksize);
int pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr,
size_t stacksize);

DESCRIPTION

The pthread_attr_getstack() and pthread_attr_setstack() functions, respectively, shall get and set the thread creation stack attributes stackaddr and stacksize in the attr object.

The stack attributes specify the area of storage to be used for the created thread's stack. The base (lowest addressable byte) of the storage shall be stackaddr, and the size of the storage shall be stacksize bytes. The stacksize shall be at least {PTHREAD_STACK_MIN}. The stackaddr shall be aligned appropriately to be used as a stack; for example, pthread_attr_setstack() may fail with [EINVAL] if ( stackaddr & 0x7) is not 0. All pages within the stack described by stackaddr and stacksize shall be both readable and writable by the thread.

RETURN VALUE

Upon successful completion, these functions shall return a value of 0; otherwise, an error number shall be returned to indicate the error.

The pthread_attr_getstack() function shall store the stack attribute values in stackaddr and stacksize if successful.

ERRORS

The pthread_attr_setstack() function shall fail if:

EINVAL
The value of stacksize is less than {PTHREAD_STACK_MIN} or exceeds an implementation-defined limit.

The pthread_attr_setstack() function may fail if:

EINVAL
The value of stackaddr does not have proper alignment to be used as a stack, or if ( stackaddr + stacksize) lacks proper alignment.
EACCES
The stack page(s) described by stackaddr and stacksize are not both readable and writable by the thread.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are appropriate for use by applications in an environment where the stack for a thread must be placed in some particular region of memory.

While it might seem that an application could detect stack overflow by providing a protected page outside the specified stack region, this cannot be done portably. Implementations are free to place the thread's initial stack pointer anywhere within the specified region to accommodate the machine's stack pointer behavior and allocation requirements. Furthermore, on some architectures, such as the IA-64, "overflow" might mean that two separate stack pointers allocated within the region will overlap somewhere in the middle of the region.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_init() , pthread_attr_setdetachstate() , pthread_attr_setstacksize() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fwide(3p)

FWIDE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fwide - set stream orientation

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

int fwide(FILE *stream, int mode);

DESCRIPTION

The fwide() function shall determine the orientation of the stream pointed to by stream. If mode is greater than zero, the function first attempts to make the stream wide-oriented. If mode is less than zero, the function first attempts to make the stream byte-oriented. Otherwise, mode is zero and the function does not alter the orientation of the stream.

If the orientation of the stream has already been determined, fwide() shall not change it.

Since no return value is reserved to indicate an error, an application wishing to check for error situations should set errno to 0, then call fwide(), then check errno, and if it is non-zero, assume an error has occurred.

RETURN VALUE

The fwide() function shall return a value greater than zero if, after the call, the stream has wide-orientation, a value less than zero if the stream has byte-orientation, or zero if the stream has no orientation.

ERRORS

The fwide() function may fail if:

EBADF
The stream argument is not a valid stream.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

A call to fwide() with mode set to zero can be used to determine the current orientation of a stream.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


putmsg(3p)

PUTMSG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

putmsg, putpmsg - send a message on a STREAM (STREAMS)

SYNOPSIS

#include <stropts.h>

int putmsg(int fildes, const struct strbuf *ctlptr,
const struct strbuf *dataptr, int flags);
int putpmsg(int fildes, const struct strbuf *ctlptr,
const struct strbuf *dataptr, int band, int flags);

DESCRIPTION

The putmsg() function shall create a message from a process buffer(s) and send the message to a STREAMS file. The message may contain either a data part, a control part, or both. The data and control parts are distinguished by placement in separate buffers, as described below. The semantics of each part are defined by the STREAMS module that receives the message.

The putpmsg() function is equivalent to putmsg(), except that the process can send messages in different priority bands. Except where noted, all requirements on putmsg() also pertain to putpmsg().

The fildes argument specifies a file descriptor referencing an open STREAM. The ctlptr and dataptr arguments each point to a strbuf structure.

The ctlptr argument points to the structure describing the control part, if any, to be included in the message. The buf member in the strbuf structure points to the buffer where the control information resides, and the len member indicates the number of bytes to be sent. The maxlen member is not used by putmsg(). In a similar manner, the argument dataptr specifies the data, if any, to be included in the message. The flags argument indicates what type of message should be sent and is described further below.

To send the data part of a message, the application shall ensure that dataptr is not a null pointer and the len member of dataptr is 0 or greater. To send the control part of a message, the application shall ensure that the corresponding values are set for ctlptr. No data (control) part shall be sent if either dataptr( ctlptr) is a null pointer or the len member of dataptr( ctlptr) is set to -1.

For putmsg(), if a control part is specified and flags is set to RS_HIPRI, a high priority message shall be sent. If no control part is specified, and flags is set to RS_HIPRI, putmsg() shall fail and set errno to [EINVAL]. If flags is set to 0, a normal message (priority band equal to 0) shall be sent. If a control part and data part are not specified and flags is set to 0, no message shall be sent and 0 shall be returned.

For putpmsg(), the flags are different. The flags argument is a bitmask with the following mutually-exclusive flags defined: MSG_HIPRI and MSG_BAND. If flags is set to 0, putpmsg() shall fail and set errno to [EINVAL]. If a control part is specified and flags is set to MSG_HIPRI and band is set to 0, a high-priority message shall be sent. If flags is set to MSG_HIPRI and either no control part is specified or band is set to a non-zero value, putpmsg() shall fail and set errno to [EINVAL]. If flags is set to MSG_BAND, then a message shall be sent in the priority band specified by band. If a control part and data part are not specified and flags is set to MSG_BAND, no message shall be sent and 0 shall be returned.

The putmsg() function shall block if the STREAM write queue is full due to internal flow control conditions, with the following exceptions:

*
For high-priority messages, putmsg() shall not block on this condition and continues processing the message.

*
For other messages, putmsg() shall not block but shall fail when the write queue is full and O_NONBLOCK is set.

The putmsg() function shall also block, unless prevented by lack of internal resources, while waiting for the availability of message blocks in the STREAM, regardless of priority or whether O_NONBLOCK has been specified. No partial message shall be sent.

RETURN VALUE

Upon successful completion, putmsg() and putpmsg() shall return 0; otherwise, they shall return -1 and set errno to indicate the error.

ERRORS

The putmsg() and putpmsg() functions shall fail if:

EAGAIN
A non-priority message was specified, the O_NONBLOCK flag is set, and the STREAM write queue is full due to internal flow control conditions; or buffers could not be allocated for the message that was to be created.
EBADF
fildes is not a valid file descriptor open for writing.
EINTR
A signal was caught during putmsg().
EINVAL
An undefined value is specified in flags, or flags is set to RS_HIPRI or MSG_HIPRI and no control part is supplied, or the STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer, or flags is set to MSG_HIPRI and band is non-zero (for putpmsg() only).
ENOSR
Buffers could not be allocated for the message that was to be created due to insufficient STREAMS memory resources.
ENOSTR
A STREAM is not associated with fildes.
ENXIO
A hangup condition was generated downstream for the specified STREAM.
EPIPE or EIO
The fildes argument refers to a STREAMS-based pipe and the other end of the pipe is closed. A SIGPIPE signal is generated for the calling thread.
ERANGE
The size of the data part of the message does not fall within the range specified by the maximum and minimum packet sizes of the topmost STREAM module. This value is also returned if the control part of the message is larger than the maximum configured size of the control part of a message, or if the data part of a message is larger than the maximum configured size of the data part of a message.

In addition, putmsg() and putpmsg() shall fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno does not reflect the result of putmsg() or putpmsg(), but reflects the prior error.

The following sections are informative.

EXAMPLES

Sending a High-Priority Message

The value of fd is assumed to refer to an open STREAMS file. This call to putmsg() does the following:

1.
Creates a high-priority message with a control part and a data part, using the buffers pointed to by ctrlbuf and databuf, respectively.

2.
Sends the message to the STREAMS file identified by fd.

#include <stropts.h>
#include <string.h>
...
int fd;
char *ctrlbuf = "This is the control part";
char *databuf = "This is the data part";
struct strbuf ctrl;
struct strbuf data;
int ret;

ctrl.buf = ctrlbuf;
ctrl.len = strlen(ctrlbuf);

data.buf = databuf;
data.len = strlen(databuf);

ret = putmsg(fd, &ctrl, &data, MSG_HIPRI);

Using putpmsg()

This example has the same effect as the previous example. In this example, however, the putpmsg() function creates and sends the message to the STREAMS file.

#include <stropts.h>
#include <string.h>
...
int fd;
char *ctrlbuf = "This is the control part";
char *databuf = "This is the data part";
struct strbuf ctrl;
struct strbuf data;
int ret;

ctrl.buf = ctrlbuf;
ctrl.len = strlen(ctrlbuf);

data.buf = databuf;
data.len = strlen(databuf);

ret = putpmsg(fd, &ctrl, &data, 0, MSG_HIPRI);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

STREAMS , getmsg() , poll() , read() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ccoshf (3p)

 Continue to this page.


gethostname(3p)

GETHOSTNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gethostname - get name of current host

SYNOPSIS

#include <unistd.h>

int gethostname(char *name, size_t namelen);

DESCRIPTION

The gethostname() function shall return the standard host name for the current machine. The namelen argument shall specify the size of the array pointed to by the name argument. The returned name shall be null-terminated, except that if namelen is an insufficient length to hold the host name, then the returned name shall be truncated and it is unspecified whether the returned name is null-terminated.

Host names are limited to {HOST_NAME_MAX} bytes.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

gethostid() , uname() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ccoshl (3p)

 Continue to this page.


strtok_r (3p)

 Continue to this page.


aio_suspend(3p)

AIO_SUSPEND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio_suspend - wait for an asynchronous I/O request (REALTIME)

SYNOPSIS

#include <aio.h>

int aio_suspend(const struct aiocb * const list[], int nent,
const struct timespec *timeout);

DESCRIPTION

The aio_suspend() function shall suspend the calling thread until at least one of the asynchronous I/O operations referenced by the list argument has completed, until a signal interrupts the function, or, if timeout is not NULL, until the time interval specified by timeout has passed. If any of the aiocb structures in the list correspond to completed asynchronous I/O operations (that is, the error status for the operation is not equal to [EINPROGRESS]) at the time of the call, the function shall return without suspending the calling thread. The list argument is an array of pointers to asynchronous I/O control blocks. The nent argument indicates the number of elements in the array. Each aiocb structure pointed to has been used in initiating an asynchronous I/O request via aio_read(), aio_write(), or lio_listio(). This array may contain NULL pointers, which are ignored. If this array contains pointers that refer to aiocb structures that have not been used in submitting asynchronous I/O, the effect is undefined.

If the time interval indicated in the timespec structure pointed to by timeout passes before any of the I/O operations referenced by list are completed, then aio_suspend() shall return with an error. If the Monotonic Clock option is supported, the clock that shall be used to measure this time interval shall be the CLOCK_MONOTONIC clock.

RETURN VALUE

If the aio_suspend() function returns after one or more asynchronous I/O operations have completed, the function shall return zero. Otherwise, the function shall return a value of -1 and set errno to indicate the error.

The application may determine which asynchronous I/O completed by scanning the associated error and return status using aio_error() and aio_return(), respectively.

ERRORS

The aio_suspend() function shall fail if:

EAGAIN
No asynchronous I/O indicated in the list referenced by list completed in the time interval indicated by timeout.
EINTR
A signal interrupted the aio_suspend() function. Note that, since each asynchronous I/O operation may possibly provoke a signal when it completes, this error return may be caused by the completion of one (or more) of the very I/O operations being awaited.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The aio_suspend() function is part of the Asynchronous Input and Output option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_read() , aio_write() , lio_listio() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setjmp(3p)

SETJMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setjmp - set jump point for a non-local goto

SYNOPSIS

#include <setjmp.h>

int setjmp(jmp_buf env);

DESCRIPTION

A call to setjmp() shall save the calling environment in its env argument for later use by longjmp().

It is unspecified whether setjmp() is a macro or a function. If a macro definition is suppressed in order to access an actual function, or a program defines an external identifier with the name setjmp, the behavior is undefined.

An application shall ensure that an invocation of setjmp() appears in one of the following contexts only:

*
The entire controlling expression of a selection or iteration statement

*
One operand of a relational or equality operator with the other operand an integral constant expression, with the resulting expression being the entire controlling expression of a selection or iteration statement

*
The operand of a unary '!' operator with the resulting expression being the entire controlling expression of a selection or iteration

*
The entire expression of an expression statement (possibly cast to void)

If the invocation appears in any other context, the behavior is undefined.

RETURN VALUE

If the return is from a direct invocation, setjmp() shall return 0. If the return is from a call to longjmp(), setjmp() shall return a non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

In general, sigsetjmp() is more useful in dealing with errors and interrupts encountered in a low-level subroutine of a program.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

longjmp() , sigsetjmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <setjmp.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventid_open (3p)

 Continue to this page.


pclose(3p)

PCLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pclose - close a pipe stream to or from a process

SYNOPSIS

#include <stdio.h>

int pclose(FILE *stream);

DESCRIPTION

The pclose() function shall close a stream that was opened by popen(), wait for the command to terminate, and return the termination status of the process that was running the command language interpreter. However, if a call caused the termination status to be unavailable to pclose(), then pclose() shall return -1 with errno set to [ECHILD] to report this situation. This can happen if the application calls one of the following functions:

*
wait()

*
waitpid() with a pid argument less than or equal to 0 or equal to the process ID of the command line interpreter

*
Any other function not defined in this volume of IEEE Std 1003.1-2001 that could do one of the above

In any case, pclose() shall not return before the child process created by popen() has terminated.

If the command language interpreter cannot be executed, the child termination status returned by pclose() shall be as if the command language interpreter terminated using exit(127) or _exit(127).

The pclose() function shall not affect the termination status of any child of the calling process other than the one created by popen() for the associated stream.

If the argument stream to pclose() is not a pointer to a stream created by popen(), the result of pclose() is undefined.

RETURN VALUE

Upon successful return, pclose() shall return the termination status of the command language interpreter. Otherwise, pclose() shall return -1 and set errno to indicate the error.

ERRORS

The pclose() function shall fail if:

ECHILD
The status of the child process could not be obtained, as described above.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

There is a requirement that pclose() not return before the child process terminates. This is intended to disallow implementations that return [EINTR] if a signal is received while waiting. If pclose() returned before the child terminated, there would be no way for the application to discover which child used to be associated with the stream, and it could not do the cleanup itself.

If the stream pointed to by stream was not created by popen(), historical implementations of pclose() return -1 without setting errno. To avoid requiring pclose() to set errno in this case, IEEE Std 1003.1-2001 makes the behavior unspecified. An application should not use pclose() to close any stream that was not created by popen().

Some historical implementations of pclose() either block or ignore the signals SIGINT, SIGQUIT, and SIGHUP while waiting for the child process to terminate. Since this behavior is not described for the pclose() function in IEEE Std 1003.1-2001, such implementations are not conforming. Also, some historical implementations return [EINTR] if a signal is received, even though the child process has not terminated. Such implementations are also considered non-conforming.

Consider, for example, an application that uses:

popen("command", "r")

to start command, which is part of the same application. The parent writes a prompt to its standard output (presumably the terminal) and then reads from the popen()ed stream. The child reads the response from the user, does some transformation on the response (pathname expansion, perhaps) and writes the result to its standard output. The parent process reads the result from the pipe, does something with it, and prints another prompt. The cycle repeats. Assuming that both processes do appropriate buffer flushing, this would be expected to work.

To conform to IEEE Std 1003.1-2001, pclose() must use waitpid(), or some similar function, instead of wait().

The code sample below illustrates how the pclose() function might be implemented on a system conforming to IEEE Std 1003.1-2001.

int pclose(FILE *stream)
{
    int stat;
    pid_t pid;

    pid = <pid for process created for stream by popen()>
    (void) fclose(stream);
    while (waitpid(pid, &stat, 0) == -1) {
        if (errno != EINTR){
            stat = -1;
            break;
        }
    }
    return(stat);
}

FUTURE DIRECTIONS

None.

SEE ALSO

fork() , popen() , waitpid() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getcwd(3p)

GETCWD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getcwd - get the pathname of the current working directory

SYNOPSIS

#include <unistd.h>

char *getcwd(char *buf, size_t size);

DESCRIPTION

The getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf. The pathname copied to the array shall contain no components that are symbolic links. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behavior of getcwd() is unspecified.

RETURN VALUE

Upon successful completion, getcwd() shall return the buf argument. Otherwise, getcwd() shall return a null pointer and set errno to indicate the error. The contents of the array pointed to by buf are then undefined.

ERRORS

The getcwd() function shall fail if:

EINVAL
The size argument is 0.
ERANGE
The size argument is greater than 0, but is smaller than the length of the pathname +1.

The getcwd() function may fail if:

EACCES
Read or search permission was denied for a component of the pathname.
ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

Determining the Absolute Pathname of the Current Working Directory

The following example returns a pointer to an array that holds the absolute pathname of the current working directory. The pointer is returned in the ptr variable, which points to the buf array where the pathname is stored.

#include <stdlib.h>
#include <unistd.h>
...
long size;
char *buf;
char *ptr;

size = pathconf(".", _PC_PATH_MAX);

if ((buf = (char *)malloc((size_t)size)) != NULL)
    ptr = getcwd(buf, (size_t)size);
...

APPLICATION USAGE

None.

RATIONALE

Since the maximum pathname length is arbitrary unless {PATH_MAX} is defined, an application generally cannot supply a buf with size {{PATH_MAX}+1}.

Having getcwd() take no arguments and instead use the malloc() function to produce space for the returned argument was considered. The advantage is that getcwd() knows how big the working directory pathname is and can allocate an appropriate amount of space. But the programmer would have to use the free() function to free the resulting object, or each use of getcwd() would further reduce the available memory. Also, malloc() and free() are used nowhere else in this volume of IEEE Std 1003.1-2001. Finally, getcwd() is taken from the SVID where it has the two arguments used in this volume of IEEE Std 1003.1-2001.

The older function getwd() was rejected for use in this context because it had only a buffer argument and no size argument, and thus had no way to prevent overwriting the buffer, except to depend on the programmer to provide a large enough buffer.

On some implementations, if buf is a null pointer, getcwd() may obtain size bytes of memory using malloc(). In this case, the pointer returned by getcwd() may be used as the argument in a subsequent call to free(). Invoking getcwd() with buf as a null pointer is not recommended in conforming applications.

If a program is operating in a directory where some (grand)parent directory does not permit reading, getcwd() may fail, as in most implementations it must read the directory to determine the name of the file. This can occur if search, but not read, permission is granted in an intermediate directory, or if the program is placed in that directory by some more privileged process (for example, login). Including the [EACCES] error condition makes the reporting of the error consistent and warns the application writer that getcwd() can fail for reasons beyond the control of the application writer or user. Some implementations can avoid this occurrence (for example, by implementing getcwd() using pwd, where pwd is a set-user-root process), thus the error was made optional. Since this volume of IEEE Std 1003.1-2001 permits the addition of other errors, this would be a common addition and yet one that applications could not be expected to deal with without this addition.

FUTURE DIRECTIONS

None.

SEE ALSO

malloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setkey(3p)

SETKEY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setkey - set encoding key (CRYPT)

SYNOPSIS

#include <stdlib.h>

void setkey(const char *key);

DESCRIPTION

The setkey() function provides access to an implementation-defined encoding algorithm. The argument of setkey() is an array of length 64 bytes containing only the bytes with numerical value of 0 and 1. If this string is divided into groups of 8, the low-order bit in each group is ignored; this gives a 56-bit key which is used by the algorithm. This is the key that shall be used with the algorithm to encode a string block passed to encrypt().

The setkey() function shall not change the setting of errno if successful. An application wishing to check for error situations should set errno to 0 before calling setkey(). If errno is non-zero on return, an error has occurred.

The setkey() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

No values are returned.

ERRORS

The setkey() function shall fail if:

ENOSYS
The functionality is not supported on this implementation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Decoding need not be implemented in all environments. This is related to government restrictions in some countries on encryption and decryption routines. Historical practice has been to ship a different version of the encryption library without the decryption feature in the routines supplied. Thus the exported version of encrypt() does encoding but not decoding.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

crypt() , encrypt() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


bzero(3p)

BZERO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bzero - memory operations (LEGACY)

SYNOPSIS

#include <strings.h>

void bzero(void *s, size_t n);

DESCRIPTION

The bzero() function shall place n zero-valued bytes in the area pointed to by s.

RETURN VALUE

The bzero() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The memset() function is preferred over this function.

For maximum portability, it is recommended to replace the function call to bzero() as follows:

#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

memset() , the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlockattr_setpshared (3p)

 Continue to this page.


fdatasync(3p)

FDATASYNC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fdatasync - synchronize the data of a file (REALTIME)

SYNOPSIS

#include <unistd.h>

int fdatasync(int fildes);

DESCRIPTION

The fdatasync() function shall force all currently queued I/O operations associated with the file indicated by file descriptor fildes to the synchronized I/O completion state.

The functionality shall be equivalent to fsync() with the symbol _POSIX_SYNCHRONIZED_IO defined, with the exception that all I/O operations shall be completed as defined for synchronized I/O data integrity completion.

RETURN VALUE

If successful, the fdatasync() function shall return the value 0; otherwise, the function shall return the value -1 and set errno to indicate the error. If the fdatasync() function fails, outstanding I/O operations are not guaranteed to have been completed.

ERRORS

The fdatasync() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor open for writing.
EINVAL
This implementation does not support synchronized I/O for this file.

In the event that any of the queued I/O operations fail, fdatasync() shall return the error conditions defined for read() and write().

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_fsync() , fcntl() , fsync() , open() , read() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_getstackaddr(3p)

PTHREAD_ATTR_GETSTACKADDR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getstackaddr, pthread_attr_setstackaddr - get and set the stackaddr attribute

SYNOPSIS

#include <pthread.h>

int pthread_attr_getstackaddr(const pthread_attr_t *restrict attr,
void **restrict stackaddr);
int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr);

DESCRIPTION

The pthread_attr_getstackaddr() and pthread_attr_setstackaddr() functions, respectively, shall get and set the thread creation stackaddr attribute in the attr object.

The stackaddr attribute specifies the location of storage to be used for the created thread's stack. The size of the storage shall be at least {PTHREAD_STACK_MIN}.

RETURN VALUE

Upon successful completion, pthread_attr_getstackaddr() and pthread_attr_setstackaddr() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.

The pthread_attr_getstackaddr() function stores the stackaddr attribute value in stackaddr if successful.

ERRORS

No errors are defined.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The specification of the stackaddr attribute presents several ambiguities that make portable use of these interfaces impossible. The description of the single address parameter as a "stack" does not specify a particular relationship between the address and the "stack" implied by that address. For example, the address may be taken as the low memory address of a buffer intended for use as a stack, or it may be taken as the address to be used as the initial stack pointer register value for the new thread. These two are not the same except for a machine on which the stack grows "up" from low memory to high, and on which a "push" operation first stores the value in memory and then increments the stack pointer register. Further, on a machine where the stack grows "down" from high memory to low, interpretation of the address as the "low memory" address requires a determination of the intended size of the stack. IEEE Std 1003.1-2001 has introduced the new interfaces pthread_attr_setstack() and pthread_attr_getstack() to resolve these ambiguities.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_attr_getdetachstate()
, pthread_attr_getstack() , pthread_attr_getstacksize()
, pthread_attr_setstack() , pthread_create() , the
Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>,
<pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tcsetattr(3p)

TCSETATTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcsetattr - set the parameters associated with the terminal

SYNOPSIS

#include <termios.h>

int tcsetattr(int fildes, int optional_actions,
const struct termios *termios_p);

DESCRIPTION

The tcsetattr() function shall set the parameters associated with the terminal referred to by the open file descriptor fildes (an open file descriptor associated with a terminal) from the termios structure referenced by termios_p as follows:

*
If optional_actions is TCSANOW, the change shall occur immediately.

*
If optional_actions is TCSADRAIN, the change shall occur after all output written to fildes is transmitted. This function should be used when changing parameters that affect output.

*
If optional_actions is TCSAFLUSH, the change shall occur after all output written to fildes is transmitted, and all input so far received but not read shall be discarded before the change is made.

If the output baud rate stored in the termios structure pointed to by termios_p is the zero baud rate, B0, the modem control lines shall no longer be asserted. Normally, this shall disconnect the line.

If the input baud rate stored in the termios structure pointed to by termios_p is 0, the input baud rate given to the hardware is the same as the output baud rate stored in the termios structure.

The tcsetattr() function shall return successfully if it was able to perform any of the requested actions, even if some of the requested actions could not be performed. It shall set all the attributes that the implementation supports as requested and leave all the attributes not supported by the implementation unchanged. If no part of the request can be honored, it shall return -1 and set errno to [EINVAL]. If the input and output baud rates differ and are a combination that is not supported, neither baud rate shall be changed. A subsequent call to tcgetattr() shall return the actual state of the terminal device (reflecting both the changes made and not made in the previous tcsetattr() call). The tcsetattr() function shall not change the values found in the termios structure under any circumstances.

The effect of tcsetattr() is undefined if the value of the termios structure pointed to by termios_p was not derived from the result of a call to tcgetattr() on fildes; an application should modify only fields and flags defined by this volume of IEEE Std 1003.1-2001 between the call to tcgetattr() and tcsetattr(), leaving all other fields and flags unmodified.

No actions defined by this volume of IEEE Std 1003.1-2001, other than a call to tcsetattr() or a close of the last file descriptor in the system associated with this terminal device, shall cause any of the terminal attributes defined by this volume of IEEE Std 1003.1-2001 to change.

If tcsetattr() is called from a process which is a member of a background process group on a fildes associated with its controlling terminal:

*
If the calling process is blocking or ignoring SIGTTOU signals, the operation completes normally and no signal is sent.

*
Otherwise, a SIGTTOU signal shall be sent to the process group.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcsetattr() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINTR
A signal interrupted tcsetattr().
EINVAL
The optional_actions argument is not a supported value, or an attempt was made to change an attribute represented in the termios structure to an unsupported value.
ENOTTY
The file associated with fildes is not a terminal.

The tcsetattr() function may fail if:

EIO
The process group of the writing process is orphaned, and the writing process is not ignoring or blocking SIGTTOU.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If trying to change baud rates, applications should call tcsetattr() then call tcgetattr() in order to determine what baud rates were actually selected.

RATIONALE

The tcsetattr() function can be interrupted in the following situations:

*
It is interrupted while waiting for output to drain.

*
It is called from a process in a background process group and SIGTTOU is caught.

See also the RATIONALE section in tcgetattr() .

FUTURE DIRECTIONS

Using an input baud rate of 0 to set the input rate equal to the output rate may not necessarily be supported in a future version of this volume of IEEE Std 1003.1-2001.

SEE ALSO

cfgetispeed() , tcgetattr() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


msgget(3p)

MSGGET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

msgget - get the XSI message queue identifier

SYNOPSIS

#include <sys/msg.h>

int msgget(key_t key, int msgflg);

DESCRIPTION

The msgget() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The msgget() function shall return the message queue identifier associated with the argument key.

A message queue identifier, associated message queue, and data structure (see <sys/msg.h>), shall be created for the argument key if one of the following is true:

*
The argument key is equal to IPC_PRIVATE.

*
The argument key does not already have a message queue identifier associated with it, and (msgflg & IPC_CREAT) is non-zero.

Upon creation, the data structure associated with the new message queue identifier shall be initialized as follows:

*
msg_perm.cuid, msg_perm.uid, msg_perm.cgid, and msg_perm.gid shall be set equal to the effective user ID and effective group ID, respectively, of the calling process.

*
The low-order 9 bits of msg_perm.mode shall be set equal to the low-order 9 bits of msgflg.

*
msg_qnum, msg_lspid, msg_lrpid, msg_stime, and msg_rtime shall be set equal to 0.

*
msg_ctime shall be set equal to the current time.

*
msg_qbytes shall be set equal to the system limit.

RETURN VALUE

Upon successful completion, msgget() shall return a non-negative integer, namely a message queue identifier. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The msgget() function shall fail if:

EACCES
A message queue identifier exists for the argument key, but operation permission as specified by the low-order 9 bits of msgflg would not be granted; see XSI Interprocess Communication .
EEXIST
A message queue identifier exists for the argument key but ((msgflg & IPC_CREAT) && (msgflg & IPC_EXCL)) is non-zero.
ENOENT
A message queue identifier does not exist for the argument key and (msgflg & IPC_CREAT) is 0.
ENOSPC
A message queue identifier is to be created but the system-imposed limit on the maximum number of allowed message queue identifiers system-wide would be exceeded.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication (IPC). Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , mq_close() , mq_getattr() , mq_notify() , mq_open() , mq_receive() , mq_send() , mq_setattr() , mq_unlink() , msgctl() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/msg.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


islessequal(3p)

ISLESSEQUAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

islessequal - test if x is less than or equal to y

SYNOPSIS

#include <math.h>

int islessequal(real-floating x, real-floating y);

DESCRIPTION

The islessequal() macro shall determine whether its first argument is less than or equal to its second argument. The value of islessequal( x, y) shall be equal to (x) <= (y); however, unlike (x) <= (y), islessequal( x, y) shall not raise the invalid floating-point exception when x and y are unordered.

RETURN VALUE

Upon successful completion, the islessequal() macro shall return the value of (x) <= (y).

If x or y is NaN, 0 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values, exactly one of the relationships (less, greater, and equal) is true. Relational operators may raise the invalid floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. This macro is a quiet (non-floating-point exception raising) version of a relational operator. It facilitates writing efficient code that accounts for NaNs without suffering the invalid floating-point exception. In the SYNOPSIS section, real-floating indicates that the argument shall be an expression of real-floating type.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isgreater() , isgreaterequal() , isless() , islessgreater() , isunordered() , the Base Definitions volume of IEEE Std 1003.1-2001 <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlockattr_destroy (3p)

 Continue to this page.


recvmsg(3p)

RECVMSG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

recvmsg - receive a message from a socket

SYNOPSIS

#include <sys/socket.h>

ssize_t recvmsg(int socket, struct msghdr *message, int flags);

DESCRIPTION

The recvmsg() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.

The recvmsg() function takes the following arguments:

socket
Specifies the socket file descriptor.
message
Points to a msghdr structure, containing both the buffer to store the source address and the buffers for the incoming message. The length and format of the address depend on the address family of the socket. The msg_flags member is ignored on input, but may contain meaningful values on output.
flags
Specifies the type of message reception. Values of this argument are formed by logically OR'ing zero or more of the following values:
MSG_OOB
Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific.
MSG_PEEK
Peeks at the incoming message.
MSG_WAITALL
On SOCK_STREAM sockets this requests that the function block until the full amount of data can be returned. The function may return the smaller amount of data if the socket is a message-based socket, if a signal is caught, if the connection is terminated, if MSG_PEEK was specified, or if an error is pending for the socket.

The recvmsg() function shall receive messages from unconnected or connected sockets and shall return the length of the message.

The recvmsg() function shall return the total length of the message. For message-based sockets, such as SOCK_DGRAM and SOCK_SEQPACKET, the entire message shall be read in a single operation. If a message is too long to fit in the supplied buffers, and MSG_PEEK is not set in the flags argument, the excess bytes shall be discarded, and MSG_TRUNC shall be set in the msg_flags member of the msghdr structure. For stream-based sockets, such as SOCK_STREAM, message boundaries shall be ignored. In this case, data shall be returned to the user as soon as it becomes available, and no data shall be discarded.

If the MSG_WAITALL flag is not set, data shall be returned only up to the end of the first message.

If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, recvmsg() shall block until a message arrives. If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, the recvmsg() function shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].

In the msghdr structure, the msg_name and msg_namelen members specify the source address if the socket is unconnected. If the socket is connected, the msg_name and msg_namelen members shall be ignored. The msg_name member may be a null pointer if no names are desired or required. The msg_iov and msg_iovlen fields are used to specify where the received data shall be stored. msg_iov points to an array of iovec structures; msg_iovlen shall be set to the dimension of this array. In each iovec structure, the iov_base field specifies a storage area and the iov_len field gives its size in bytes. Each storage area indicated by msg_iov is filled with received data in turn until all of the received data is stored or all of the areas have been filled.

Upon successful completion, the msg_flags member of the message header shall be the bitwise-inclusive OR of all of the following flags that indicate conditions detected for the received message:

MSG_EOR
End-of-record was received (if supported by the protocol).
MSG_OOB
Out-of-band data was received.
MSG_TRUNC
Normal data was truncated.
MSG_CTRUNC
Control data was truncated.

RETURN VALUE

Upon successful completion, recvmsg() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recvmsg() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The recvmsg() function shall fail if:

EAGAIN or EWOULDBLOCK

The socket's file descriptor is marked O_NONBLOCK and no data is waiting to be received; or MSG_OOB is set and no out-of-band data is available and either the socket's file descriptor is marked O_NONBLOCK or the socket does not support blocking to await out-of-band data.

EBADF
The socket argument is not a valid open file descriptor.
ECONNRESET
A connection was forcibly closed by a peer.
EINTR
This function was interrupted by a signal before any data was available.
EINVAL
The sum of the iov_len values overflows a ssize_t, or the MSG_OOB flag is set and no out-of-band data is available.
EMSGSIZE
The msg_iovlen member of the msghdr structure pointed to by message is less than or equal to 0, or is greater than {IOV_MAX}.
ENOTCONN
A receive is attempted on a connection-mode socket that is not connected.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The specified flags are not supported for this socket type.
ETIMEDOUT
The connection timed out during connection establishment, or due to a transmission timeout on active connection.

The recvmsg() function may fail if:

EIO
An I/O error occurred while reading from or writing to the file system.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The select() and poll() functions can be used to determine when data is available to be received.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

poll() , recv() , recvfrom() , select() , send() , sendmsg() , sendto() , shutdown() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mktemp(3p)

MKTEMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mktemp - make a unique filename (LEGACY)

SYNOPSIS

#include <stdlib.h>

char *mktemp(char *template);

DESCRIPTION

The mktemp() function shall replace the contents of the string pointed to by template by a unique filename and return template. The application shall initialize template to be a filename with six trailing 'X' s; mktemp() shall replace each 'X' with a single byte character from the portable filename character set.

RETURN VALUE

The mktemp() function shall return the pointer template. If a unique name cannot be created, template shall point to a null string.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Generating a Filename

The following example replaces the contents of the "template" string with a 10-character filename beginning with the characters "file" and returns a pointer to the "template" string that contains the new filename.

#include <stdlib.h>
...
char *template = "/tmp/fileXXXXXX";
char *ptr;

ptr = mktemp(template);

APPLICATION USAGE

Between the time a pathname is created and the file opened, it is possible for some other process to create a file with the same name. The mkstemp() function avoids this problem and is preferred over this function.

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

mkstemp() , tmpfile() , tmpnam() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sem_trywait (3p)

 Continue to this page.


atanhf (3p)

 Continue to this page.


atanhl (3p)

 Continue to this page.


fegetenv(3p)

FEGETENV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fegetenv, fesetenv - get and set current floating-point environment

SYNOPSIS

#include <fenv.h>

int fegetenv(fenv_t *envp);
int fesetenv(const fenv_t *envp);

DESCRIPTION

The fegetenv() function shall attempt to store the current floating-point environment in the object pointed to by envp.

The fesetenv() function shall attempt to establish the floating-point environment represented by the object pointed to by envp. The argument envp shall point to an object set by a call to fegetenv() or feholdexcept(), or equal a floating-point environment macro. The fesetenv() function does not raise floating-point exceptions, but only installs the state of the floating-point status flags represented through its argument.

RETURN VALUE

If the representation was successfully stored, fegetenv() shall return zero. Otherwise, it shall return a non-zero value. If the environment was successfully established, fesetenv() shall return zero. Otherwise, it shall return a non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feholdexcept() , feupdateenv() , the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigpending(3p)

SIGPENDING

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigpending - examine pending signals

SYNOPSIS

#include <signal.h>

int sigpending(sigset_t *set);

DESCRIPTION

The sigpending() function shall store, in the location referenced by the set argument, the set of signals that are blocked from delivery to the calling thread and that are pending on the process or the calling thread.

RETURN VALUE

Upon successful completion, sigpending() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sigaddset() , sigdelset() , sigemptyset() , sigfillset() , sigismember() , sigprocmask() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mkfifo(3p)

MKFIFO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mkfifo - make a FIFO special file

SYNOPSIS

#include <sys/stat.h>

int mkfifo(const char *path, mode_t mode);

DESCRIPTION

The mkfifo() function shall create a new FIFO special file named by the pathname pointed to by path. The file permission bits of the new FIFO shall be initialized from mode. The file permission bits of the mode argument shall be modified by the process' file creation mask.

When bits in mode other than the file permission bits are set, the effect is implementation-defined.

If path names a symbolic link, mkfifo() shall fail and set errno to [EEXIST].

The FIFO's user ID shall be set to the process' effective user ID. The FIFO's group ID shall be set to the group ID of the parent directory or to the effective group ID of the process. Implementations shall provide a way to initialize the FIFO's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the FIFO's group ID to the effective group ID of the calling process.

Upon successful completion, mkfifo() shall mark for update the st_atime, st_ctime, and st_mtime fields of the file. Also, the st_ctime and st_mtime fields of the directory that contains the new entry shall be marked for update.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned, no FIFO shall be created, and errno shall be set to indicate the error.

ERRORS

The mkfifo() function shall fail if:

EACCES
A component of the path prefix denies search permission, or write permission is denied on the parent directory of the FIFO to be created.
EEXIST
The named file already exists.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of the path prefix specified by path does not name an existing directory or path is an empty string.
ENOSPC
The directory that would contain the new file cannot be extended or the file system is out of file-allocation resources.
ENOTDIR
A component of the path prefix is not a directory.
EROFS
The named file resides on a read-only file system.

The mkfifo() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Creating a FIFO File

The following example shows how to create a FIFO file named /home/cnd/mod_done, with read/write permissions for owner, and with read permissions for group and others.

#include <sys/types.h>
#include <sys/stat.h>

int status;
...
status = mkfifo("/home/cnd/mod_done", S_IWUSR | S_IRUSR |
    S_IRGRP | S_IROTH);

APPLICATION USAGE

None.

RATIONALE

The syntax of this function is intended to maintain compatibility with historical implementations of mknod(). The latter function was included in the 1984 /usr/group standard but only for use in creating FIFO special files. The mknod() function was originally excluded from the POSIX.1-1988 standard as implementation-defined and replaced by mkdir() and mkfifo(). The mknod() function is now included for alignment with the Single UNIX Specification.

The POSIX.1-1990 standard required that the group ID of a newly created FIFO be set to the group ID of its parent directory or to the effective group ID of the creating process. FIPS 151-2 required that implementations provide a way to have the group ID be set to the group ID of the containing directory, but did not prohibit implementations also supporting a way to set the group ID to the effective group ID of the creating process. Conforming applications should not assume which group ID will be used. If it matters, an application can use chown() to set the group ID after the FIFO is created, or determine under what conditions the implementation will set the desired group ID.

FUTURE DIRECTIONS

None.

SEE ALSO

umask() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutex_setprioceiling (3p)

 Continue to this page.


tcsetpgrp(3p)

TCSETPGRP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcsetpgrp - set the foreground process group ID

SYNOPSIS

#include <unistd.h>

int tcsetpgrp(int fildes, pid_t pgid_id);

DESCRIPTION

If the process has a controlling terminal, tcsetpgrp() shall set the foreground process group ID associated with the terminal to pgid_id. The application shall ensure that the file associated with fildes is the controlling terminal of the calling process and the controlling terminal is currently associated with the session of the calling process. The application shall ensure that the value of pgid_id matches a process group ID of a process in the same session as the calling process.

Attempts to use tcsetpgrp() from a process which is a member of a background process group on a fildes associated with its controlling terminal shall cause the process group to be sent a SIGTTOU signal. If the calling process is blocking or ignoring SIGTTOU signals, the process shall be allowed to perform the operation, and no signal is sent.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcsetpgrp() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINVAL
This implementation does not support the value in the pgid_id argument.
ENOTTY
The calling process does not have a controlling terminal, or the file is not the controlling terminal, or the controlling terminal is no longer associated with the session of the calling process.
EPERM
The value of pgid_id is a value supported by the implementation, but does not match the process group ID of a process in the same session as the calling process.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

tcgetpgrp() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


_tolower(3p)

_TOLOWER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

_tolower - transliterate uppercase characters to lowercase

SYNOPSIS

#include <ctype.h>

int _tolower(int c);

DESCRIPTION

The _tolower() macro shall be equivalent to tolower(c) except that the application shall ensure that the argument c is an uppercase letter.

RETURN VALUE

Upon successful completion, _tolower() shall return the lowercase letter corresponding to the argument passed.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

tolower() , isupper() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cacosf (3p)

 Continue to this page.


cacosh(3p)

CACOSH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cacosh, cacoshf, cacoshl - complex arc hyperbolic cosine functions

SYNOPSIS

#include <complex.h>

double complex cacosh(double complex z);
float complex cacoshf(float complex z);
long double complex cacoshl(long double complex z);

DESCRIPTION

These functions shall compute the complex arc hyperbolic cosine of z, with a branch cut at values less than 1 along the real axis.

RETURN VALUE

These functions shall return the complex arc hyperbolic cosine value, in the range of a half-strip of non-negative values along the real axis and in the interval [-ipi, +ipi] along the imaginary axis.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ccosh() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


system(3p)

SYSTEM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

system - issue a command

SYNOPSIS

#include <stdlib.h>

int system(const char *command);

DESCRIPTION

If command is a null pointer, the system() function shall determine whether the host environment has a command processor. If command is not a null pointer, the system() function shall pass the string pointed to by command to that command processor to be executed in an implementation-defined manner; this might then cause the program calling system() to behave in a non-conforming manner or to terminate.

The environment of the executed command shall be as if a child process were created using fork(), and the child process invoked the sh utility using execl() as follows:

execl(<shell path>, "sh", "-c", command, (char *)0);

where <shell path> is an unspecified pathname for the sh utility.

The system() function shall ignore the SIGINT and SIGQUIT signals, and shall block the SIGCHLD signal, while waiting for the command to terminate. If this might cause the application to miss a signal that would have killed it, then the application should examine the return value from system() and take whatever action is appropriate to the application if the command terminated due to receipt of a signal.

The system() function shall not affect the termination status of any child of the calling processes other than the process or processes it itself creates.

The system() function shall not return until the child process has terminated.

RETURN VALUE

If command is a null pointer, system() shall return non-zero to indicate that a command processor is available, or zero if none is available. The system() function shall always return non-zero when command is NULL.

If command is not a null pointer, system() shall return the termination status of the command language interpreter in the format specified by waitpid(). The termination status shall be as defined for the sh utility; otherwise, the termination status is unspecified. If some error prevents the command language interpreter from executing after the child process is created, the return value from system() shall be as if the command language interpreter had terminated using exit(127) or _exit(127). If a child process cannot be created, or if the termination status for the command language interpreter cannot be obtained, system() shall return -1 and set errno to indicate the error.

ERRORS

The system() function may set errno values as described by fork() .

In addition, system() may fail if:

ECHILD
The status of the child process created by system() is no longer available.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the return value of system() is not -1, its value can be decoded through the use of the macros described in <sys/wait.h>. For convenience, these macros are also provided in <stdlib.h>.

Note that, while system() must ignore SIGINT and SIGQUIT and block SIGCHLD while waiting for the child to terminate, the handling of signals in the executed command is as specified by fork() and exec. For example, if SIGINT is being caught or is set to SIG_DFL when system() is called, then the child is started with SIGINT handling set to SIG_DFL.

Ignoring SIGINT and SIGQUIT in the parent process prevents coordination problems (two processes reading from the same terminal, for example) when the executed command ignores or catches one of the signals. It is also usually the correct action when the user has given a command to the application to be executed synchronously (as in the '!' command in many interactive applications). In either case, the signal should be delivered only to the child process, not to the application itself. There is one situation where ignoring the signals might have less than the desired effect. This is when the application uses system() to perform some task invisible to the user. If the user typed the interrupt character ( "^C" , for example) while system() is being used in this way, one would expect the application to be killed, but only the executed command is killed. Applications that use system() in this way should carefully check the return status from system() to see if the executed command was successful, and should take appropriate action when the command fails.

Blocking SIGCHLD while waiting for the child to terminate prevents the application from catching the signal and obtaining status from system()'s child process before system() can get the status itself.

The context in which the utility is ultimately executed may differ from that in which system() was called. For example, file descriptors that have the FD_CLOEXEC flag set are closed, and the process ID and parent process ID are different. Also, if the executed utility changes its environment variables or its current working directory, that change is not reflected in the caller's context.

There is no defined way for an application to find the specific path for the shell. However, confstr() can provide a value for PATH that is guaranteed to find the sh utility.

RATIONALE

The system() function should not be used by programs that have set user (or group) ID privileges. The fork() and exec family of functions (except execlp() and execvp()), should be used instead. This prevents any unforeseen manipulation of the environment of the user that could cause execution of commands not anticipated by the calling program.

There are three levels of specification for the system() function. The ISO C standard gives the most basic. It requires that the function exists, and defines a way for an application to query whether a command language interpreter exists. It says nothing about the command language or the environment in which the command is interpreted.

IEEE Std 1003.1-2001 places additional restrictions on system(). It requires that if there is a command language interpreter, the environment must be as specified by fork() and exec. This ensures, for example, that close-on- exec works, that file locks are not inherited, and that the process ID is different. It also specifies the return value from system() when the command line can be run, thus giving the application some information about the command's completion status.

Finally, IEEE Std 1003.1-2001 requires the command to be interpreted as in the shell command language defined in the Shell and Utilities volume of IEEE Std 1003.1-2001.

Note that, system(NULL) is required to return non-zero, indicating that there is a command language interpreter. At first glance, this would seem to conflict with the ISO C standard which allows system(NULL) to return zero. There is no conflict, however. A system must have a command language interpreter, and is non-conforming if none is present. It is therefore permissible for the system() function on such a system to implement the behavior specified by the ISO C standard as long as it is understood that the implementation does not conform to IEEE Std 1003.1-2001 if system(NULL) returns zero.

It was explicitly decided that when command is NULL, system() should not be required to check to make sure that the command language interpreter actually exists with the correct mode, that there are enough processes to execute it, and so on. The call system(NULL) could, theoretically, check for such problems as too many existing child processes, and return zero. However, it would be inappropriate to return zero due to such a (presumably) transient condition. If some condition exists that is not under the control of this application and that would cause any system() call to fail, that system has been rendered non-conforming.

Early drafts required, or allowed, system() to return with errno set to [EINTR] if it was interrupted with a signal. This error return was removed, and a requirement that system() not return until the child has terminated was added. This means that if a waitpid() call in system() exits with errno set to [EINTR], system() must reissue the waitpid(). This change was made for two reasons:

1.
There is no way for an application to clean up if system() returns [EINTR], short of calling wait(), and that could have the undesirable effect of returning the status of children other than the one started by system().

2.
While it might require a change in some historical implementations, those implementations already have to be changed because they use wait() instead of waitpid().

Note that if the application is catching SIGCHLD signals, it will receive such a signal before a successful system() call returns.

To conform to IEEE Std 1003.1-2001, system() must use waitpid(), or some similar function, instead of wait().

The following code sample illustrates how system() might be implemented on an implementation conforming to IEEE Std 1003.1-2001.

#include <signal.h>
int system(const char *cmd)
{
    int stat;
    pid_t pid;
    struct sigaction sa, savintr, savequit;
    sigset_t saveblock;
    if (cmd == NULL)
        return(1);
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigemptyset(&savintr.sa_mask);
    sigemptyset(&savequit.sa_mask);
    sigaction(SIGINT, &sa, &savintr);
    sigaction(SIGQUIT, &sa, &savequit);
    sigaddset(&sa.sa_mask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &sa.sa_mask, &saveblock);
    if ((pid = fork()) == 0) {
        sigaction(SIGINT, &savintr, (struct sigaction *)0);
        sigaction(SIGQUIT, &savequit, (struct sigaction *)0);
        sigprocmask(SIG_SETMASK, &saveblock, (sigset_t *)0);
        execl("/bin/sh", "sh", "-c", cmd, (char *)0);
        _exit(127);
    }
    if (pid == -1) {
        stat = -1; /* errno comes from fork() */
    } else {
        while (waitpid(pid, &stat, 0) == -1) {
            if (errno != EINTR){
                stat = -1;
                break;
            }
        }
    }
    sigaction(SIGINT, &savintr, (struct sigaction *)0);
    sigaction(SIGQUIT, &savequit, (struct sigaction *)0);
    sigprocmask(SIG_SETMASK, &saveblock, (sigset_t *)0);
    return(stat);
}

Note that, while a particular implementation of system() (such as the one above) can assume a particular path for the shell, such a path is not necessarily valid on another system. The above example is not portable, and is not intended to be.

One reviewer suggested that an implementation of system() might want to use an environment variable such as SHELL to determine which command interpreter to use. The supposed implementation would use the default command interpreter if the one specified by the environment variable was not available. This would allow a user, when using an application that prompts for command lines to be processed using system(), to specify a different command interpreter. Such an implementation is discouraged. If the alternate command interpreter did not follow the command line syntax specified in the Shell and Utilities volume of IEEE Std 1003.1-2001, then changing SHELL would render system() non-conforming. This would affect applications that expected the specified behavior from system(), and since the Shell and Utilities volume of IEEE Std 1003.1-2001 does not mention that SHELL affects system(), the application would not know that it needed to unset SHELL .

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , pipe() , waitpid() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <signal.h>, <stdlib.h>, <sys/wait.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, sh

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cacosl (3p)

 Continue to this page.


getenv(3p)

GETENV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getenv - get value of an environment variable

SYNOPSIS

#include <stdlib.h>

char *getenv(const char *name);

DESCRIPTION

The getenv() function shall search the environment of the calling process (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables) for the environment variable name if it exists and return a pointer to the value of the environment variable. If the specified environment variable cannot be found, a null pointer shall be returned. The application shall ensure that it does not modify the string pointed to by the getenv() function.

The string pointed to may be overwritten by a subsequent call to getenv(), setenv(), or unsetenv(), but shall not be overwritten by a call to any other function in this volume of IEEE Std 1003.1-2001.

If the application modifies environ or the pointers to which it points, the behavior of getenv() is undefined.

The getenv() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, getenv() shall return a pointer to a string containing the value for the specified name. If the specified name cannot be found in the environment of the calling process, a null pointer shall be returned.

The return value from getenv() may point to static data which may be overwritten by subsequent calls to getenv(), setenv(), or unsetenv().

On XSI-conformant systems, the return value from getenv() may point to static data which may also be overwritten by subsequent calls to putenv().

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Getting the Value of an Environment Variable

The following example gets the value of the HOME environment variable.

#include <stdlib.h>
...
const char *name = "HOME";
char *value;

value = getenv(name);

APPLICATION USAGE

None.

RATIONALE

The clearenv() function was considered but rejected. The putenv() function has now been included for alignment with the Single UNIX Specification.

The getenv() function is inherently not reentrant because it returns a value pointing to static data.

Conforming applications are required not to modify environ directly, but to use only the functions described here to manipulate the process environment as an abstract object. Thus, the implementation of the environment access functions has complete control over the data structure used to represent the environment (subject to the requirement that environ be maintained as a list of strings with embedded equal signs for applications that wish to scan the environment). This constraint allows the implementation to properly manage the memory it allocates, either by using allocated storage for all variables (copying them on the first invocation of setenv() or unsetenv()), or keeping track of which strings are currently in allocated space and which are not, via a separate table or some other means. This enables the implementation to free any allocated space used by strings (and perhaps the pointers to them) stored in environ when unsetenv() is called. A C runtime start-up procedure (that which invokes main() and perhaps initializes environ) can also initialize a flag indicating that none of the environment has yet been copied to allocated storage, or that the separate table has not yet been initialized.

In fact, for higher performance of getenv(), the implementation could also maintain a separate copy of the environment in a data structure that could be searched much more quickly (such as an indexed hash table, or a binary tree), and update both it and the linear list at environ when setenv() or unsetenv() is invoked.

Performance of getenv() can be important for applications which have large numbers of environment variables. Typically, applications like this use the environment as a resource database of user-configurable parameters. The fact that these variables are in the user's shell environment usually means that any other program that uses environment variables (such as ls, which attempts to use COLUMNS ), or really almost any utility ( LANG , LC_ALL , and so on) is similarly slowed down by the linear search through the variables.

An implementation that maintains separate data structures, or even one that manages the memory it consumes, is not currently required as it was thought it would reduce consensus among implementors who do not want to change their historical implementations.

The POSIX Threads Extension states that multi-threaded applications must not modify environ directly, and that IEEE Std 1003.1-2001 is providing functions which such applications can use in the future to manipulate the environment in a thread-safe manner. Thus, moving away from application use of environ is desirable from that standpoint as well.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , putenv() , setenv() , unsetenv() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fgetpos(3p)

FGETPOS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fgetpos - get current file position information

SYNOPSIS

#include <stdio.h>

int fgetpos(FILE *restrict stream, fpos_t *restrict pos);

DESCRIPTION

The fgetpos() function shall store the current values of the parse state (if any) and file position indicator for the stream pointed to by stream in the object pointed to by pos. The value stored contains unspecified information usable by fsetpos() for repositioning the stream to its position at the time of the call to fgetpos().

RETURN VALUE

Upon successful completion, fgetpos() shall return 0; otherwise, it shall return a non-zero value and set errno to indicate the error.

ERRORS

The fgetpos() function shall fail if:

EOVERFLOW
The current value of the file position cannot be represented correctly in an object of type fpos_t.

The fgetpos() function may fail if:

EBADF
The file descriptor underlying stream is not valid.
ESPIPE
The file descriptor underlying stream is associated with a pipe, FIFO, or socket.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , ftell() , rewind() , ungetc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcscoll(3p)

WCSCOLL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcscoll - wide-character string comparison using collating information

SYNOPSIS

#include <wchar.h>

int wcscoll(const wchar_t *ws1, const wchar_t *ws2);

DESCRIPTION

The wcscoll() function shall compare the wide-character string pointed to by ws1 to the wide-character string pointed to by ws2, both interpreted as appropriate to the LC_COLLATE category of the current locale.

The wcscoll() function shall not change the setting of errno if successful.

An application wishing to check for error situations should set errno to 0 before calling wcscoll(). If errno is non-zero on return, an error has occurred.

RETURN VALUE

Upon successful completion, wcscoll() shall return an integer greater than, equal to, or less than 0, according to whether the wide-character string pointed to by ws1 is greater than, equal to, or less than the wide-character string pointed to by ws2, when both are interpreted as appropriate to the current locale. On error, wcscoll() shall set errno, but no return value is reserved to indicate an error.

ERRORS

The wcscoll() function may fail if:

EINVAL
The ws1 or ws2 arguments contain wide-character codes outside the domain of the collating sequence.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The wcsxfrm() and wcscmp() functions should be used for sorting large lists.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcscmp() , wcsxfrm() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getpeername(3p)

GETPEERNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getpeername - get the name of the peer socket

SYNOPSIS

#include <sys/socket.h>

int getpeername(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);

DESCRIPTION

The getpeername() function shall retrieve the peer address of the specified socket, store this address in the sockaddr structure pointed to by the address argument, and store the length of this address in the object pointed to by the address_len argument.

If the actual length of the address is greater than the length of the supplied sockaddr structure, the stored address shall be truncated.

If the protocol permits connections by unbound clients, and the peer is not bound, then the value stored in the object pointed to by address is unspecified.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The getpeername() function shall fail if:

EBADF
The socket argument is not a valid file descriptor.
EINVAL
The socket has been shut down.
ENOTCONN
The socket is not connected or otherwise has not had the peer pre-specified.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The operation is not supported for the socket protocol.

The getpeername() function may fail if:

ENOBUFS
Insufficient resources were available in the system to complete the call.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

accept() , bind() , getsockname() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tzset(3p)

TZSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

daylight, timezone, tzname, tzset - set timezone conversion information

SYNOPSIS

#include <time.h>

extern int daylight;
extern long timezone;

extern char *tzname[2];
void tzset(void);

DESCRIPTION

The tzset() function shall use the value of the environment variable TZ to set time conversion information used by ctime() , localtime() , mktime() , and strftime() . If TZ is absent from the environment, implementation-defined default timezone information shall be used.

The tzset() function shall set the external variable tzname as follows:

tzname[0] = "std";
tzname[1] = "dst";

where std and dst are as described in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.

The tzset() function also shall set the external variable daylight to 0 if Daylight Savings Time conversions should never be applied for the timezone in use; otherwise, non-zero. The external variable timezone shall be set to the difference, in seconds, between Coordinated Universal Time (UTC) and local standard time.

RETURN VALUE

The tzset() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Example TZ variables and their timezone differences are given in the table below:
TZ | timezone
EST5EDT | 5*60*60
GMT0 | 0*60*60
JST-9 | -9*60*60
MET-1MEST | -1*60*60
MST7MDT | 7*60*60
PST8PDT | 8*60*60

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ctime() , localtime() , mktime() , strftime() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ttyname(3p)

TTYNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ttyname, ttyname_r - find the pathname of a terminal

SYNOPSIS

#include <unistd.h>

char *ttyname(int fildes);

int ttyname_r(int fildes, char *name, size_t namesize);

DESCRIPTION

The ttyname() function shall return a pointer to a string containing a null-terminated pathname of the terminal associated with file descriptor fildes. The return value may point to static data whose content is overwritten by each call.

The ttyname() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The ttyname_r() function shall store the null-terminated pathname of the terminal associated with the file descriptor fildes in the character array referenced by name. The array is namesize characters long and should have space for the name and the terminating null character. The maximum length of the terminal name shall be {TTY_NAME_MAX}.

RETURN VALUE

Upon successful completion, ttyname() shall return a pointer to a string. Otherwise, a null pointer shall be returned and errno set to indicate the error.

If successful, the ttyname_r() function shall return zero. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The ttyname() function may fail if:

EBADF
The fildes argument is not a valid file descriptor.
ENOTTY
The fildes argument does not refer to a terminal.

The ttyname_r() function may fail if:

EBADF
The fildes argument is not a valid file descriptor.
ENOTTY
The fildes argument does not refer to a terminal.
ERANGE
The value of namesize is smaller than the length of the string to be returned including the terminating null character.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The term ``terminal'' is used instead of the historical term ``terminal device'' in order to avoid a reference to an undefined term.

The thread-safe version places the terminal name in a user-supplied buffer and returns a non-zero value if it fails. The non-thread-safe version may return the name in a static data area that may be overwritten by each call.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dbm_store (3p)

 Continue to this page.


dbm_fetch (3p)

 Continue to this page.


sched_rr_get_interval(3p)

SCHED_RR_GET_INTERVAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched_rr_get_interval - get execution time limits (REALTIME)

SYNOPSIS

#include <sched.h>

int sched_rr_get_interval(pid_t pid, struct timespec *interval);

DESCRIPTION

The sched_rr_get_interval() function shall update the timespec structure referenced by the interval argument to contain the current execution time limit (that is, time quantum) for the process specified by pid. If pid is zero, the current execution time limit for the calling process shall be returned.

RETURN VALUE

If successful, the sched_rr_get_interval() function shall return zero. Otherwise, it shall return a value of -1 and set errno to indicate the error.

ERRORS

The sched_rr_get_interval() function shall fail if:

ESRCH
No process can be found corresponding to that specified by pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sched_getparam() , sched_get_priority_max() , sched_getscheduler() , sched_setparam() , sched_setscheduler() , the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tgamma(3p)

TGAMMA

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tgamma, tgammaf, tgammal - compute gamma() function

SYNOPSIS

#include <math.h>

double tgamma(double x);
float tgammaf(float x);
long double tgammal(long double x);

DESCRIPTION

These functions shall compute the gamma() function of x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return Gamma( x).

If x is a negative integer, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If the correct value would cause overflow, a range error shall occur and tgamma(), tgammaf(), and tgammal() shall return ±HUGE_VAL, ±HUGE_VALF, or ±HUGE_VALL, respectively, with the same sign as the correct value of the function.

If x is NaN, a NaN shall be returned.

If x is +Inf, x shall be returned.

If x is ±0, a pole error shall occur, and tgamma(), tgammaf(), and tgammal() shall return ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL, respectively.

If x is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The value of x is a negative integer, or x is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Pole Error
The value of x is zero.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

Range Error
The value overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

For IEEE Std 754-1985 double, overflow happens when 0 < x < 1/DBL_MAX, and 171.7 < x.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

This function is named tgamma() in order to avoid conflicts with the historical gamma() and lgamma() functions.

FUTURE DIRECTIONS

It is possible that the error response for a negative integer argument may be changed to a pole error and a return value of ±Inf.

SEE ALSO

feclearexcept() , fetestexcept() , lgamma() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


floorf (3p)

 Continue to this page.


_setjmp(3p)

_LONGJMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

_longjmp, _setjmp - non-local goto

SYNOPSIS

#include <setjmp.h>

void _longjmp(jmp_buf env, int val);
int _setjmp(jmp_buf env);

DESCRIPTION

The _longjmp() and _setjmp() functions shall be equivalent to longjmp() and setjmp(), respectively, with the additional restriction that _longjmp() and _setjmp() shall not manipulate the signal mask.

If _longjmp() is called even though env was never initialized by a call to _setjmp(), or when the last such call was in a function that has since returned, the results are undefined.

RETURN VALUE

Refer to longjmp() and setjmp() .

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If _longjmp() is executed and the environment in which _setjmp() was executed no longer exists, errors can occur. The conditions under which the environment of the _setjmp() no longer exists include exiting the function that contains the _setjmp() call, and exiting an inner block with temporary storage. This condition might not be detectable, in which case the _longjmp() occurs and, if the environment no longer exists, the contents of the temporary storage of an inner block are unpredictable. This condition might also cause unexpected process termination. If the function has returned, the results are undefined.

Passing longjmp() a pointer to a buffer not created by setjmp(), passing _longjmp() a pointer to a buffer not created by _setjmp(), passing siglongjmp() a pointer to a buffer not created by sigsetjmp(), or passing any of these three functions a buffer that has been modified by the user can cause all the problems listed above, and more.

The _longjmp() and _setjmp() functions are included to support programs written to historical system interfaces. New applications should use siglongjmp() and sigsetjmp() respectively.

RATIONALE

None.

FUTURE DIRECTIONS

The _longjmp() and _setjmp() functions may be marked LEGACY in a future version.

SEE ALSO

longjmp() , setjmp() , siglongjmp() , sigsetjmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <setjmp.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


floorl (3p)

 Continue to this page.


sqrt(3p)

SQRT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sqrt, sqrtf, sqrtl - square root function

SYNOPSIS

#include <math.h>

double sqrt(double x);
float sqrtf(float x);
long double sqrtl(long double x);

DESCRIPTION

These functions shall compute the square root of their argument x, sqrt(x).

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the square root of x.

For finite values of x < -0, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0 or +Inf, x shall be returned.

If x is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The finite value of x is < -0, or x is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

Taking the Square Root of 9.0

#include <math.h>
...
double x = 9.0;
double result;
...
result = sqrt(x);

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


srand (3p)

 Continue to this page.


gethostid(3p)

GETHOSTID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gethostid - get an identifier for the current host

SYNOPSIS

#include <unistd.h>

long gethostid(void);

DESCRIPTION

The gethostid() function shall retrieve a 32-bit identifier for the current host.

RETURN VALUE

Upon successful completion, gethostid() shall return an identifier for the current host.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

This volume of IEEE Std 1003.1-2001 does not define the domain in which the return value is unique.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

random() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vfwscanf (3p)

 Continue to this page.


posix_spawnattr_getschedpolicy(3p)

POSIX_SPAWNATTR_GETSCHEDPOLICY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawnattr_getschedpolicy, posix_spawnattr_setschedpolicy - get and set the spawn-schedpolicy attribute of a spawn attributes object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>
#include <sched.h>

int posix_spawnattr_getschedpolicy(const posix_spawnattr_t *
restrict attr, int *restrict schedpolicy);
int posix_spawnattr_setschedpolicy(posix_spawnattr_t *attr,
int schedpolicy);

DESCRIPTION

The posix_spawnattr_getschedpolicy() function shall obtain the value of the spawn-schedpolicy attribute from the attributes object referenced by attr.

The posix_spawnattr_setschedpolicy() function shall set the spawn-schedpolicy attribute in an initialized attributes object referenced by attr.

The spawn-schedpolicy attribute represents the scheduling policy to be assigned to the new process image in a spawn operation (if POSIX_SPAWN_SETSCHEDULER is set in the spawn-flags attribute). The default value of this attribute is unspecified.

RETURN VALUE

Upon successful completion, posix_spawnattr_getschedpolicy() shall return zero and store the value of the spawn-schedpolicy attribute of attr into the object referenced by the schedpolicy parameter; otherwise, an error number shall be returned to indicate the error.

Upon successful completion, posix_spawnattr_setschedpolicy() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The posix_spawnattr_setschedpolicy() function may fail if:

EINVAL
The value of the attribute being set is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn and Process Scheduling options and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnattr_destroy() , posix_spawnattr_init()
, posix_spawnattr_getsigdefault() , posix_spawnattr_getflags()
, posix_spawnattr_getpgroup() , posix_spawnattr_getschedparam()
, posix_spawnattr_getsigmask() , posix_spawnattr_setsigdefault()
, posix_spawnattr_setflags() , posix_spawnattr_setpgroup()
, posix_spawnattr_setschedparam() , posix_spawnattr_setsigmask()
, posix_spawnp() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>,
<spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pause(3p)

PAUSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pause - suspend the thread until a signal is received

SYNOPSIS

#include <unistd.h>

int pause(void);

DESCRIPTION

The pause() function shall suspend the calling thread until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process.

If the action is to terminate the process, pause() shall not return.

If the action is to execute a signal-catching function, pause() shall return after the signal-catching function returns.

RETURN VALUE

Since pause() suspends thread execution indefinitely unless interrupted by a signal, there is no successful completion return value. A value of -1 shall be returned and errno set to indicate the error.

ERRORS

The pause() function shall fail if:

EINTR
A signal is caught by the calling process and control is returned from the signal-catching function.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Many common uses of pause() have timing windows. The scenario involves checking a condition related to a signal and, if the signal has not occurred, calling pause(). When the signal occurs between the check and the call to pause(), the process often blocks indefinitely. The sigprocmask() and sigsuspend() functions can be used to avoid this type of problem.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sockatmark(3p)

SOCKATMARK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sockatmark - determine whether a socket is at the out-of-band mark

SYNOPSIS

#include <sys/socket.h>

int sockatmark(int s);

DESCRIPTION

The sockatmark() function shall determine whether the socket specified by the descriptor s is at the out-of-band data mark (see the System Interfaces volume of IEEE Std 1003.1-2001, Section 2.10.12, Socket Out-of-Band State). If the protocol for the socket supports out-of-band data by marking the stream with an out-of-band data mark, the sockatmark() function shall return 1 when all data preceding the mark has been read and the out-of-band data mark is the first element in the receive queue. The sockatmark() function shall not remove the mark from the stream.

RETURN VALUE

Upon successful completion, the sockatmark() function shall return a value indicating whether the socket is at an out-of-band data mark. If the protocol has marked the data stream and all data preceding the mark has been read, the return value shall be 1; if there is no mark, or if data precedes the mark in the receive queue, the sockatmark() function shall return 0. Otherwise, it shall return a value of -1 and set errno to indicate the error.

ERRORS

The sockatmark() function shall fail if:

EBADF
The s argument is not a valid file descriptor.
ENOTTY
The s argument does not specify a descriptor for a socket.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The use of this function between receive operations allows an application to determine which received data precedes the out-of-band data and which follows the out-of-band data.

There is an inherent race condition in the use of this function. On an empty receive queue, the current read of the location might well be at the "mark", but the system has no way of knowing that the next data segment that will arrive from the network will carry the mark, and sockatmark() will return false, and the next read operation will silently consume the mark.

Hence, this function can only be used reliably when the application already knows that the out-of-band data has been seen by the system or that it is known that there is data waiting to be read at the socket (via SIGURG or select()). See Socket Receive Queue , Socket Out-of-Band Data State , Signals , and pselect() for details.

RATIONALE

The sockatmark() function replaces the historical SIOCATMARK command to ioctl() which implemented the same functionality on many implementations. Using a wrapper function follows the adopted conventions to avoid specifying commands to the ioctl() function, other than those now included to support XSI STREAMS. The sockatmark() function could be implemented as follows:

#include <sys/ioctl.h>

int sockatmark(int s)
{
    int val;
    if (ioctl(s,SIOCATMARK,&val)==-1)
        return(-1);
    return(val);
}

The use of [ENOTTY] to indicate an incorrect descriptor type matches the historical behavior of SIOCATMARK.

FUTURE DIRECTIONS

None.

SEE ALSO

pselect() , recv() , recvmsg() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getgid(3p)

GETGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getgid - get the real group ID

SYNOPSIS

#include <unistd.h>

gid_t getgid(void);

DESCRIPTION

The getgid() function shall return the real group ID of the calling process.

RETURN VALUE

The getgid() function shall always be successful and no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getegid() , geteuid() , getuid() , setegid() , seteuid() , setgid() , setregid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


abs(3p)

ABS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

abs - return an integer absolute value

SYNOPSIS

#include <stdlib.h>

int abs(int i);

DESCRIPTION

The abs() function shall compute the absolute value of its integer operand, i. If the result cannot be represented, the behavior is undefined.

RETURN VALUE

The abs() function shall return the absolute value of its integer operand.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

In two's-complement representation, the absolute value of the negative integer with largest magnitude {INT_MIN} might not be representable.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fabs() , labs() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lgammaf (3p)

 Continue to this page.


lgammal (3p)

 Continue to this page.


fnmatch(3p)

FNMATCH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fnmatch - match a filename or a pathname

SYNOPSIS

#include <fnmatch.h>

int fnmatch(const char *pattern, const char *string, int flags);

DESCRIPTION

The fnmatch() function shall match patterns as described in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13.1, Patterns Matching a Single Character, and Section 2.13.2, Patterns Matching Multiple Characters. It checks the string specified by the string argument to see if it matches the pattern specified by the pattern argument.

The flags argument shall modify the interpretation of pattern and string. It is the bitwise-inclusive OR of zero or more of the flags defined in <fnmatch.h>. If the FNM_PATHNAME flag is set in flags, then a slash character ( '/' ) in string shall be explicitly matched by a slash in pattern; it shall not be matched by either the asterisk or question-mark special characters, nor by a bracket expression. If the FNM_PATHNAME flag is not set, the slash character shall be treated as an ordinary character.

If FNM_NOESCAPE is not set in flags, a backslash character ( '\' ) in pattern followed by any other character shall match that second character in string. In particular, "\\" shall match a backslash in string. If FNM_NOESCAPE is set, a backslash character shall be treated as an ordinary character.

If FNM_PERIOD is set in flags, then a leading period ( '.' ) in string shall match a period in pattern; as described by rule 2 in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13.3, Patterns Used for Filename Expansion where the location of "leading" is indicated by the value of FNM_PATHNAME:

*
If FNM_PATHNAME is set, a period is "leading" if it is the first character in string or if it immediately follows a slash.

*
If FNM_PATHNAME is not set, a period is "leading" only if it is the first character of string.

If FNM_PERIOD is not set, then no special restrictions are placed on matching a period.

RETURN VALUE

If string matches the pattern specified by pattern, then fnmatch() shall return 0. If there is no match, fnmatch() shall return FNM_NOMATCH, which is defined in <fnmatch.h>. If an error occurs, fnmatch() shall return another non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The fnmatch() function has two major uses. It could be used by an application or utility that needs to read a directory and apply a pattern against each entry. The find utility is an example of this. It can also be used by the pax utility to process its pattern operands, or by applications that need to match strings in a similar manner.

The name fnmatch() is intended to imply filename match, rather than pathname match. The default action of this function is to match filenames, rather than pathnames, since it gives no special significance to the slash character. With the FNM_PATHNAME flag, fnmatch() does match pathnames, but without tilde expansion, parameter expansion, or special treatment for a period at the beginning of a filename.

RATIONALE

This function replaced the REG_FILENAME flag of regcomp() in early proposals of this volume of IEEE Std 1003.1-2001. It provides virtually the same functionality as the regcomp() and regexec() functions using the REG_FILENAME and REG_FSLASH flags (the REG_FSLASH flag was proposed for regcomp(), and would have had the opposite effect from FNM_PATHNAME), but with a simpler function and less system overhead.

FUTURE DIRECTIONS

None.

SEE ALSO

glob() , wordexp() , the Base Definitions volume of IEEE Std 1003.1-2001, <fnmatch.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


basename(3p)

BASENAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

basename - return the last component of a pathname

SYNOPSIS

#include <libgen.h>

char *basename(char *path);

DESCRIPTION

The basename() function shall take the pathname pointed to by path and return a pointer to the final component of the pathname, deleting any trailing '/' characters.

If the string consists entirely of the '/' character, basename() shall return a pointer to the string "/" . If the string is exactly "//" , it is implementation-defined whether '/' or "//" is returned.

If path is a null pointer or points to an empty string, basename() shall return a pointer to the string "." .

The basename() function may modify the string pointed to by path, and may return a pointer to static storage that may then be overwritten by a subsequent call to basename().

The basename() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The basename() function shall return a pointer to the final component of path.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Using basename()

The following program fragment returns a pointer to the value lib, which is the base name of /usr/lib.

#include <libgen.h>
...
char *name = "/usr/lib";
char *base;

base = basename(name);
...

Sample Input and Output Strings for basename()

In the following table, the input string is the value pointed to by path, and the output string is the return value of the basename() function.
Input String | Output String
"/usr/lib" | "lib"
"/usr/" | "usr"
"/" | "/"
"///" | "/"
"//usr//lib//" | "lib"

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

dirname() , the Base Definitions volume of IEEE Std 1003.1-2001, <libgen.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, basename

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswctype(3p)

ISWCTYPE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswctype - test character for a specified class

SYNOPSIS

#include <wctype.h>

int iswctype(wint_t wc, wctype_t charclass);

DESCRIPTION

The iswctype() function shall determine whether the wide-character code wc has the character class charclass, returning true or false. The iswctype() function is defined on WEOF and wide-character codes corresponding to the valid character encodings in the current locale. If the wc argument is not in the domain of the function, the result is undefined. If the value of charclass is invalid (that is, not obtained by a call to wctype() or charclass is invalidated by a subsequent call to setlocale() that has affected category LC_CTYPE ) the result is unspecified.

RETURN VALUE

The iswctype() function shall return non-zero (true) if and only if wc has the property described by charclass. If charclass is 0, iswctype() shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Testing for a Valid Character

#include <wctype.h>
...
int yes_or_no;
wint_t wc;
wctype_t valid_class;
...
if ((valid_class=wctype("vowel")) == (wctype_t)0)
    /* Invalid character class. */
yes_or_no=iswctype(wc,valid_class);

APPLICATION USAGE

The twelve strings "alnum" , "alpha" , "blank" , "cntrl" , "digit" , "graph" , "lower" , "print" , "punct" , "space" , "upper" , and "xdigit" are reserved for the standard character classes. In the table below, the functions in the left column are equivalent to the functions in the right column.

iswalnum(wc)    iswctype(wc, wctype("alnum"))
iswalpha(wc)    iswctype(wc, wctype("alpha"))
iswblank(wc)    iswctype(wc, wctype("blank"))
iswcntrl(wc)    iswctype(wc, wctype("cntrl"))
iswdigit(wc)    iswctype(wc, wctype("digit"))
iswgraph(wc)    iswctype(wc, wctype("graph"))
iswlower(wc)    iswctype(wc, wctype("lower"))
iswprint(wc)    iswctype(wc, wctype("print"))
iswpunct(wc)    iswctype(wc, wctype("punct"))
iswspace(wc)    iswctype(wc, wctype("space"))
iswupper(wc)    iswctype(wc, wctype("upper"))
iswxdigit(wc)   iswctype(wc, wctype("xdigit"))

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , wctype() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setpwent (3p)

 Continue to this page.


wcsrchr(3p)

WCSRCHR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsrchr - wide-character string scanning operation

SYNOPSIS

#include <wchar.h>

wchar_t *wcsrchr(const wchar_t *ws, wchar_t wc);

DESCRIPTION

The wcsrchr() function shall locate the last occurrence of wc in the wide-character string pointed to by ws. The application shall ensure that the value of wc is a character representable as a type wchar_t and a wide-character code corresponding to a valid character in the current locale. The terminating null wide-character code shall be considered to be part of the wide-character string.

RETURN VALUE

Upon successful completion, wcsrchr() shall return a pointer to the wide-character code or a null pointer if wc does not occur in the wide-character string.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcschr() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


abort(3p)

ABORT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

abort - generate an abnormal process abort

SYNOPSIS

#include <stdlib.h>

void abort(void);

DESCRIPTION

The abort() function shall cause abnormal process termination to occur, unless the signal SIGABRT is being caught and the signal handler does not return.

The abnormal termination processing shall include the default actions defined for SIGABRT and may include an attempt to effect fclose() on all open streams.

The SIGABRT signal shall be sent to the calling process as if by means of raise() with the argument SIGABRT.

The status made available to wait() or waitpid() by abort() shall be that of a process terminated by the SIGABRT signal. The abort() function shall override blocking or ignoring the SIGABRT signal.

RETURN VALUE

The abort() function shall not return.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Catching the signal is intended to provide the application writer with a portable means to abort processing, free from possible interference from any implementation-defined functions.

RATIONALE

The ISO/IEC 9899:1999 standard requires the abort() function to be async-signal-safe. Since IEEE Std 1003.1-2001 defers to the ISO C standard, this required a change to the DESCRIPTION from ``shall include the effect of fclose()'' to ``may include an attempt to effect fclose().''

The revised wording permits some backwards-compatibility and avoids a potential deadlock situation.

The Open Group Base Resolution bwg2002-003 is applied, removing the following XSI shaded paragraph from the DESCRIPTION:

``On XSI-conformant systems, in addition the abnormal termination processing shall include the effect of fclose() on message catalog descriptors.''

There were several reasons to remove this paragraph:

*
No special processing of open message catalogs needs to be performed prior to abnormal process termination.

*
The main reason to specifically mention that abort() includes the effect of fclose() on open streams is to flush output queued on the stream. Message catalogs in this context are read-only and, therefore, do not need to be flushed.

*
The effect of fclose() on a message catalog descriptor is unspecified. Message catalog descriptors are allowed, but not required to be implemented using a file descriptor, but there is no mention in IEEE Std 1003.1-2001 of a message catalog descriptor using a standard I/O stream FILE object as would be expected by fclose().

FUTURE DIRECTIONS

None.

SEE ALSO

exit() , kill() , raise() , signal() , wait() , waitpid() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getpwnam_r (3p)

 Continue to this page.


pthread_attr_setdetachstate (3p)

 Continue to this page.


regexec (3p)

 Continue to this page.


cimagf (3p)

 Continue to this page.


vwscanf(3p)

VFWSCANF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

vfwscanf, vswscanf, vwscanf - wide-character formatted input of a stdarg argument list

SYNOPSIS

#include <stdarg.h>
#include <stdio.h>
#include <wchar.h>

int vfwscanf(FILE *restrict stream, const wchar_t *restrict format,
va_list arg);
int vswscanf(const wchar_t *restrict ws, const wchar_t *restrict format,
va_list arg);
int vwscanf(const wchar_t *restrict format, va_list arg);

DESCRIPTION

The vfwscanf(), vswscanf(), and vwscanf() functions shall be equivalent to the fwscanf(), swscanf(), and wscanf() functions, respectively, except that instead of being called with a variable number of arguments, they are called with an argument list as defined in the <stdarg.h> header. These functions shall not invoke the va_end macro. As these functions invoke the va_arg macro, the value of ap after the return is unspecified.

RETURN VALUE

Refer to fwscanf() .

ERRORS

Refer to fwscanf() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions should call va_end( ap) afterwards to clean up.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fwscanf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdarg.h>, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stat(3p)

STAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stat - get file status

SYNOPSIS

#include <sys/stat.h>

int stat(const char *restrict path, struct stat *restrict buf);

DESCRIPTION

The stat() function shall obtain information about the named file and write it to the area pointed to by the buf argument. The path argument points to a pathname naming a file. Read, write, or execute permission of the named file is not required. An implementation that provides additional or alternate file access control mechanisms may, under implementation-defined conditions, cause stat() to fail. In particular, the system may deny the existence of the file specified by path.

If the named file is a symbolic link, the stat() function shall continue pathname resolution using the contents of the symbolic link, and shall return information pertaining to the resulting file if the file exists.

The buf argument is a pointer to a stat structure, as defined in the <sys/stat.h> header, into which information is placed concerning the file.

The stat() function shall update any time-related fields (as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.7, File Times Update), before writing into the stat structure.

Unless otherwise specified, the structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime shall have meaningful values for all file types defined in this volume of IEEE Std 1003.1-2001. The value of the member st_nlink shall be set to the number of links to the file.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The stat() function shall fail if:

EACCES
Search permission is denied for a component of the path prefix.
EIO
An error occurred while reading from the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
EOVERFLOW
The file size in bytes or the number of blocks allocated to the file or the file serial number cannot be represented correctly in the structure pointed to by buf.

The stat() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
EOVERFLOW
A value to be stored would overflow one of the members of the stat structure.

The following sections are informative.

EXAMPLES

Obtaining File Status Information

The following example shows how to obtain file status information for a file named /home/cnd/mod1. The structure variable buffer is defined for the stat structure.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

struct stat buffer;
int         status;
...
status = stat("/home/cnd/mod1", &buffer);

Getting Directory Information

The following example fragment gets status information for each entry in a directory. The call to the stat() function stores file information in the stat structure pointed to by statbuf. The lines that follow the stat() call format the fields in the stat structure for presentation to the user of the program.

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <locale.h>
#include <langinfo.h>
#include <stdio.h>
#include <stdint.h>

struct dirent  *dp;
struct stat     statbuf;
struct passwd  *pwd;
struct group   *grp;
struct tm      *tm;
char            datestring[256];
...
/* Loop through directory entries. */
while ((dp = readdir(dir)) != NULL) {

    /* Get entry's information. */
    if (stat(dp->d_name, &statbuf) == -1)
        continue;

    /* Print out type, permissions, and number of links. */
    printf("%10.10s", sperm (statbuf.st_mode));
    printf("%4d", statbuf.st_nlink);

    /* Print out owner's name if it is found using getpwuid(). */
    if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
        printf(" %-8.8s", pwd->pw_name);
    else
        printf(" %-8d", statbuf.st_uid);

    /* Print out group name if it is found using getgrgid(). */
    if ((grp = getgrgid(statbuf.st_gid)) != NULL)
        printf(" %-8.8s", grp->gr_name);
    else
        printf(" %-8d", statbuf.st_gid);

    /* Print size of file. */
    printf(" %9jd", (intmax_t)statbuf.st_size);

    tm = localtime(&statbuf.st_mtime);

    /* Get localized date string. */
    strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm);

    printf(" %s %s\n", datestring, dp->d_name);
}

APPLICATION USAGE

None.

RATIONALE

The intent of the paragraph describing "additional or alternate file access control mechanisms" is to allow a secure implementation where a process with a label that does not dominate the file's label cannot perform a stat() function. This is not related to read permission; a process with a label that dominates the file's label does not need read permission. An implementation that supports write-up operations could fail fstat() function calls even though it has a valid file descriptor open for writing.

FUTURE DIRECTIONS

None.

SEE ALSO

fstat() , lstat() , readlink() , symlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sendto(3p)

SENDTO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sendto - send a message on a socket

SYNOPSIS

#include <sys/socket.h>

ssize_t sendto(int socket, const void *message, size_t length,
int flags, const struct sockaddr *dest_addr,
socklen_t dest_len);

DESCRIPTION

The sendto() function shall send a message through a connection-mode or connectionless-mode socket. If the socket is connectionless-mode, the message shall be sent to the address specified by dest_addr. If the socket is connection-mode, dest_addr shall be ignored.

The sendto() function takes the following arguments:

socket
Specifies the socket file descriptor.
message
Points to a buffer containing the message to be sent.
length
Specifies the size of the message in bytes.
flags
Specifies the type of message transmission. Values of this argument are formed by logically OR'ing zero or more of the following flags:
MSG_EOR
Terminates a record (if supported by the protocol).
MSG_OOB
Sends out-of-band data on sockets that support out-of-band data. The significance and semantics of out-of-band data are protocol-specific.

dest_addr
Points to a sockaddr structure containing the destination address. The length and format of the address depend on the address family of the socket.
dest_len
Specifies the length of the sockaddr structure pointed to by the dest_addr argument.

If the socket protocol supports broadcast and the specified address is a broadcast address for the socket protocol, sendto() shall fail if the SO_BROADCAST option is not set for the socket.

The dest_addr argument specifies the address of the target. The length argument specifies the length of the message.

Successful completion of a call to sendto() does not guarantee delivery of the message. A return value of -1 indicates only locally-detected errors.

If space is not available at the sending socket to hold the message to be transmitted and the socket file descriptor does not have O_NONBLOCK set, sendto() shall block until space is available. If space is not available at the sending socket to hold the message to be transmitted and the socket file descriptor does have O_NONBLOCK set, sendto() shall fail.

The socket in use may require the process to have appropriate privileges to use the sendto() function.

RETURN VALUE

Upon successful completion, sendto() shall return the number of bytes sent. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The sendto() function shall fail if:

EAFNOSUPPORT
Addresses in the specified address family cannot be used with this socket.
EAGAIN or EWOULDBLOCK
The socket's file descriptor is marked O_NONBLOCK and the requested operation would block.
EBADF
The socket argument is not a valid file descriptor.
ECONNRESET
A connection was forcibly closed by a peer.
EINTR
A signal interrupted sendto() before any data was transmitted.
EMSGSIZE
The message is too large to be sent all at once, as the socket requires.
ENOTCONN
The socket is connection-mode but is not connected.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The socket argument is associated with a socket that does not support one or more of the values set in flags.
EPIPE
The socket is shut down for writing, or the socket is connection-mode and is no longer connected. In the latter case, and if the socket is of type SOCK_STREAM, the SIGPIPE signal is generated to the calling thread.

If the address family of the socket is AF_UNIX, then sendto() shall fail if:

EIO
An I/O error occurred while reading from or writing to the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the pathname in the socket address.
ENAMETOOLONG
A component of a pathname exceeded {NAME_MAX} characters, or an entire pathname exceeded {PATH_MAX} characters.
ENOENT
A component of the pathname does not name an existing file or the pathname is an empty string.
ENOTDIR
A component of the path prefix of the pathname in the socket address is not a directory.

The sendto() function may fail if:

EACCES
Search permission is denied for a component of the path prefix; or write access to the named socket is denied.
EDESTADDRREQ
The socket is not connection-mode and does not have its peer address set, and no destination address was specified.
EHOSTUNREACH
The destination host cannot be reached (probably because the host is down or a remote router cannot reach it).
EINVAL
The dest_len argument is not a valid length for the address family.
EIO
An I/O error occurred while reading from or writing to the file system.
EISCONN
A destination address was specified and the socket is already connected. This error may or may not be returned for connection mode sockets.
ENETDOWN
The local network interface used to reach the destination is down.
ENETUNREACH
No route to the network is present.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.

If the address family of the socket is AF_UNIX, then sendto() may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the pathname in the socket address.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The select() and poll() functions can be used to determine when it is possible to send more data.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getsockopt() , poll() , recv() , recvfrom() , recvmsg() , select() , send() , sendmsg() , setsockopt() , shutdown() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cimagl (3p)

 Continue to this page.


rewinddir(3p)

REWINDDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rewinddir - reset the position of a directory stream to the beginning of a directory

SYNOPSIS

#include <dirent.h>

void rewinddir(DIR *dirp);

DESCRIPTION

The rewinddir() function shall reset the position of the directory stream to which dirp refers to the beginning of the directory. It shall also cause the directory stream to refer to the current state of the corresponding directory, as a call to opendir() would have done. If dirp does not refer to a directory stream, the effect is undefined.

After a call to the fork() function, either the parent or child (but not both) may continue processing the directory stream using readdir(), rewinddir(), or seekdir(). If both the parent and child processes use these functions, the result is undefined.

RETURN VALUE

The rewinddir() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The rewinddir() function should be used in conjunction with opendir(), readdir(), and closedir() to examine the contents of the directory. This method is recommended for portability.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

closedir() , opendir() , readdir() , the Base Definitions volume of IEEE Std 1003.1-2001, <dirent.h> <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nextafterf (3p)

 Continue to this page.


nextafterl (3p)

 Continue to this page.


scalbn(3p)

SCALBLN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

scalbln, scalblnf, scalblnl, scalbn, scalbnf, scalbnl - compute exponent using FLT_RADIX

SYNOPSIS

#include <math.h>

double scalbln(double x, long n);
float scalblnf(float x, long n);
long double scalblnl(long double x, long n);
double scalbn(double x, int n);
float scalbnf(float x, int n);
long double scalbnl(long double x, int n);

DESCRIPTION

These functions shall compute x * FLT_RADIX**n efficiently, not normally by computing FLT_RADIX**n explicitly.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return x * FLT_RADIX**n.

If the result would cause overflow, a range error shall occur and these functions shall return ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (according to the sign of x) as appropriate for the return type of the function.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

If n is 0, x shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

ERRORS

These functions shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

These functions are named so as to avoid conflicting with the historical definition of the scalb() function from the Single UNIX Specification. The difference is that the scalb() function has a second argument of double instead of int. The scalb() function is not part of the ISO C standard. The three functions whose second type is long are provided because the factor required to scale from the smallest positive floating-point value to the largest finite one, on many implementations, is too large to represent in the minimum-width int format.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , scalb() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isatty(3p)

ISATTY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isatty - test for a terminal device

SYNOPSIS

#include <unistd.h>

int isatty(int fildes);

DESCRIPTION

The isatty() function shall test whether fildes, an open file descriptor, is associated with a terminal device.

RETURN VALUE

The isatty() function shall return 1 if fildes is associated with a terminal; otherwise, it shall return 0 and may set errno to indicate the error.

ERRORS

The isatty() function may fail if:

EBADF
The fildes argument is not a valid open file descriptor.
ENOTTY
The fildes argument is not associated with a terminal.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The isatty() function does not necessarily indicate that a human being is available for interaction via fildes. It is quite possible that non-terminal devices are connected to the communications line.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcsspn(3p)

WCSSPN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsspn - get the length of a wide substring

SYNOPSIS

#include <wchar.h>

size_t wcsspn(const wchar_t *ws1, const wchar_t *ws2);

DESCRIPTION

The wcsspn() function shall compute the length (in wide characters) of the maximum initial segment of the wide-character string pointed to by ws1 which consists entirely of wide-character codes from the wide-character string pointed to by ws2.

RETURN VALUE

The wcsspn() function shall return the length of the initial substring of ws1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcscspn() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lchown(3p)

LCHOWN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lchown - change the owner and group of a symbolic link

SYNOPSIS

#include <unistd.h>

int lchown(const char *path, uid_t owner, gid_t group);

DESCRIPTION

The lchown() function shall be equivalent to chown(), except in the case where the named file is a symbolic link. In this case, lchown() shall change the ownership of the symbolic link file itself, while chown() changes the ownership of the file or directory to which the symbolic link refers.

RETURN VALUE

Upon successful completion, lchown() shall return 0. Otherwise, it shall return -1 and set errno to indicate an error.

ERRORS

The lchown() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix of path.
EINVAL
The owner or group ID is not a value supported by the implementation.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of a pathname exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix of path is not a directory.
EOPNOTSUPP
The path argument names a symbolic link and the implementation does not support setting the owner or group of a symbolic link.
EPERM
The effective user ID does not match the owner of the file and the process does not have appropriate privileges.
EROFS
The file resides on a read-only file system.

The lchown() function may fail if:

EIO
An I/O error occurred while reading or writing to the file system.
EINTR
A signal was caught during execution of the function.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

Changing the Current Owner of a File

The following example shows how to change the ownership of the symbolic link named /modules/pass1 to the user ID associated with "jones" and the group ID associated with "cnd".

The numeric value for the user ID is obtained by using the getpwnam() function. The numeric value for the group ID is obtained by using the getgrnam() function.

#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>

struct passwd *pwd;
struct group  *grp;
char          *path = "/modules/pass1";
...
pwd = getpwnam("jones");
grp = getgrnam("cnd");
lchown(path, pwd->pw_uid, grp->gr_gid);

APPLICATION USAGE

On implementations which support symbolic links as directory entries rather than files, lchown() may fail.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

chown() , symlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


catclose(3p)

CATCLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

catclose - close a message catalog descriptor

SYNOPSIS

#include <nl_types.h>

int catclose(nl_catd catd);

DESCRIPTION

The catclose() function shall close the message catalog identified by catd. If a file descriptor is used to implement the type nl_catd, that file descriptor shall be closed.

RETURN VALUE

Upon successful completion, catclose() shall return 0; otherwise, -1 shall be returned, and errno set to indicate the error.

ERRORS

The catclose() function may fail if:

EBADF
The catalog descriptor is not valid.
EINTR
The catclose() function was interrupted by a signal.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

catgets() , catopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <nl_types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


geteuid(3p)

GETEUID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

geteuid - get the effective user ID

SYNOPSIS

#include <unistd.h>

uid_t geteuid(void);

DESCRIPTION

The geteuid() function shall return the effective user ID of the calling process.

RETURN VALUE

The geteuid() function shall always be successful and no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getegid() , getgid() , getuid() , setegid() , seteuid() , setgid() , setregid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcswidth(3p)

WCSWIDTH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcswidth - number of column positions of a wide-character string

SYNOPSIS

#include <wchar.h>

int wcswidth(const wchar_t *pwcs, size_t n);

DESCRIPTION

The wcswidth() function shall determine the number of column positions required for n wide-character codes (or fewer than n wide-character codes if a null wide-character code is encountered before n wide-character codes are exhausted) in the string pointed to by pwcs.

RETURN VALUE

The wcswidth() function either shall return 0 (if pwcs points to a null wide-character code), or return the number of column positions to be occupied by the wide-character string pointed to by pwcs, or return -1 (if any of the first n wide-character codes in the wide-character string pointed to by pwcs is not a printable wide-character code).

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

This function was removed from the final ISO/IEC 9899:1990/Amendment 1:1995 (E), and the return value for a non-printable wide character is not specified.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcwidth() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.103, Column Position, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcsstr(3p)

WCSSTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsstr - find a wide-character substring

SYNOPSIS

#include <wchar.h>

wchar_t *wcsstr(const wchar_t *restrict ws1,
const wchar_t *restrict ws2);

DESCRIPTION

The wcsstr() function shall locate the first occurrence in the wide-character string pointed to by ws1 of the sequence of wide characters (excluding the terminating null wide character) in the wide-character string pointed to by ws2.

RETURN VALUE

Upon successful completion, wcsstr() shall return a pointer to the located wide-character string, or a null pointer if the wide-character string is not found.

If ws2 points to a wide-character string with zero length, the function shall return ws1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcschr() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawn(3p)

POSIX_SPAWN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawn, posix_spawnp - spawn a process (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

int posix_spawn(pid_t *restrict pid, const char *restrict path,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *restrict attrp,
char *const argv[restrict], char *const envp[restrict]);
int posix_spawnp(pid_t *restrict pid, const char *restrict file,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *restrict attrp,
char *const argv[restrict], char * const envp[restrict]);

DESCRIPTION

The posix_spawn() and posix_spawnp() functions shall create a new process (child process) from the specified process image. The new process image shall be constructed from a regular executable file called the new process image file.

When a C program is executed as the result of this call, it shall be entered as a C-language function call as follows:

int main(int argc, char *argv[]);

where argc is the argument count and argv is an array of character pointers to the arguments themselves. In addition, the following variable:

extern char **environ;

shall be initialized as a pointer to an array of character pointers to the environment strings.

The argument argv is an array of character pointers to null-terminated strings. The last member of this array shall be a null pointer and is not counted in argc. These strings constitute the argument list available to the new process image. The value in argv[0] should point to a filename that is associated with the process image being started by the posix_spawn() or posix_spawnp() function.

The argument envp is an array of character pointers to null-terminated strings. These strings constitute the environment for the new process image. The environment array is terminated by a null pointer.

The number of bytes available for the child process' combined argument and environment lists is {ARG_MAX}. The implementation shall specify in the system documentation (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 2, Conformance) whether any list overhead, such as length words, null terminators, pointers, or alignment bytes, is included in this total.

The path argument to posix_spawn() is a pathname that identifies the new process image file to execute.

The file parameter to posix_spawnp() shall be used to construct a pathname that identifies the new process image file. If the file parameter contains a slash character, the file parameter shall be used as the pathname for the new process image file. Otherwise, the path prefix for this file shall be obtained by a search of the directories passed as the environment variable PATH (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables). If this environment variable is not defined, the results of the search are implementation-defined.

If file_actions is a null pointer, then file descriptors open in the calling process shall remain open in the child process, except for those whose close-on- exec flag FD_CLOEXEC is set (see fcntl() ). For those file descriptors that remain open, all attributes of the corresponding open file descriptions, including file locks (see fcntl() ), shall remain unchanged.

If file_actions is not NULL, then the file descriptors open in the child process shall be those open in the calling process as modified by the spawn file actions object pointed to by file_actions and the FD_CLOEXEC flag of each remaining open file descriptor after the spawn file actions have been processed. The effective order of processing the spawn file actions shall be:

1.
The set of open file descriptors for the child process shall initially be the same set as is open for the calling process. All attributes of the corresponding open file descriptions, including file locks (see fcntl() ), shall remain unchanged.

2.
The signal mask, signal default actions, and the effective user and group IDs for the child process shall be changed as specified in the attributes object referenced by attrp.

3.
The file actions specified by the spawn file actions object shall be performed in the order in which they were added to the spawn file actions object.

4.
Any file descriptor that has its FD_CLOEXEC flag set (see fcntl() ) shall be closed.

The posix_spawnattr_t spawn attributes object type is defined in <spawn.h>. It shall contain at least the attributes defined below.

If the POSIX_SPAWN_SETPGROUP flag is set in the spawn-flags attribute of the object referenced by attrp, and the spawn-pgroup attribute of the same object is non-zero, then the child's process group shall be as specified in the spawn-pgroup attribute of the object referenced by attrp.

As a special case, if the POSIX_SPAWN_SETPGROUP flag is set in the spawn-flags attribute of the object referenced by attrp, and the spawn-pgroup attribute of the same object is set to zero, then the child shall be in a new process group with a process group ID equal to its process ID.

If the POSIX_SPAWN_SETPGROUP flag is not set in the spawn-flags attribute of the object referenced by attrp, the new child process shall inherit the parent's process group.

If the POSIX_SPAWN_SETSCHEDPARAM flag is set in the spawn-flags attribute of the object referenced by attrp, but POSIX_SPAWN_SETSCHEDULER is not set, the new process image shall initially have the scheduling policy of the calling process with the scheduling parameters specified in the spawn-schedparam attribute of the object referenced by attrp.

If the POSIX_SPAWN_SETSCHEDULER flag is set in the spawn-flags attribute of the object referenced by attrp (regardless of the setting of the POSIX_SPAWN_SETSCHEDPARAM flag), the new process image shall initially have the scheduling policy specified in the spawn-schedpolicy attribute of the object referenced by attrp and the scheduling parameters specified in the spawn-schedparam attribute of the same object.

The POSIX_SPAWN_RESETIDS flag in the spawn-flags attribute of the object referenced by attrp governs the effective user ID of the child process. If this flag is not set, the child process shall inherit the parent process' effective user ID. If this flag is set, the child process' effective user ID shall be reset to the parent's real user ID. In either case, if the set-user-ID mode bit of the new process image file is set, the effective user ID of the child process shall become that file's owner ID before the new process image begins execution.

The POSIX_SPAWN_RESETIDS flag in the spawn-flags attribute of the object referenced by attrp also governs the effective group ID of the child process. If this flag is not set, the child process shall inherit the parent process' effective group ID. If this flag is set, the child process' effective group ID shall be reset to the parent's real group ID. In either case, if the set-group-ID mode bit of the new process image file is set, the effective group ID of the child process shall become that file's group ID before the new process image begins execution.

If the POSIX_SPAWN_SETSIGMASK flag is set in the spawn-flags attribute of the object referenced by attrp, the child process shall initially have the signal mask specified in the spawn-sigmask attribute of the object referenced by attrp.

If the POSIX_SPAWN_SETSIGDEF flag is set in the spawn-flags attribute of the object referenced by attrp, the signals specified in the spawn-sigdefault attribute of the same object shall be set to their default actions in the child process. Signals set to the default action in the parent process shall be set to the default action in the child process.

Signals set to be caught by the calling process shall be set to the default action in the child process.

Except for SIGCHLD, signals set to be ignored by the calling process image shall be set to be ignored by the child process, unless otherwise specified by the POSIX_SPAWN_SETSIGDEF flag being set in the spawn-flags attribute of the object referenced by attrp and the signals being indicated in the spawn-sigdefault attribute of the object referenced by attrp.

If the SIGCHLD signal is set to be ignored by the calling process, it is unspecified whether the SIGCHLD signal is set to be ignored or to the default action in the child process, unless otherwise specified by the POSIX_SPAWN_SETSIGDEF flag being set in the spawn_flags attribute of the object referenced by attrp and the SIGCHLD signal being indicated in the spawn_sigdefault attribute of the object referenced by attrp.

If the value of the attrp pointer is NULL, then the default values are used.

All process attributes, other than those influenced by the attributes set in the object referenced by attrp as specified above or by the file descriptor manipulations specified in file_actions, shall appear in the new process image as though fork() had been called to create a child process and then a member of the exec family of functions had been called by the child process to execute the new process image.

It is implementation-defined whether the fork handlers are run when posix_spawn() or posix_spawnp() is called.

RETURN VALUE

Upon successful completion, posix_spawn() and posix_spawnp() shall return the process ID of the child process to the parent process, in the variable pointed to by a non-NULL pid argument, and shall return zero as the function return value. Otherwise, no child process shall be created, the value stored into the variable pointed to by a non-NULL pid is unspecified, and an error number shall be returned as the function return value to indicate the error. If the pid argument is a null pointer, the process ID of the child is not returned to the caller.

ERRORS

The posix_spawn() and posix_spawnp() functions may fail if:

EINVAL
The value specified by file_actions or attrp is invalid.

If this error occurs after the calling process successfully returns from the posix_spawn() or posix_spawnp() function, the child process may exit with exit status 127.

If posix_spawn() or posix_spawnp() fail for any of the reasons that would cause fork() or one of the exec family of functions to fail, an error value shall be returned as described by fork() and exec, respectively (or, if the error occurs after the calling process successfully returns, the child process shall exit with exit status 127).

If POSIX_SPAWN_SETPGROUP is set in the spawn-flags attribute of the object referenced by attrp, and posix_spawn() or posix_spawnp() fails while changing the child's process group, an error value shall be returned as described by setpgid() (or, if the error occurs after the calling process successfully returns, the child process shall exit with exit status 127).

If POSIX_SPAWN_SETSCHEDPARAM is set and POSIX_SPAWN_SETSCHEDULER is not set in the spawn-flags attribute of the object referenced by attrp, then if posix_spawn() or posix_spawnp() fails for any of the reasons that would cause sched_setparam() to fail, an error value shall be returned as described by sched_setparam() (or, if the error occurs after the calling process successfully returns, the child process shall exit with exit status 127).

If POSIX_SPAWN_SETSCHEDULER is set in the spawn-flags attribute of the object referenced by attrp, and if posix_spawn() or posix_spawnp() fails for any of the reasons that would cause sched_setscheduler() to fail, an error value shall be returned as described by sched_setscheduler() (or, if the error occurs after the calling process successfully returns, the child process shall exit with exit status 127).

If the file_actions argument is not NULL, and specifies any close, dup2, or open actions to be performed, and if posix_spawn() or posix_spawnp() fails for any of the reasons that would cause close(), dup2(), or open() to fail, an error value shall be returned as described by close(), dup2(), and open(), respectively (or, if the error occurs after the calling process successfully returns, the child process shall exit with exit status 127). An open file action may, by itself, result in any of the errors described by close() or dup2(), in addition to those described by open().

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

The posix_spawn() function and its close relation posix_spawnp() have been introduced to overcome the following perceived difficulties with fork(): the fork() function is difficult or impossible to implement without swapping or dynamic address translation.

*
Swapping is generally too slow for a realtime environment.

*
Dynamic address translation is not available everywhere that POSIX might be useful.

*
Processes are too useful to simply option out of POSIX whenever it must run without address translation or other MMU services.

Thus, POSIX needs process creation and file execution primitives that can be efficiently implemented without address translation or other MMU services.

The posix_spawn() function is implementable as a library routine, but both posix_spawn() and posix_spawnp() are designed as kernel operations. Also, although they may be an efficient replacement for many fork()/ exec pairs, their goal is to provide useful process creation primitives for systems that have difficulty with fork(), not to provide drop-in replacements for fork()/ exec.

This view of the role of posix_spawn() and posix_spawnp() influenced the design of their API. It does not attempt to provide the full functionality of fork()/ exec in which arbitrary user-specified operations of any sort are permitted between the creation of the child process and the execution of the new process image; any attempt to reach that level would need to provide a programming language as parameters. Instead, posix_spawn() and posix_spawnp() are process creation primitives like the Start_Process and Start_Process_Search Ada language bindings package POSIX_Process_Primitives and also like those in many operating systems that are not UNIX systems, but with some POSIX-specific additions.

To achieve its coverage goals, posix_spawn() and posix_spawnp() have control of six types of inheritance: file descriptors, process group ID, user and group ID, signal mask, scheduling, and whether each signal ignored in the parent will remain ignored in the child, or be reset to its default action in the child.

Control of file descriptors is required to allow an independently written child process image to access data streams opened by and even generated or read by the parent process without being specifically coded to know which parent files and file descriptors are to be used. Control of the process group ID is required to control how the child process' job control relates to that of the parent.

Control of the signal mask and signal defaulting is sufficient to support the implementation of system(). Although support for system() is not explicitly one of the goals for posix_spawn() and posix_spawnp(), it is covered under the "at least 50%" coverage goal.

The intention is that the normal file descriptor inheritance across fork(), the subsequent effect of the specified spawn file actions, and the normal file descriptor inheritance across one of the exec family of functions should fully specify open file inheritance. The implementation need make no decisions regarding the set of open file descriptors when the child process image begins execution, those decisions having already been made by the caller and expressed as the set of open file descriptors and their FD_CLOEXEC flags at the time of the call and the spawn file actions object specified in the call. We have been assured that in cases where the POSIX Start_Process Ada primitives have been implemented in a library, this method of controlling file descriptor inheritance may be implemented very easily.

We can identify several problems with posix_spawn() and posix_spawnp(), but there does not appear to be a solution that introduces fewer problems. Environment modification for child process attributes not specifiable via the attrp or file_actions arguments must be done in the parent process, and since the parent generally wants to save its context, it is more costly than similar functionality with fork()/ exec. It is also complicated to modify the environment of a multi-threaded process temporarily, since all threads must agree when it is safe for the environment to be changed. However, this cost is only borne by those invocations of posix_spawn() and posix_spawnp() that use the additional functionality. Since extensive modifications are not the usual case, and are particularly unlikely in time-critical code, keeping much of the environment control out of posix_spawn() and posix_spawnp() is appropriate design.

The posix_spawn() and posix_spawnp() functions do not have all the power of fork()/ exec. This is to be expected. The fork() function is a wonderfully powerful operation. We do not expect to duplicate its functionality in a simple, fast function with no special hardware requirements. It is worth noting that posix_spawn() and posix_spawnp() are very similar to the process creation operations on many operating systems that are not UNIX systems.

Requirements

The requirements for posix_spawn() and posix_spawnp() are:

*
They must be implementable without an MMU or unusual hardware.

*
They must be compatible with existing POSIX standards.

Additional goals are:

*
They should be efficiently implementable.

*
They should be able to replace at least 50% of typical executions of fork().

*
A system with posix_spawn() and posix_spawnp() and without fork() should be useful, at least for realtime applications.

*
A system with fork() and the exec family should be able to implement posix_spawn() and posix_spawnp() as library routines.

Two-Syntax

POSIX exec has several calling sequences with approximately the same functionality. These appear to be required for compatibility with existing practice. Since the existing practice for the posix_spawn*() functions is otherwise substantially unlike POSIX, we feel that simplicity outweighs compatibility. There are, therefore, only two names for the posix_spawn*() functions.

The parameter list does not differ between posix_spawn() and posix_spawnp(); posix_spawnp() interprets the second parameter more elaborately than posix_spawn().

Compatibility with POSIX.5 (Ada)

The Start_Process and Start_Process_Search procedures from the POSIX_Process_Primitives package from the Ada language binding to POSIX.1 encapsulate fork() and exec functionality in a manner similar to that of posix_spawn() and posix_spawnp(). Originally, in keeping with our simplicity goal, the standard developers had limited the capabilities of posix_spawn() and posix_spawnp() to a subset of the capabilities of Start_Process and Start_Process_Search; certain non-default capabilities were not supported. However, based on suggestions by the ballot group to improve file descriptor mapping or drop it, and on the advice of an Ada Language Bindings working group member, the standard developers decided that posix_spawn() and posix_spawnp() should be sufficiently powerful to implement Start_Process and Start_Process_Search. The rationale is that if the Ada language binding to such a primitive had already been approved as an IEEE standard, there can be little justification for not approving the functionally-equivalent parts of a C binding. The only three capabilities provided by posix_spawn() and posix_spawnp() that are not provided by Start_Process and Start_Process_Search are optionally specifying the child's process group ID, the set of signals to be reset to default signal handling in the child process, and the child's scheduling policy and parameters.

For the Ada language binding for Start_Process to be implemented with posix_spawn(), that binding would need to explicitly pass an empty signal mask and the parent's environment to posix_spawn() whenever the caller of Start_Process allowed these arguments to default, since posix_spawn() does not provide such defaults. The ability of Start_Process to mask user-specified signals during its execution is functionally unique to the Ada language binding and must be dealt with in the binding separately from the call to posix_spawn().

Process Group

The process group inheritance field can be used to join the child process with an existing process group. By assigning a value of zero to the spawn-pgroup attribute of the object referenced by attrp, the setpgid() mechanism will place the child process in a new process group.

Threads

Without the posix_spawn() and posix_spawnp() functions, systems without address translation can still use threads to give an abstraction of concurrency. In many cases, thread creation suffices, but it is not always a good substitute. The posix_spawn() and posix_spawnp() functions are considerably "heavier" than thread creation. Processes have several important attributes that threads do not. Even without address translation, a process may have base-and-bound memory protection. Each process has a process environment including security attributes and file capabilities, and powerful scheduling attributes. Processes abstract the behavior of non-uniform-memory-architecture multi-processors better than threads, and they are more convenient to use for activities that are not closely linked.

The posix_spawn() and posix_spawnp() functions may not bring support for multiple processes to every configuration. Process creation is not the only piece of operating system support required to support multiple processes. The total cost of support for multiple processes may be quite high in some circumstances. Existing practice shows that support for multiple processes is uncommon and threads are common among "tiny kernels". There should, therefore, probably continue to be AEPs for operating systems with only one process.

Asynchronous Error Notification

A library implementation of posix_spawn() or posix_spawnp() may not be able to detect all possible errors before it forks the child process. IEEE Std 1003.1-2001 provides for an error indication returned from a child process which could not successfully complete the spawn operation via a special exit status which may be detected using the status value returned by wait() and waitpid().

The stat_val interface and the macros used to interpret it are not well suited to the purpose of returning API errors, but they are the only path available to a library implementation. Thus, an implementation may cause the child process to exit with exit status 127 for any error detected during the spawn process after the posix_spawn() or posix_spawnp() function has successfully returned.

The standard developers had proposed using two additional macros to interpret stat_val. The first, WIFSPAWNFAIL, would have detected a status that indicated that the child exited because of an error detected during the posix_spawn() or posix_spawnp() operations rather than during actual execution of the child process image; the second, WSPAWNERRNO, would have extracted the error value if WIFSPAWNFAIL indicated a failure. Unfortunately, the ballot group strongly opposed this because it would make a library implementation of posix_spawn() or posix_spawnp() dependent on kernel modifications to waitpid() to be able to embed special information in stat_val to indicate a spawn failure.

The 8 bits of child process exit status that are guaranteed by IEEE Std 1003.1-2001 to be accessible to the waiting parent process are insufficient to disambiguate a spawn error from any other kind of error that may be returned by an arbitrary process image. No other bits of the exit status are required to be visible in stat_val, so these macros could not be strictly implemented at the library level. Reserving an exit status of 127 for such spawn errors is consistent with the use of this value by system() and popen() to signal failures in these operations that occur after the function has returned but before a shell is able to execute. The exit status of 127 does not uniquely identify this class of error, nor does it provide any detailed information on the nature of the failure. Note that a kernel implementation of posix_spawn() or posix_spawnp() is permitted (and encouraged) to return any possible error as the function value, thus providing more detailed failure information to the parent process.

Thus, no special macros are available to isolate asynchronous posix_spawn() or posix_spawnp() errors. Instead, errors detected by the posix_spawn() or posix_spawnp() operations in the context of the child process before the new process image executes are reported by setting the child's exit status to 127. The calling process may use the WIFEXITED and WEXITSTATUS macros on the stat_val stored by the wait() or waitpid() functions to detect spawn failures to the extent that other status values with which the child process image may exit (before the parent can conclusively determine that the child process image has begun execution) are distinct from exit status 127.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , chmod() , close() , dup() , exec()
, exit() , fcntl() , fork() , kill() , open()
, posix_spawn_file_actions_addclose() , posix_spawn_file_actions_adddup2()
, posix_spawn_file_actions_addopen() , posix_spawn_file_actions_destroy()
, , posix_spawnattr_destroy() , posix_spawnattr_init()
, posix_spawnattr_getsigdefault() , posix_spawnattr_getflags()
, posix_spawnattr_getpgroup() , posix_spawnattr_getschedparam()
, posix_spawnattr_getschedpolicy() , posix_spawnattr_getsigmask()
, posix_spawnattr_setsigdefault() , posix_spawnattr_setflags()
, posix_spawnattr_setpgroup() , posix_spawnattr_setschedparam()
, posix_spawnattr_setschedpolicy() , posix_spawnattr_setsigmask()
, sched_setparam() , sched_setscheduler() , setpgid()
, setuid() , stat() , times() , wait() , the
Base Definitions volume of
IEEE Std 1003.1-2001, <spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmaf (3p)

 Continue to this page.


mktime(3p)

MKTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mktime - convert broken-down time into time since the Epoch

SYNOPSIS

#include <time.h>

time_t mktime(struct tm *timeptr);

DESCRIPTION

The mktime() function shall convert the broken-down time, expressed as local time, in the structure pointed to by timeptr, into a time since the Epoch value with the same encoding as that of the values returned by time(). The original values of the tm_wday and tm_yday components of the structure are ignored, and the original values of the other components are not restricted to the ranges described in <time.h>.

A positive or 0 value for tm_isdst shall cause mktime() to presume initially that Daylight Savings Time, respectively, is or is not in effect for the specified time. A negative value for tm_isdst shall cause mktime() to attempt to determine whether Daylight Savings Time is in effect for the specified time.

Local timezone information shall be set as though mktime() called tzset().

The relationship between the tm structure (defined in the <time.h> header) and the time in seconds since the Epoch is that the result shall be as specified in the expression given in the definition of seconds since the Epoch (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.14, Seconds Since the Epoch) corrected for timezone and any seasonal time adjustments, where the names in the structure and in the expression correspond.

Upon successful completion, the values of the tm_wday and tm_yday components of the structure shall be set appropriately, and the other components are set to represent the specified time since the Epoch, but with their values forced to the ranges indicated in the <time.h> entry; the final value of tm_mday shall not be set until tm_mon and tm_year are determined.

RETURN VALUE

The mktime() function shall return the specified time since the Epoch encoded as a value of type time_t. If the time since the Epoch cannot be represented, the function shall return the value (time_t)-1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

What day of the week is July 4, 2001?

#include <stdio.h>
#include <time.h>

struct tm time_str;

char daybuf[20];

int main(void)
{
    time_str.tm_year = 2001 - 1900;
    time_str.tm_mon = 7 - 1;
    time_str.tm_mday = 4;
    time_str.tm_hour = 0;
    time_str.tm_min = 0;
    time_str.tm_sec = 1;
    time_str.tm_isdst = -1;
    if (mktime(&time_str) == -1)
        (void)puts("-unknown-");
    else {
        (void)strftime(daybuf, sizeof(daybuf), "%A", &time_str);
        (void)puts(daybuf);
    }
    return 0;
}

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asctime() , clock() , ctime() , difftime() , gmtime() , localtime() , strftime() , strptime() , time() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmal (3p)

 Continue to this page.


pthread_sigmask (3p)

 Continue to this page.


readdir(3p)

READDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

readdir, readdir_r - read a directory

SYNOPSIS

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

int readdir_r(DIR *restrict dirp, struct dirent *restrict entry,
struct dirent **restrict result);

DESCRIPTION

The type DIR, which is defined in the <dirent.h> header, represents a directory stream, which is an ordered sequence of all the directory entries in a particular directory. Directory entries represent files; files may be removed from a directory or added to a directory asynchronously to the operation of readdir().

The readdir() function shall return a pointer to a structure representing the directory entry at the current position in the directory stream specified by the argument dirp, and position the directory stream at the next entry. It shall return a null pointer upon reaching the end of the directory stream. The structure dirent defined in the <dirent.h> header describes a directory entry.

The readdir() function shall not return directory entries containing empty names. If entries for dot or dot-dot exist, one entry shall be returned for dot and one entry shall be returned for dot-dot; otherwise, they shall not be returned.

The pointer returned by readdir() points to data which may be overwritten by another call to readdir() on the same directory stream. This data is not overwritten by another call to readdir() on a different directory stream.

If a file is removed from or added to the directory after the most recent call to opendir() or rewinddir(), whether a subsequent call to readdir() returns an entry for that file is unspecified.

The readdir() function may buffer several directory entries per actual read operation; readdir() shall mark for update the st_atime field of the directory each time the directory is actually read.

After a call to fork(), either the parent or child (but not both) may continue processing the directory stream using readdir(), rewinddir(), or seekdir(). If both the parent and child processes use these functions, the result is undefined.

If the entry names a symbolic link, the value of the d_ino member is unspecified.

The readdir() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The readdir_r() function shall initialize the dirent structure referenced by entry to represent the directory entry at the current position in the directory stream referred to by dirp, store a pointer to this structure at the location referenced by result, and position the directory stream at the next entry.

The storage pointed to by entry shall be large enough for a dirent with an array of char d_name members containing at least {NAME_MAX}+1 elements.

Upon successful return, the pointer returned at *result shall have the same value as the argument entry. Upon reaching the end of the directory stream, this pointer shall have the value NULL.

The readdir_r() function shall not return directory entries containing empty names.

If a file is removed from or added to the directory after the most recent call to opendir() or rewinddir(), whether a subsequent call to readdir_r() returns an entry for that file is unspecified.

The readdir_r() function may buffer several directory entries per actual read operation; the readdir_r() function shall mark for update the st_atime field of the directory each time the directory is actually read.

Applications wishing to check for error situations should set errno to 0 before calling readdir(). If errno is set to non-zero on return, an error occurred.

RETURN VALUE

Upon successful completion, readdir() shall return a pointer to an object of type struct dirent. When an error is encountered, a null pointer shall be returned and errno shall be set to indicate the error. When the end of the directory is encountered, a null pointer shall be returned and errno is not changed.

If successful, the readdir_r() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The readdir() function shall fail if:

EOVERFLOW
One of the values in the structure to be returned cannot be represented correctly.

The readdir() function may fail if:

EBADF
The dirp argument does not refer to an open directory stream.
ENOENT
The current position of the directory stream is invalid.

The readdir_r() function may fail if:

EBADF
The dirp argument does not refer to an open directory stream.

The following sections are informative.

EXAMPLES

The following sample program searches the current directory for each of the arguments supplied on the command line.

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

static void lookup(const char *arg)
{
    DIR *dirp;
    struct dirent *dp;

    if ((dirp = opendir(".")) == NULL) {
        perror("couldn't open '.'");
        return;
    }

    do {
        errno = 0;
        if ((dp = readdir(dirp)) != NULL) {
            if (strcmp(dp->d_name, arg) != 0)
                continue;

            (void) printf("found %s\n", arg);
            (void) closedir(dirp);
                return;

        }
    } while (dp != NULL);

    if (errno != 0)
        perror("error reading directory");
    else
        (void) printf("failed to find %s\n", arg);
    (void) closedir(dirp);
    return;
}

int main(int argc, char *argv[])
{
    int i;
    for (i = 1; i < argc; i++)
        lookup(arvg[i]);
    return (0);
}

APPLICATION USAGE

The readdir() function should be used in conjunction with opendir(), closedir(), and rewinddir() to examine the contents of the directory.

The readdir_r() function is thread-safe and shall return values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

The returned value of readdir() merely represents a directory entry. No equivalence should be inferred.

Historical implementations of readdir() obtain multiple directory entries on a single read operation, which permits subsequent readdir() operations to operate from the buffered information. Any wording that required each successful readdir() operation to mark the directory st_atime field for update would disallow such historical performance-oriented implementations.

Since readdir() returns NULL when it detects an error and when the end of the directory is encountered, an application that needs to tell the difference must set errno to zero before the call and check it if NULL is returned. Since the function must not change errno in the second case and must set it to a non-zero value in the first case, a zero errno after a call returning NULL indicates end-of-directory; otherwise, an error.

Routines to deal with this problem more directly were proposed:

int derror (dirp)
DIR *dirp;

void clearderr (dirp)
DIR *dirp;

The first would indicate whether an error had occurred, and the second would clear the error indication. The simpler method involving errno was adopted instead by requiring that readdir() not change errno when end-of-directory is encountered.

An error or signal indicating that a directory has changed while open was considered but rejected.

The thread-safe version of the directory reading function returns values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call. Either the {NAME_MAX} compile-time constant or the corresponding pathconf() option can be used to determine the maximum sizes of returned pathnames.

FUTURE DIRECTIONS

None.

SEE ALSO

closedir() , lstat() , opendir() , rewinddir() , symlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <dirent.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmax(3p)

FMAX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fmax, fmaxf, fmaxl - determine maximum numeric value of two floating-point numbers

SYNOPSIS

#include <math.h>

double fmax(double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);

DESCRIPTION

These functions shall determine the maximum numeric value of their arguments. NaN arguments shall be treated as missing data: if one argument is a NaN and the other numeric, then these functions shall choose the numeric value.

RETURN VALUE

Upon successful completion, these functions shall return the maximum numeric value of their arguments.

If just one argument is a NaN, the other argument shall be returned.

If x and y are NaN, a NaN shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fdim() , fmin() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


time(3p)

TIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

time - get time

SYNOPSIS

#include <time.h>

time_t time(time_t *tloc);

DESCRIPTION

The time() function shall return the value of time in seconds since the Epoch.

The tloc argument points to an area where the return value is also stored. If tloc is a null pointer, no value is stored.

RETURN VALUE

Upon successful completion, time() shall return the value of time. Otherwise, (time_t)-1 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Getting the Current Time

The following example uses the time() function to calculate the time elapsed, in seconds, since the Epoch, localtime() to convert that value to a broken-down time, and asctime() to convert the broken-down time values into a printable string.

#include <stdio.h>
#include <time.h>

int main(void)
{
time_t result;

    result = time(NULL);
    printf("%s%ju secs since the Epoch\n",
        asctime(localtime(&result)),
            (uintmax_t)result);
    return(0);
}

This example writes the current time to stdout in a form like this:

Wed Jun 26 10:32:15 1996
835810335 secs since the Epoch

Timing an Event

The following example gets the current time, prints it out in the user's format, and prints the number of minutes to an event being timed.

#include <time.h>
#include <stdio.h>
...
time_t now;
int minutes_to_event;
...
time(&now);
minutes_to_event = ...;
printf("The time is ");
puts(asctime(localtime(&now)));
printf("There are %d minutes to the event.\n",
    minutes_to_event);
...

APPLICATION USAGE

None.

RATIONALE

The time() function returns a value in seconds (type time_t) while times() returns a set of values in clock ticks (type clock_t). Some historical implementations, such as 4.3 BSD, have mechanisms capable of returning more precise times (see below). A generalized timing scheme to unify these various timing mechanisms has been proposed but not adopted.

Implementations in which time_t is a 32-bit signed integer (many historical implementations) fail in the year 2038. IEEE Std 1003.1-2001 does not address this problem. However, the use of the time_t type is mandated in order to ease the eventual fix.

The use of the <time.h> header instead of <sys/types.h> allows compatibility with the ISO C standard.

Many historical implementations (including Version 7) and the 1984 /usr/group standard use long instead of time_t. This volume of IEEE Std 1003.1-2001 uses the latter type in order to agree with the ISO C standard.

4.3 BSD includes time() only as an alternate function to the more flexible gettimeofday() function.

FUTURE DIRECTIONS

In a future version of this volume of IEEE Std 1003.1-2001, time_t is likely to be required to be capable of representing times far in the future. Whether this will be mandated as a 64-bit type or a requirement that a specific date in the future be representable (for example, 10000 AD) is not yet determined. Systems purchased after the approval of this volume of IEEE Std 1003.1-2001 should be evaluated to determine whether their lifetime will extend past 2038.

SEE ALSO

asctime() , clock() , ctime() , difftime() , gettimeofday() , gmtime() , localtime() , mktime() , strftime() , strptime() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


exec(3p)

EXEC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

environ, execl, execv, execle, execve, execlp, execvp - execute a file

SYNOPSIS

#include <unistd.h>

extern char **environ;
int execl(const char *path, const char *arg0, ... /*, (char *)0 */);
int execv(const char *path, char *const argv[]);
int execle(const char *path, const char *arg0, ... /*,
(char *)0, char *const envp[]*/);
int execve(const char *path, char *const argv[], char *const envp[]);
int execlp(const char *file, const char *arg0, ... /*, (char *)0 */);
int execvp(const char *file, char *const argv[]);

DESCRIPTION

The exec family of functions shall replace the current process image with a new process image. The new image shall be constructed from a regular, executable file called the new process image file. There shall be no return from a successful exec, because the calling process image is overlaid by the new process image.

When a C-language program is executed as a result of this call, it shall be entered as a C-language function call as follows:

int main (int argc, char *argv[]);

where argc is the argument count and argv is an array of character pointers to the arguments themselves. In addition, the following variable:

extern char **environ;

is initialized as a pointer to an array of character pointers to the environment strings. The argv and environ arrays are each terminated by a null pointer. The null pointer terminating the argv array is not counted in argc.

Conforming multi-threaded applications shall not use the environ variable to access or modify any environment variable while any other thread is concurrently modifying any environment variable. A call to any function dependent on any environment variable shall be considered a use of the environ variable to access that environment variable.

The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments.

The argument path points to a pathname that identifies the new process image file.

The argument file is used to construct a pathname that identifies the new process image file. If the file argument contains a slash character, the file argument shall be used as the pathname for this file. Otherwise, the path prefix for this file is obtained by a search of the directories passed as the environment variable PATH (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables). If this environment variable is not present, the results of the search are implementation-defined.

There are two distinct ways in which the contents of the process image file may cause the execution to fail, distinguished by the setting of errno to either [ENOEXEC] or [EINVAL] (see the ERRORS section). In the cases where the other members of the exec family of functions would fail and set errno to [ENOEXEC], the execlp() and execvp() functions shall execute a command interpreter and the environment of the executed command shall be as if the process invoked the sh utility using execl() as follows:

execl(<shell path>, arg0, file, arg1, ..., (char *)0);

where <shell path> is an unspecified pathname for the sh utility, file is the process image file, and for execvp(), where arg0, arg1, and so on correspond to the values passed to execvp() in argv[0], argv[1], and so on.

The arguments represented by arg0,... are pointers to null-terminated character strings. These strings shall constitute the argument list available to the new process image. The list is terminated by a null pointer. The argument arg0 should point to a filename that is associated with the process being started by one of the exec functions.

The argument argv is an array of character pointers to null-terminated strings. The application shall ensure that the last member of this array is a null pointer. These strings shall constitute the argument list available to the new process image. The value in argv[0] should point to a filename that is associated with the process being started by one of the exec functions.

The argument envp is an array of character pointers to null-terminated strings. These strings shall constitute the environment for the new process image. The envp array is terminated by a null pointer.

For those forms not containing an envp pointer ( execl(), execv(), execlp(), and execvp()), the environment for the new process image shall be taken from the external variable environ in the calling process.

The number of bytes available for the new process' combined argument and environment lists is {ARG_MAX}. It is implementation-defined whether null terminators, pointers, and/or any alignment bytes are included in this total.

File descriptors open in the calling process image shall remain open in the new process image, except for those whose close-on- exec flag FD_CLOEXEC is set. For those file descriptors that remain open, all attributes of the open file description remain unchanged. For any file descriptor that is closed for this reason, file locks are removed as a result of the close as described in close() . Locks that are not removed by closing of file descriptors remain unchanged.

If file descriptors 0, 1, and 2 would otherwise be closed after a successful call to one of the exec family of functions, and the new process image file has the set-user-ID or set-group-ID file mode bits set, and the ST_NOSUID bit is not set for the file system containing the new process image file, implementations may open an unspecified file for each of these file descriptors in the new process image.

Directory streams open in the calling process image shall be closed in the new process image.

The state of the floating-point environment in the new process image shall be set to the default.

The state of conversion descriptors and message catalog descriptors in the new process image is undefined. For the new process image, the equivalent of:

setlocale(LC_ALL, "C")

shall be executed at start-up.

Signals set to the default action (SIG_DFL) in the calling process image shall be set to the default action in the new process image. Except for SIGCHLD, signals set to be ignored (SIG_IGN) by the calling process image shall be set to be ignored by the new process image. Signals set to be caught by the calling process image shall be set to the default action in the new process image (see <signal.h>). If the SIGCHLD signal is set to be ignored by the calling process image, it is unspecified whether the SIGCHLD signal is set to be ignored or to the default action in the new process image. After a successful call to any of the exec functions, alternate signal stacks are not preserved and the SA_ONSTACK flag shall be cleared for all signals.

After a successful call to any of the exec functions, any functions previously registered by atexit() are no longer registered.

If the ST_NOSUID bit is set for the file system containing the new process image file, then the effective user ID, effective group ID, saved set-user-ID, and saved set-group-ID are unchanged in the new process image. Otherwise, if the set-user-ID mode bit of the new process image file is set, the effective user ID of the new process image shall be set to the user ID of the new process image file. Similarly, if the set-group-ID mode bit of the new process image file is set, the effective group ID of the new process image shall be set to the group ID of the new process image file. The real user ID, real group ID, and supplementary group IDs of the new process image shall remain the same as those of the calling process image. The effective user ID and effective group ID of the new process image shall be saved (as the saved set-user-ID and the saved set-group-ID) for use by setuid().

Any shared memory segments attached to the calling process image shall not be attached to the new process image.

Any named semaphores open in the calling process shall be closed as if by appropriate calls to sem_close().

Any blocks of typed memory that were mapped in the calling process are unmapped, as if munmap() was implicitly called to unmap them.

Memory locks established by the calling process via calls to mlockall() or mlock() shall be removed. If locked pages in the address space of the calling process are also mapped into the address spaces of other processes and are locked by those processes, the locks established by the other processes shall be unaffected by the call by this process to the exec function. If the exec function fails, the effect on memory locks is unspecified.

Memory mappings created in the process are unmapped before the address space is rebuilt for the new process image.

For the SCHED_FIFO and SCHED_RR scheduling policies, the policy and priority settings shall not be changed by a call to an exec function. For other scheduling policies, the policy and priority settings on exec are implementation-defined.

Per-process timers created by the calling process shall be deleted before replacing the current process image with the new process image.

All open message queue descriptors in the calling process shall be closed, as described in mq_close() .

Any outstanding asynchronous I/O operations may be canceled. Those asynchronous I/O operations that are not canceled shall complete as if the exec function had not yet occurred, but any associated signal notifications shall be suppressed. It is unspecified whether the exec function itself blocks awaiting such I/O completion. In no event, however, shall the new process image created by the exec function be affected by the presence of outstanding asynchronous I/O operations at the time the exec function is called. Whether any I/O is canceled, and which I/O may be canceled upon exec, is implementation-defined.

The new process image shall inherit the CPU-time clock of the calling process image. This inheritance means that the process CPU-time clock of the process being exec-ed shall not be reinitialized or altered as a result of the exec function other than to reflect the time spent by the process executing the exec function itself.

The initial value of the CPU-time clock of the initial thread of the new process image shall be set to zero.

If the calling process is being traced, the new process image shall continue to be traced into the same trace stream as the original process image, but the new process image shall not inherit the mapping of trace event names to trace event type identifiers that was defined by calls to the posix_trace_eventid_open() or the posix_trace_trid_eventid_open() functions in the calling process image.

If the calling process is a trace controller process, any trace streams that were created by the calling process shall be shut down as described in the posix_trace_shutdown() function.

The new process shall inherit at least the following attributes from the calling process image:

*
Nice value (see nice() )

*
semadj values (see semop() )

*
Process ID

*
Parent process ID

*
Process group ID

*
Session membership

*
Real user ID

*
Real group ID

*
Supplementary group IDs

*
Time left until an alarm clock signal (see alarm() )

*
Current working directory

*
Root directory

*
File mode creation mask (see umask() )

*
File size limit (see ulimit() )

*
Process signal mask (see sigprocmask() )

*
Pending signal (see sigpending() )

*
tms_utime, tms_stime, tms_cutime, and tms_cstime (see times() )

*
Resource limits

*
Controlling terminal

*
Interval timers

All other process attributes defined in this volume of IEEE Std 1003.1-2001 shall be the same in the new and old process images. The inheritance of process attributes not defined by this volume of IEEE Std 1003.1-2001 is implementation-defined.

A call to any exec function from a process with more than one thread shall result in all threads being terminated and the new executable image being loaded and executed. No destructor functions shall be called.

Upon successful completion, the exec functions shall mark for update the st_atime field of the file. If an exec function failed but was able to locate the process image file, whether the st_atime field is marked for update is unspecified. Should the exec function succeed, the process image file shall be considered to have been opened with open(). The corresponding close() shall be considered to occur at a time after this open, but before process termination or successful completion of a subsequent call to one of the exec functions, posix_spawn(), or posix_spawnp(). The argv[] and envp[] arrays of pointers and the strings to which those arrays point shall not be modified by a call to one of the exec functions, except as a consequence of replacing the process image.

The saved resource limits in the new process image are set to be a copy of the process' corresponding hard and soft limits.

RETURN VALUE

If one of the exec functions returns to the calling process image, an error has occurred; the return value shall be -1, and errno shall be set to indicate the error.

ERRORS

The exec functions shall fail if:

E2BIG
The number of bytes used by the new process image's argument list and environment list is greater than the system-imposed limit of {ARG_MAX} bytes.
EACCES
Search permission is denied for a directory listed in the new process image file's path prefix, or the new process image file denies execution permission, or the new process image file is not a regular file and the implementation does not support execution of files of its type.
EINVAL
The new process image file has the appropriate permission and has a recognized executable binary format, but the system does not support execution of a file with this format.
ELOOP
A loop exists in symbolic links encountered during resolution of the path or file argument.
ENAMETOOLONG
The length of the path or file arguments exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path or file does not name an existing file or path or file is an empty string.
ENOTDIR
A component of the new process image file's path prefix is not a directory.

The exec functions, except for execlp() and execvp(), shall fail if:

ENOEXEC
The new process image file has the appropriate access permission but has an unrecognized format.

The exec functions may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path or file argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ENOMEM
The new process image requires more memory than is allowed by the hardware or system-imposed memory management constraints.
ETXTBSY
The new process image file is a pure procedure (shared text) file that is currently open for writing by some process.

The following sections are informative.

EXAMPLES

Using execl()

The following example executes the ls command, specifying the pathname of the executable ( /bin/ls) and using arguments supplied directly to the command to produce single-column output.

#include <unistd.h>

int ret;
...
ret = execl ("/bin/ls", "ls", "-1", (char *)0);

Using execle()

The following example is similar to Using execl() . In addition, it specifies the environment for the new process image using the env argument.

#include <unistd.h>

int ret;
char *env[] = { "HOME=/usr/home", "LOGNAME=home", (char *)0 };
...
ret = execle ("/bin/ls", "ls", "-l", (char *)0, env);

Using execlp()

The following example searches for the location of the ls command among the directories specified by the PATH environment variable.

#include <unistd.h>

int ret;
...
ret = execlp ("ls", "ls", "-l", (char *)0);

Using execv()

The following example passes arguments to the ls command in the cmd array.

#include <unistd.h>

int ret;
char *cmd[] = { "ls", "-l", (char *)0 };
...
ret = execv ("/bin/ls", cmd);

Using execve()

The following example passes arguments to the ls command in the cmd array, and specifies the environment for the new process image using the env argument.

#include <unistd.h>

int ret;
char *cmd[] = { "ls", "-l", (char *)0 };
char *env[] = { "HOME=/usr/home", "LOGNAME=home", (char *)0 };
...
ret = execve ("/bin/ls", cmd, env);

Using execvp()

The following example searches for the location of the ls command among the directories specified by the PATH environment variable, and passes arguments to the ls command in the cmd array.

#include <unistd.h>

int ret;
char *cmd[] = { "ls", "-l", (char *)0 };
...
ret = execvp ("ls", cmd);

APPLICATION USAGE

As the state of conversion descriptors and message catalog descriptors in the new process image is undefined, conforming applications should not rely on their use and should close them prior to calling one of the exec functions.

Applications that require other than the default POSIX locale should call setlocale() with the appropriate parameters to establish the locale of the new process.

The environ array should not be accessed directly by the application.

Applications should not depend on file descriptors 0, 1, and 2 being closed after an exec. A future version may allow these file descriptors to be automatically opened for any process.

RATIONALE

Early proposals required that the value of argc passed to main() be "one or greater". This was driven by the same requirement in drafts of the ISO C standard. In fact, historical implementations have passed a value of zero when no arguments are supplied to the caller of the exec functions. This requirement was removed from the ISO C standard and subsequently removed from this volume of IEEE Std 1003.1-2001 as well. The wording, in particular the use of the word should, requires a Strictly Conforming POSIX Application to pass at least one argument to the exec function, thus guaranteeing that argc be one or greater when invoked by such an application. In fact, this is good practice, since many existing applications reference argv[0] without first checking the value of argc.

The requirement on a Strictly Conforming POSIX Application also states that the value passed as the first argument be a filename associated with the process being started. Although some existing applications pass a pathname rather than a filename in some circumstances, a filename is more generally useful, since the common usage of argv[0] is in printing diagnostics. In some cases the filename passed is not the actual filename of the file; for example, many implementations of the login utility use a convention of prefixing a hyphen ( '-' ) to the actual filename, which indicates to the command interpreter being invoked that it is a "login shell".

Historically there have been two ways that implementations can exec shell scripts.

One common historical implementation is that the execl(), execv(), execle(), and execve() functions return an [ENOEXEC] error for any file not recognizable as executable, including a shell script. When the execlp() and execvp() functions encounter such a file, they assume the file to be a shell script and invoke a known command interpreter to interpret such files. This is now required by IEEE Std 1003.1-2001. These implementations of execvp() and execlp() only give the [ENOEXEC] error in the rare case of a problem with the command interpreter's executable file. Because of these implementations, the [ENOEXEC] error is not mentioned for execlp() or execvp(), although implementations can still give it.

Another way that some historical implementations handle shell scripts is by recognizing the first two bytes of the file as the character string "#!" and using the remainder of the first line of the file as the name of the command interpreter to execute.

One potential source of confusion noted by the standard developers is over how the contents of a process image file affect the behavior of the exec family of functions. The following is a description of the actions taken:

1.
If the process image file is a valid executable (in a format that is executable and valid and having appropriate permission) for this system, then the system executes the file.

2.
If the process image file has appropriate permission and is in a format that is executable but not valid for this system (such as a recognized binary for another architecture), then this is an error and errno is set to [EINVAL] (see later RATIONALE on [EINVAL]).

3.
If the process image file has appropriate permission but is not otherwise recognized:
a.
If this is a call to execlp() or execvp(), then they invoke a command interpreter assuming that the process image file is a shell script.

b.
If this is not a call to execlp() or execvp(), then an error occurs and errno is set to [ENOEXEC].

Applications that do not require to access their arguments may use the form:

main(void)
as specified in the ISO C standard. However, the implementation will always provide the two arguments argc and argv, even if they are not used.

Some implementations provide a third argument to main() called envp. This is defined as a pointer to the environment. The ISO C standard specifies invoking main() with two arguments, so implementations must support applications written this way. Since this volume of IEEE Std 1003.1-2001 defines the global variable environ, which is also provided by historical implementations and can be used anywhere that envp could be used, there is no functional need for the envp argument. Applications should use the getenv() function rather than accessing the environment directly via either envp or environ. Implementations are required to support the two-argument calling sequence, but this does not prohibit an implementation from supporting envp as an optional third argument.

This volume of IEEE Std 1003.1-2001 specifies that signals set to SIG_IGN remain set to SIG_IGN, and that the process signal mask be unchanged across an exec. This is consistent with historical implementations, and it permits some useful functionality, such as the nohup command. However, it should be noted that many existing applications wrongly assume that they start with certain signals set to the default action and/or unblocked. In particular, applications written with a simpler signal model that does not include blocking of signals, such as the one in the ISO C standard, may not behave properly if invoked with some signals blocked. Therefore, it is best not to block or ignore signals across execs without explicit reason to do so, and especially not to block signals across execs of arbitrary (not closely co-operating) programs.

The exec functions always save the value of the effective user ID and effective group ID of the process at the completion of the exec, whether or not the set-user-ID or the set-group-ID bit of the process image file is set.

The statement about argv[] and envp[] being constants is included to make explicit to future writers of language bindings that these objects are completely constant. Due to a limitation of the ISO C standard, it is not possible to state that idea in standard C. Specifying two levels of const- qualification for the argv[] and envp[] parameters for the exec functions may seem to be the natural choice, given that these functions do not modify either the array of pointers or the characters to which the function points, but this would disallow existing correct code. Instead, only the array of pointers is noted as constant. The table of assignment compatibility for dst= src derived from the ISO C standard summarizes the compatibility:
dst: | char *[] | const char *[] | char *const[] | const char *const[]
src: |  |  |  |
char *[] | VALID | - | VALID | -
const char *[] | - | VALID | - | VALID
char * const [] | - | - | VALID | -
const char *const[] | - | - | - | VALID

Since all existing code has a source type matching the first row, the column that gives the most valid combinations is the third column. The only other possibility is the fourth column, but using it would require a cast on the argv or envp arguments. It is unfortunate that the fourth column cannot be used, because the declaration a non-expert would naturally use would be that in the second row.

The ISO C standard and this volume of IEEE Std 1003.1-2001 do not conflict on the use of environ, but some historical implementations of environ may cause a conflict. As long as environ is treated in the same way as an entry point (for example, fork()), it conforms to both standards. A library can contain fork(), but if there is a user-provided fork(), that fork() is given precedence and no problem ensues. The situation is similar for environ: the definition in this volume of IEEE Std 1003.1-2001 is to be used if there is no user-provided environ to take precedence. At least three implementations are known to exist that solve this problem.

E2BIG
The limit {ARG_MAX} applies not just to the size of the argument list, but to the sum of that and the size of the environment list.
EFAULT
Some historical systems return [EFAULT] rather than [ENOEXEC] when the new process image file is corrupted. They are non-conforming.
EINVAL
This error condition was added to IEEE Std 1003.1-2001 to allow an implementation to detect executable files generated for different architectures, and indicate this situation to the application. Historical implementations of shells, execvp(), and execlp() that encounter an [ENOEXEC] error will execute a shell on the assumption that the file is a shell script. This will not produce the desired effect when the file is a valid executable for a different architecture. An implementation may now choose to avoid this problem by returning [EINVAL] when a valid executable for a different architecture is encountered. Some historical implementations return [EINVAL] to indicate that the path argument contains a character with the high order bit set. The standard developers chose to deviate from historical practice for the following reasons:
1.
The new utilization of [EINVAL] will provide some measure of utility to the user community.

2.
Historical use of [EINVAL] is not acceptable in an internationalized operating environment.

ENAMETOOLONG
Since the file pathname may be constructed by taking elements in the PATH variable and putting them together with the filename, the [ENAMETOOLONG] error condition could also be reached this way.
ETXTBSY
System V returns this error when the executable file is currently open for writing by some process. This volume of IEEE Std 1003.1-2001 neither requires nor prohibits this behavior.

Other systems (such as System V) may return [EINTR] from exec. This is not addressed by this volume of IEEE Std 1003.1-2001, but implementations may have a window between the call to exec and the time that a signal could cause one of the exec calls to return with [EINTR].

An explicit statement regarding the floating-point environment (as defined in the <fenv.h> header) was added to make it clear that the floating-point environment is set to its default when a call to one of the exec functions succeeds. The requirements for inheritance or setting to the default for other process and thread start-up functions is covered by more generic statements in their descriptions and can be summarized as follows:

posix_spawn()
Set to default.
fork()
Inherit.
pthread_create()
Inherit.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , atexit() , chmod() , close() , exit() , fcntl() , fork() , fstatvfs() , getenv() , getitimer() , getrlimit() , mmap() , nice() , posix_spawn() , posix_trace_eventid_open() , posix_trace_shutdown() , posix_trace_trid_eventid_open() , putenv() , semop() , setlocale() , shmat() , sigaction() , sigaltstack() , sigpending() , sigprocmask() , system() , times() , ulimit() , umask() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstod(3p)

WCSTOD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcstod, wcstof, wcstold - convert a wide-character string to a double-precision number

SYNOPSIS

#include <wchar.h>

double wcstod(const wchar_t *restrict nptr, wchar_t **restrict endptr);
float wcstof(const wchar_t *restrict nptr, wchar_t **restrict endptr);
long double wcstold(const wchar_t *restrict nptr,
wchar_t **restrict endptr);

DESCRIPTION

These functions shall convert the initial portion of the wide-character string pointed to by nptr to double, float, and long double representation, respectively. First, they shall decompose the input wide-character string into three parts:

1.
An initial, possibly empty, sequence of white-space wide-character codes (as specified by iswspace())

2.
A subject sequence interpreted as a floating-point constant or representing infinity or NaN

3.
A final wide-character string of one or more unrecognized wide-character codes, including the terminating null wide-character code of the input wide-character string

Then they shall attempt to convert the subject sequence to a floating-point number, and return the result.

The expected form of the subject sequence is an optional plus or minus sign, then one of the following:

*
A non-empty sequence of decimal digits optionally containing a radix character, then an optional exponent part

*
A 0x or 0X, then a non-empty sequence of hexadecimal digits optionally containing a radix character, then an optional binary exponent part

*
One of INF or INFINITY, or any other wide string equivalent except for case

*
One of NAN or NAN(n-wchar-sequence_opt), or any other wide string ignoring case in the NAN part, where:

n-wchar-sequence:
    digit
    nondigit
    n-wchar-sequence digit
    n-wchar-sequence nondigit

The subject sequence is defined as the longest initial subsequence of the input wide string, starting with the first non-white-space wide character, that is of the expected form. The subject sequence contains no wide characters if the input wide string is not of the expected form.

If the subject sequence has the expected form for a floating-point number, the sequence of wide characters starting with the first digit or the radix character (whichever occurs first) shall be interpreted as a floating constant according to the rules of the C language, except that the radix character shall be used in place of a period, and that if neither an exponent part nor a radix character appears in a decimal floating-point number, or if a binary exponent part does not appear in a hexadecimal floating-point number, an exponent part of the appropriate type with value zero shall be assumed to follow the last digit in the string. If the subject sequence begins with a minus sign, the sequence shall be interpreted as negated. A wide-character sequence INF or INFINITY shall be interpreted as an infinity, if representable in the return type, else as if it were a floating constant that is too large for the range of the return type. A wide-character sequence NAN or NAN(n-wchar-sequence_opt) shall be interpreted as a quiet NaN, if supported in the return type, else as if it were a subject sequence part that does not have the expected form; the meaning of the n-wchar sequences is implementation-defined. A pointer to the final wide string shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

If the subject sequence has the hexadecimal form and FLT_RADIX is a power of 2, the conversion shall be rounded in an implementation-defined manner.

The radix character shall be as defined in the program's locale (category LC_NUMERIC ). In the POSIX locale, or in a locale where the radix character is not defined, the radix character shall default to a period ( '.' ).

In other than the C or POSIX locales, other implementation-defined subject sequences may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion shall be performed; the value of nptr shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

The wcstod() function shall not change the setting of errno if successful.

Since 0 is returned on error and is also a valid return on success, an application wishing to check for error situations should set errno to 0, then call wcstod(), wcstof(), or wcstold(), then check errno.

RETURN VALUE

Upon successful completion, these functions shall return the converted value. If no conversion could be performed, 0 shall be returned and errno may be set to [EINVAL].

If the correct value is outside the range of representable values, ±HUGE_VAL, ±HUGE_VALF, or ±HUGE_VALL shall be returned (according to the sign of the value), and errno shall be set to [ERANGE].

If the correct value would cause underflow, a value whose magnitude is no greater than the smallest normalized positive number in the return type shall be returned and errno set to [ERANGE].

ERRORS

The wcstod() function shall fail if:

ERANGE
The value to be returned would cause overflow or underflow.

The wcstod() function may fail if:

EINVAL
No conversion could be performed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the subject sequence has the hexadecimal form and FLT_RADIX is not a power of 2, and the result is not exactly representable, the result should be one of the two numbers in the appropriate internal format that are adjacent to the hexadecimal floating source value, with the extra stipulation that the error should have a correct sign for the current rounding direction.

If the subject sequence has the decimal form and at most DECIMAL_DIG (defined in <float.h>) significant digits, the result should be correctly rounded. If the subject sequence D has the decimal form and more than DECIMAL_DIG significant digits, consider the two bounding, adjacent decimal strings L and U, both having DECIMAL_DIG significant digits, such that the values of L, D, and U satisfy "L <= D <= U" . The result should be one of the (equal or adjacent) values that would be obtained by correctly rounding L and U according to the current rounding direction, with the extra stipulation that the error with respect to D should have a correct sign for the current rounding direction.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswspace() , localeconv() , scanf() , setlocale() , wcstol() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <float.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstof (3p)

 Continue to this page.


rand_r (3p)

 Continue to this page.


wcstok(3p)

WCSTOK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcstok - split a wide-character string into tokens

SYNOPSIS

#include <wchar.h>

wchar_t *wcstok(wchar_t *restrict ws1, const wchar_t *restrict ws2,
wchar_t **restrict ptr);

DESCRIPTION

A sequence of calls to wcstok() shall break the wide-character string pointed to by ws1 into a sequence of tokens, each of which shall be delimited by a wide-character code from the wide-character string pointed to by ws2. The ptr argument points to a caller-provided wchar_t pointer into which the wcstok() function shall store information necessary for it to continue scanning the same wide-character string.

The first call in the sequence has ws1 as its first argument, and is followed by calls with a null pointer as their first argument. The separator string pointed to by ws2 may be different from call to call.

The first call in the sequence shall search the wide-character string pointed to by ws1 for the first wide-character code that is not contained in the current separator string pointed to by ws2. If no such wide-character code is found, then there are no tokens in the wide-character string pointed to by ws1 and wcstok() shall return a null pointer. If such a wide-character code is found, it shall be the start of the first token.

The wcstok() function shall then search from there for a wide-character code that is contained in the current separator string. If no such wide-character code is found, the current token extends to the end of the wide-character string pointed to by ws1, and subsequent searches for a token shall return a null pointer. If such a wide-character code is found, it shall be overwritten by a null wide character, which terminates the current token. The wcstok() function shall save a pointer to the following wide-character code, from which the next search for a token shall start.

Each subsequent call, with a null pointer as the value of the first argument, shall start searching from the saved pointer and behave as described above.

The implementation shall behave as if no function calls wcstok().

RETURN VALUE

Upon successful completion, the wcstok() function shall return a pointer to the first wide-character code of a token. Otherwise, if there is no token, wcstok() shall return a null pointer.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstol(3p)

WCSTOL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcstol, wcstoll - convert a wide-character string to a long integer

SYNOPSIS

#include <wchar.h>

long wcstol(const wchar_t *restrict nptr, wchar_t **restrict endptr,
int base);
long long wcstoll(const wchar_t *restrict nptr,
wchar_t **restrict endptr, int base);

DESCRIPTION

These functions shall convert the initial portion of the wide-character string pointed to by nptr to long, long long, unsigned long, and unsigned long long representation, respectively. First, they shall decompose the input string into three parts:

1.
An initial, possibly empty, sequence of white-space wide-character codes (as specified by iswspace())

2.
A subject sequence interpreted as an integer represented in some radix determined by the value of base

3.
A final wide-character string of one or more unrecognized wide-character codes, including the terminating null wide-character code of the input wide-character string

Then they shall attempt to convert the subject sequence to an integer, and return the result.

If base is 0, the expected form of the subject sequence is that of a decimal constant, octal constant, or hexadecimal constant, any of which may be preceded by a '+' or '-' sign. A decimal constant begins with a non-zero digit, and consists of a sequence of decimal digits. An octal constant consists of the prefix '0' optionally followed by a sequence of the digits '0' to '7' only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and letters 'a' (or 'A' ) to 'f' (or 'F' ) with values 10 to 15 respectively.

If the value of base is between 2 and 36, the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a '+' or '-' sign, but not including an integer suffix. The letters from 'a' (or 'A' ) to 'z' (or 'Z' ) inclusive are ascribed the values 10 to 35; only letters whose ascribed values are less than that of base shall be permitted. If the value of base is 16, the wide-character code representations of 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.

The subject sequence is defined as the longest initial subsequence of the input wide-character string, starting with the first non-white-space wide-character code that is of the expected form. The subject sequence contains no wide-character codes if the input wide-character string is empty or consists entirely of white-space wide-character code, or if the first non-white-space wide-character code is other than a sign or a permissible letter or digit.

If the subject sequence has the expected form and base is 0, the sequence of wide-character codes starting with the first digit shall be interpreted as an integer constant. If the subject sequence has the expected form and the value of base is between 2 and 36, it shall be used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion shall be negated. A pointer to the final wide-character string shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

In other than the C or POSIX locales, other implementation-defined subject sequences may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion shall be performed; the value of nptr shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

These functions shall not change the setting of errno if successful.

Since 0, {LONG_MIN} or {LLONG_MIN} and {LONG_MAX} or {LLONG_MAX} are returned on error and are also valid returns on success, an application wishing to check for error situations should set errno to 0, then call wcstol() or wcstoll(), then check errno.

RETURN VALUE

Upon successful completion, these functions shall return the converted value, if any. If no conversion could be performed, 0 shall be returned and errno may be set to indicate the error. If the correct value is outside the range of representable values, {LONG_MIN}, {LONG_MAX}, {LLONG_MIN}, or {LLONG_MAX} shall be returned (according to the sign of the value), and errno set to [ERANGE].

ERRORS

These functions shall fail if:

EINVAL
The value of base is not supported.
ERANGE
The value to be returned is not representable.

These functions may fail if:

EINVAL
No conversion could be performed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalpha() , scanf() , wcstod() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


siglongjmp(3p)

SIGLONGJMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

siglongjmp - non-local goto with signal handling

SYNOPSIS

#include <setjmp.h>

void siglongjmp(sigjmp_buf env, int val);

DESCRIPTION

The siglongjmp() function shall be equivalent to the longjmp() function, except as follows:

*
References to setjmp() shall be equivalent to sigsetjmp().

*
The siglongjmp() function shall restore the saved signal mask if and only if the env argument was initialized by a call to sigsetjmp() with a non-zero savemask argument.

RETURN VALUE

After siglongjmp() is completed, program execution shall continue as if the corresponding invocation of sigsetjmp() had just returned the value specified by val. The siglongjmp() function shall not cause sigsetjmp() to return 0; if val is 0, sigsetjmp() shall return the value 1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The distinction between setjmp() or longjmp() and sigsetjmp() or siglongjmp() is only significant for programs which use sigaction(), sigprocmask(), or sigsuspend().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

longjmp() , setjmp() , sigprocmask() , sigsetjmp() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <setjmp.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlock_timedwrlock(3p)

PTHREAD_RWLOCK_TIMEDWRLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlock_timedwrlock - lock a read-write lock for writing

SYNOPSIS

#include <pthread.h>
#include <time.h>

int pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict rwlock,
const struct timespec *restrict abs_timeout);

DESCRIPTION

The pthread_rwlock_timedwrlock() function shall apply a write lock to the read-write lock referenced by rwlock as in the pthread_rwlock_wrlock() function. However, if the lock cannot be acquired without waiting for other threads to unlock the lock, this wait shall be terminated when the specified timeout expires. The timeout shall expire when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call.

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock. If the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function. The resolution of the timeout shall be the resolution of the clock on which it is based. The timespec data type is defined in the <time.h> header. Under no circumstances shall the function fail with a timeout if the lock can be acquired immediately. The validity of the abs_timeout parameter need not be checked if the lock can be immediately acquired.

If a signal that causes a signal handler to be executed is delivered to a thread blocked on a read-write lock via a call to pthread_rwlock_timedwrlock(), upon return from the signal handler the thread shall resume waiting for the lock as if it was not interrupted.

The calling thread may deadlock if at the time the call is made it holds the read-write lock. The results are undefined if this function is called with an uninitialized read-write lock.

RETURN VALUE

The pthread_rwlock_timedwrlock() function shall return zero if the lock for writing on the read-write lock object referenced by rwlock is acquired. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_rwlock_timedwrlock() function shall fail if:

ETIMEDOUT
The lock could not be acquired before the specified timeout expired.

The pthread_rwlock_timedwrlock() function may fail if:

EDEADLK
The calling thread already holds the rwlock.
EINVAL
The value specified by rwlock does not refer to an initialized read-write lock object, or the abs_timeout nanosecond value is less than zero or greater than or equal to 1000 million.

This function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using this function may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

The pthread_rwlock_timedwrlock() function is part of the Threads and Timeouts options and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_destroy() , pthread_rwlock_rdlock() , pthread_rwlock_timedrdlock()
, pthread_rwlock_tryrdlock() , pthread_rwlock_trywrlock()
, pthread_rwlock_unlock() , pthread_rwlock_wrlock() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>,
<time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fwrite(3p)

FWRITE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fwrite - binary output

SYNOPSIS

#include <stdio.h>

size_t fwrite(const void *restrict ptr, size_t size, size_t nitems,
FILE *restrict stream);

DESCRIPTION

The fwrite() function shall write, from the array pointed to by ptr, up to nitems elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls shall be made to the fputc() function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file-position indicator for the stream (if defined) shall be advanced by the number of bytes successfully written. If an error occurs, the resulting value of the file-position indicator for the stream is unspecified.

The st_ctime and st_mtime fields of the file shall be marked for update between the successful execution of fwrite() and the next successful completion of a call to fflush() or fclose() on the same stream, or a call to exit() or abort().

RETURN VALUE

The fwrite() function shall return the number of elements successfully written, which may be less than nitems if a write error is encountered. If size or nitems is 0, fwrite() shall return 0 and the state of the stream remains unchanged. Otherwise, if a write error occurs, the error indicator for the stream shall be set, and errno shall be set to indicate the error.

ERRORS

Refer to fputc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Because of possible differences in element length and byte ordering, files written using fwrite() are application-dependent, and possibly cannot be read using fread() by a different application or by the same application on a different processor.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ferror() , fopen() , printf() , putc() , puts() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sched_get_priority_max(3p)

SCHED_GET_PRIORITY_MAX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched_get_priority_max, sched_get_priority_min - get priority limits (REALTIME)

SYNOPSIS

#include <sched.h>

int sched_get_priority_max(int policy);
int sched_get_priority_min(int policy);

DESCRIPTION

The sched_get_priority_max() and sched_get_priority_min() functions shall return the appropriate maximum or minimum, respectively, for the scheduling policy specified by policy.

The value of policy shall be one of the scheduling policy values defined in <sched.h>.

RETURN VALUE

If successful, the sched_get_priority_max() and sched_get_priority_min() functions shall return the appropriate maximum or minimum values, respectively. If unsuccessful, they shall return a value of -1 and set errno to indicate the error.

ERRORS

The sched_get_priority_max() and sched_get_priority_min() functions shall fail if:

EINVAL
The value of the policy parameter does not represent a defined scheduling policy.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sched_getparam() , sched_setparam() , sched_getscheduler() , sched_rr_get_interval() , sched_setscheduler() , the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_barrier_wait(3p)

PTHREAD_BARRIER_WAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_barrier_wait - synchronize at a barrier (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_barrier_wait(pthread_barrier_t *barrier);

DESCRIPTION

The pthread_barrier_wait() function shall synchronize participating threads at the barrier referenced by barrier. The calling thread shall block until the required number of threads have called pthread_barrier_wait() specifying the barrier.

When the required number of threads have called pthread_barrier_wait() specifying the barrier, the constant PTHREAD_BARRIER_SERIAL_THREAD shall be returned to one unspecified thread and zero shall be returned to each of the remaining threads. At this point, the barrier shall be reset to the state it had as a result of the most recent pthread_barrier_init() function that referenced it.

The constant PTHREAD_BARRIER_SERIAL_THREAD is defined in <pthread.h> and its value shall be distinct from any other value returned by pthread_barrier_wait().

The results are undefined if this function is called with an uninitialized barrier.

If a signal is delivered to a thread blocked on a barrier, upon return from the signal handler the thread shall resume waiting at the barrier if the barrier wait has not completed (that is, if the required number of threads have not arrived at the barrier during the execution of the signal handler); otherwise, the thread shall continue as normal from the completed barrier wait. Until the thread in the signal handler returns from it, it is unspecified whether other threads may proceed past the barrier once they have all reached it.

A thread that has blocked on a barrier shall not prevent any unblocked thread that is eligible to use the same processing resources from eventually making forward progress in its execution. Eligibility for processing resources shall be determined by the scheduling policy.

RETURN VALUE

Upon successful completion, the pthread_barrier_wait() function shall return PTHREAD_BARRIER_SERIAL_THREAD for a single (arbitrary) thread synchronized at the barrier and zero for each of the other threads. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_barrier_wait() function may fail if:

EINVAL
The value specified by barrier does not refer to an initialized barrier object.

This function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using this function may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

The pthread_barrier_wait() function is part of the Barriers option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_barrier_destroy() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_init(3p)

POSIX_SPAWNATTR_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawnattr_destroy, posix_spawnattr_init - destroy and initialize spawn attributes object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

int posix_spawnattr_destroy(posix_spawnattr_t *attr);
int posix_spawnattr_init(posix_spawnattr_t *attr);

DESCRIPTION

The posix_spawnattr_destroy() function shall destroy a spawn attributes object. A destroyed attr attributes object can be reinitialized using posix_spawnattr_init(); the results of otherwise referencing the object after it has been destroyed are undefined. An implementation may cause posix_spawnattr_destroy() to set the object referenced by attr to an invalid value.

The posix_spawnattr_init() function shall initialize a spawn attributes object attr with the default value for all of the individual attributes used by the implementation. Results are undefined if posix_spawnattr_init() is called specifying an already initialized attr attributes object.

A spawn attributes object is of type posix_spawnattr_t (defined in <spawn.h>) and is used to specify the inheritance of process attributes across a spawn operation. IEEE Std 1003.1-2001 does not define comparison or assignment operators for the type posix_spawnattr_t.

Each implementation shall document the individual attributes it uses and their default values unless these values are defined by IEEE Std 1003.1-2001. Attributes not defined by IEEE Std 1003.1-2001, their default values, and the names of the associated functions to get and set those attribute values are implementation-defined.

The resulting spawn attributes object (possibly modified by setting individual attribute values), is used to modify the behavior of posix_spawn() or posix_spawnp(). After a spawn attributes object has been used to spawn a process by a call to a posix_spawn() or posix_spawnp(), any function affecting the attributes object (including destruction) shall not affect any process that has been spawned in this way.

RETURN VALUE

Upon successful completion, posix_spawnattr_destroy() and posix_spawnattr_init() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The posix_spawnattr_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the spawn attributes object.

The posix_spawnattr_destroy() function may fail if:

EINVAL
The value specified by attr is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

The original spawn interface proposed in IEEE Std 1003.1-2001 defined the attributes that specify the inheritance of process attributes across a spawn operation as a structure. In order to be able to separate optional individual attributes under their appropriate options (that is, the spawn-schedparam and spawn-schedpolicy attributes depending upon the Process Scheduling option), and also for extensibility and consistency with the newer POSIX interfaces, the attributes interface has been changed to an opaque data type. This interface now consists of the type posix_spawnattr_t, representing a spawn attributes object, together with associated functions to initialize or destroy the attributes object, and to set or get each individual attribute. Although the new object-oriented interface is more verbose than the original structure, it is simple to use, more extensible, and easy to implement.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnattr_getsigdefault() , posix_spawnattr_getflags()
, posix_spawnattr_getpgroup() , posix_spawnattr_getschedparam()
, posix_spawnattr_getschedpolicy() , posix_spawnattr_getsigmask()
, posix_spawnattr_setsigdefault() , posix_spawnattr_setflags()
, posix_spawnattr_setpgroup() , posix_spawnattr_setsigmask()
, posix_spawnattr_setschedpolicy() , posix_spawnattr_setschedparam()
, posix_spawnp() , the Base Definitions volume of IEEE Std 1003.1-2001,
<spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmin(3p)

FMIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fmin, fminf, fminl - determine minimum numeric value of two floating-point numbers

SYNOPSIS

#include <math.h>

double fmin(double x, double y);
float fminf(float x, float y);
long double fminl(long double x, long double y);

DESCRIPTION

These functions shall determine the minimum numeric value of their arguments. NaN arguments shall be treated as missing data: if one argument is a NaN and the other numeric, then these functions shall choose the numeric value.

RETURN VALUE

Upon successful completion, these functions shall return the minimum numeric value of their arguments.

If just one argument is a NaN, the other argument shall be returned.

If x and y are NaN, a NaN shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fdim() , fmax() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


raise(3p)

RAISE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

raise - send a signal to the executing process

SYNOPSIS

#include <signal.h>

int raise(int sig);

DESCRIPTION

The raise() function shall send the signal sig to the executing thread or process. If a signal handler is called, the raise() function shall not return until after the signal handler does.

If the implementation supports the Threads option, the effect of the raise() function shall be equivalent to calling:

pthread_kill(pthread_self(), sig);

Otherwise, the effect of the raise() function shall be equivalent to calling:

kill(getpid(), sig);

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, a non-zero value shall be returned and errno shall be set to indicate the error.

ERRORS

The raise() function shall fail if:

EINVAL
The value of the sig argument is an invalid signal number.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The term "thread" is an extension to the ISO C standard.

FUTURE DIRECTIONS

None.

SEE ALSO

kill() , sigaction() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


exit(3p)

EXIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

exit, _Exit, _exit - terminate a process

SYNOPSIS

#include <stdlib.h>

void exit(int status);
void _Exit(int status);

#include <unistd.h>
void _exit(int status);

DESCRIPTION

For exit() and _Exit(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process.

The exit() function shall first call all functions registered by atexit(), in the reverse order of their registration, except that a function is called after any previously registered functions that had already been called at the time it was registered. Each function is called as many times as it was registered. If, during the call to any such function, a call to the longjmp() function is made that would terminate the call to the registered function, the behavior is undefined.

If a function registered by a call to atexit() fails to return, the remaining registered functions shall not be called and the rest of the exit() processing shall not be completed. If exit() is called more than once, the behavior is undefined.

The exit() function shall then flush all open streams with unwritten buffered data, close all open streams, and remove all files created by tmpfile(). Finally, control shall be terminated with the consequences described below.

The _Exit() and _exit() functions shall be functionally equivalent.

The _Exit() and _exit() functions shall not call functions registered with atexit() nor any registered signal handlers. Whether open streams are flushed or closed, or temporary files are removed is implementation-defined. Finally, the calling process is terminated with the consequences described below.

These functions shall terminate the calling process with the following consequences:

Note:
These consequences are all extensions to the ISO C standard and are not further CX shaded. However, XSI extensions are shaded.

*
All of the file descriptors, directory streams, conversion descriptors, and message catalog descriptors open in the calling process shall be closed.

*
If the parent process of the calling process is executing a wait() or waitpid(), and has neither set its SA_NOCLDWAIT flag nor set SIGCHLD to SIG_IGN, it shall be notified of the calling process' termination and the low-order eight bits (that is, bits 0377) of status shall be made available to it. If the parent is not waiting, the child's status shall be made available to it when the parent subsequently executes wait() or waitpid().

The semantics of the waitid() function shall be equivalent to wait().

*
If the parent process of the calling process is not executing a wait() or waitpid(), and has neither set its SA_NOCLDWAIT flag nor set SIGCHLD to SIG_IGN, the calling process shall be transformed into a zombie process. A zombie process is an inactive process and it shall be deleted at some later time when its parent process executes wait() or waitpid().

The semantics of the waitid() function shall be equivalent to wait().

*
Termination of a process does not directly terminate its children. The sending of a SIGHUP signal as described below indirectly terminates children in some circumstances.

*
Either:

If the implementation supports the SIGCHLD signal, a SIGCHLD shall be sent to the parent process.

Or:

If the parent process has set its SA_NOCLDWAIT flag, or set SIGCHLD to SIG_IGN, the status shall be discarded, and the lifetime of the calling process shall end immediately. If SA_NOCLDWAIT is set, it is implementation-defined whether a SIGCHLD signal is sent to the parent process.

*
The parent process ID of all of the calling process' existing child processes and zombie processes shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process.

*
Each attached shared-memory segment is detached and the value of shm_nattch (see shmget()) in the data structure associated with its shared memory ID shall be decremented by 1.

*
For each semaphore for which the calling process has set a semadj value (see semop() ), that value shall be added to the semval of the specified semaphore.

*
If the process is a controlling process, the SIGHUP signal shall be sent to each process in the foreground process group of the controlling terminal belonging to the calling process.

*
If the process is a controlling process, the controlling terminal associated with the session shall be disassociated from the session, allowing it to be acquired by a new controlling process.

*
If the exit of the process causes a process group to become orphaned, and if any member of the newly-orphaned process group is stopped, then a SIGHUP signal followed by a SIGCONT signal shall be sent to each process in the newly-orphaned process group.

*
All open named semaphores in the calling process shall be closed as if by appropriate calls to sem_close().

*
Any memory locks established by the process via calls to mlockall() or mlock() shall be removed. If locked pages in the address space of the calling process are also mapped into the address spaces of other processes and are locked by those processes, the locks established by the other processes shall be unaffected by the call by this process to _Exit() or _exit().

*
Memory mappings that were created in the process shall be unmapped before the process is destroyed.

*
Any blocks of typed memory that were mapped in the calling process shall be unmapped, as if munmap() was implicitly called to unmap them.

*
All open message queue descriptors in the calling process shall be closed as if by appropriate calls to mq_close().

*
Any outstanding cancelable asynchronous I/O operations may be canceled. Those asynchronous I/O operations that are not canceled shall complete as if the _Exit() or _exit() operation had not yet occurred, but any associated signal notifications shall be suppressed. The _Exit() or _exit() operation may block awaiting such I/O completion. Whether any I/O is canceled, and which I/O may be canceled upon _Exit() or _exit(), is implementation-defined.

*
Threads terminated by a call to _Exit() or _exit() shall not invoke their cancellation cleanup handlers or per-thread data destructors.

*
If the calling process is a trace controller process, any trace streams that were created by the calling process shall be shut down as described by the posix_trace_shutdown() function, and any process' mapping of trace event names to trace event type identifiers built for these trace streams may be deallocated.

RETURN VALUE

These functions do not return.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Normally applications should use exit() rather than _Exit() or _exit().

RATIONALE

Process Termination

Early proposals drew a distinction between normal and abnormal process termination. Abnormal termination was caused only by certain signals and resulted in implementation-defined "actions", as discussed below. Subsequent proposals distinguished three types of termination: normal termination (as in the current specification), simple abnormal termination, and abnormal termination with actions. Again the distinction between the two types of abnormal termination was that they were caused by different signals and that implementation-defined actions would result in the latter case. Given that these actions were completely implementation-defined, the early proposals were only saying when the actions could occur and how their occurrence could be detected, but not what they were. This was of little or no use to conforming applications, and thus the distinction is not made in this volume of IEEE Std 1003.1-2001.

The implementation-defined actions usually include, in most historical implementations, the creation of a file named core in the current working directory of the process. This file contains an image of the memory of the process, together with descriptive information about the process, perhaps sufficient to reconstruct the state of the process at the receipt of the signal.

There is a potential security problem in creating a core file if the process was set-user-ID and the current user is not the owner of the program, if the process was set-group-ID and none of the user's groups match the group of the program, or if the user does not have permission to write in the current directory. In this situation, an implementation either should not create a core file or should make it unreadable by the user.

Despite the silence of this volume of IEEE Std 1003.1-2001 on this feature, applications are advised not to create files named core because of potential conflicts in many implementations. Some implementations use a name other than core for the file; for example, by appending the process ID to the filename.

Terminating a Process

It is important that the consequences of process termination as described occur regardless of whether the process called _exit() (perhaps indirectly through exit()) or instead was terminated due to a signal or for some other reason. Note that in the specific case of exit() this means that the status argument to exit() is treated in the same way as the status argument to _exit().

A language other than C may have other termination primitives than the C-language exit() function, and programs written in such a language should use its native termination primitives, but those should have as part of their function the behavior of _exit() as described. Implementations in languages other than C are outside the scope of this version of this volume of IEEE Std 1003.1-2001, however.

As required by the ISO C standard, using return from main() has the same behavior (other than with respect to language scope issues) as calling exit() with the returned value. Reaching the end of the main() function has the same behavior as calling exit(0).

A value of zero (or EXIT_SUCCESS, which is required to be zero) for the argument status conventionally indicates successful termination. This corresponds to the specification for exit() in the ISO C standard. The convention is followed by utilities such as make and various shells, which interpret a zero status from a child process as success. For this reason, applications should not call exit(0) or _exit(0) when they terminate unsuccessfully; for example, in signal-catching functions.

Historically, the implementation-defined process that inherits children whose parents have terminated without waiting on them is called init and has a process ID of 1.

The sending of a SIGHUP to the foreground process group when a controlling process terminates corresponds to somewhat different historical implementations. In System V, the kernel sends a SIGHUP on termination of (essentially) a controlling process. In 4.2 BSD, the kernel does not send SIGHUP in a case like this, but the termination of a controlling process is usually noticed by a system daemon, which arranges to send a SIGHUP to the foreground process group with the vhangup() function. However, in 4.2 BSD, due to the behavior of the shells that support job control, the controlling process is usually a shell with no other processes in its process group. Thus, a change to make _exit() behave this way in such systems should not cause problems with existing applications.

The termination of a process may cause a process group to become orphaned in either of two ways. The connection of a process group to its parent(s) outside of the group depends on both the parents and their children. Thus, a process group may be orphaned by the termination of the last connecting parent process outside of the group or by the termination of the last direct descendant of the parent process(es). In either case, if the termination of a process causes a process group to become orphaned, processes within the group are disconnected from their job control shell, which no longer has any information on the existence of the process group. Stopped processes within the group would languish forever. In order to avoid this problem, newly orphaned process groups that contain stopped processes are sent a SIGHUP signal and a SIGCONT signal to indicate that they have been disconnected from their session. The SIGHUP signal causes the process group members to terminate unless they are catching or ignoring SIGHUP. Under most circumstances, all of the members of the process group are stopped if any of them are stopped.

The action of sending a SIGHUP and a SIGCONT signal to members of a newly orphaned process group is similar to the action of 4.2 BSD, which sends SIGHUP and SIGCONT to each stopped child of an exiting process. If such children exit in response to the SIGHUP, any additional descendants receive similar treatment at that time. In this volume of IEEE Std 1003.1-2001, the signals are sent to the entire process group at the same time. Also, in this volume of IEEE Std 1003.1-2001, but not in 4.2 BSD, stopped processes may be orphaned, but may be members of a process group that is not orphaned; therefore, the action taken at _exit() must consider processes other than child processes.

It is possible for a process group to be orphaned by a call to setpgid() or setsid(), as well as by process termination. This volume of IEEE Std 1003.1-2001 does not require sending SIGHUP and SIGCONT in those cases, because, unlike process termination, those cases are not caused accidentally by applications that are unaware of job control. An implementation can choose to send SIGHUP and SIGCONT in those cases as an extension; such an extension must be documented as required in <signal.h>.

The ISO/IEC 9899:1999 standard adds the _Exit() function that results in immediate program termination without triggering signals or atexit()-registered functions. In IEEE Std 1003.1-2001, this is equivalent to the _exit() function.

FUTURE DIRECTIONS

None.

SEE ALSO

atexit() , close() , fclose() , longjmp() , posix_trace_shutdown() , posix_trace_trid_eventid_open() , semop() , shmget() , sigaction() , wait() , waitid() , waitpid() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


exp2(3p)

EXP2

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

exp2, exp2f, exp2l - exponential base 2 functions

SYNOPSIS

#include <math.h>

double exp2(double x);
float exp2f(float x);
long double exp2l(long double x);

DESCRIPTION

These functions shall compute the base-2 exponential of x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return 2**x.

If the correct value would cause overflow, a range error shall occur and exp2(), exp2f(), and exp2l() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0, 1 shall be returned.

If x is -Inf, +0 shall be returned.

If x is +Inf, x shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

ERRORS

These functions shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

For IEEE Std 754-1985 double, 1024 <= x implies exp2( x) has overflowed. The value x < -1022 implies exp( x) has underflowed.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exp() , feclearexcept() , fetestexcept() , isnan() , log() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sched_get_priority_min (3p)

 Continue to this page.


putpmsg (3p)

 Continue to this page.


fmod(3p)

FMOD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fmod, fmodf, fmodl - floating-point remainder value function

SYNOPSIS

#include <math.h>

double fmod(double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);

DESCRIPTION

These functions shall return the floating-point remainder of the division of x by y.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

These functions shall return the value x- i* y, for some integer i such that, if y is non-zero, the result has the same sign as x and magnitude less than the magnitude of y.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x or y is NaN, a NaN shall be returned.

If y is zero, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is infinite, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is ±0 and y is not zero, ±0 shall be returned.

If x is not infinite and y is ±Inf, x shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is infinite or y is zero.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlock_unlock(3p)

PTHREAD_RWLOCK_UNLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlock_unlock - unlock a read-write lock object

SYNOPSIS

#include <pthread.h>

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

DESCRIPTION

The pthread_rwlock_unlock() function shall release a lock held on the read-write lock object referenced by rwlock. Results are undefined if the read-write lock rwlock is not held by the calling thread.

If this function is called to release a read lock from the read-write lock object and there are other read locks currently held on this read-write lock object, the read-write lock object remains in the read locked state. If this function releases the last read lock for this read-write lock object, the read-write lock object shall be put in the unlocked state with no owners.

If this function is called to release a write lock for this read-write lock object, the read-write lock object shall be put in the unlocked state.

If there are threads blocked on the lock when it becomes available, the scheduling policy shall determine which thread(s) shall acquire the lock. If the Thread Execution Scheduling option is supported, when threads executing with the scheduling policies SCHED_FIFO, SCHED_RR, or SCHED_SPORADIC are waiting on the lock, they shall acquire the lock in priority order when the lock becomes available. For equal priority threads, write locks shall take precedence over read locks. If the Thread Execution Scheduling option is not supported, it is implementation-defined whether write locks take precedence over read locks.

Results are undefined if any of these functions are called with an uninitialized read-write lock.

RETURN VALUE

If successful, the pthread_rwlock_unlock() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_rwlock_unlock() function may fail if:

EINVAL
The value specified by rwlock does not refer to an initialized read-write lock object.
EPERM
The current thread does not hold a lock on the read-write lock.

The pthread_rwlock_unlock() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_destroy() , pthread_rwlock_rdlock() , pthread_rwlock_timedrdlock()
, pthread_rwlock_timedwrlock() , pthread_rwlock_tryrdlock()
, pthread_rwlock_trywrlock() , pthread_rwlock_wrlock()
, the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mmap(3p)

MMAP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mmap - map pages of memory

SYNOPSIS

#include <sys/mman.h>

void *mmap(void *addr, size_t len, int prot, int flags,
int fildes, off_t off);

DESCRIPTION

The mmap() function shall establish a mapping between a process' address space and a file, shared memory object, or typed memory object. The format of the call is as follows:

pa=mmap(addr, len, prot, flags, fildes, off);

The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes. The value of pa is an implementation-defined function of the parameter addr and the values of flags, further described below. A successful mmap() call shall return pa as its result. The address range starting at pa and continuing for len bytes shall be legitimate for the possible (not necessarily current) address space of the process. The range of bytes starting at off and continuing for len bytes shall be legitimate for the possible (not necessarily current) offsets in the file, shared memory object, or typed memory object represented by fildes.

If fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, the memory object to be mapped shall be that portion of the typed memory object allocated by the implementation as specified below. In this case, if off is non-zero, the behavior of mmap() is undefined. If fildes refers to a valid typed memory object that is not accessible from the calling process, mmap() shall fail.

The mapping established by mmap() shall replace any previous mappings for those whole pages containing any part of the address space of the process starting at pa and continuing for len bytes.

If the size of the mapped file changes after the call to mmap() as a result of some other operation on the mapped file, the effect of references to portions of the mapped region that correspond to added or removed portions of the file is unspecified.

The mmap() function shall be supported for regular files, shared memory objects, and typed memory objects. Support for any other type of file is unspecified.

The parameter prot determines whether read, write, execute, or some combination of accesses are permitted to the data being mapped. The prot shall be either PROT_NONE or the bitwise-inclusive OR of one or more of the other flags in the following table, defined in the <sys/mman.h> header.
Symbolic Constant | Description
PROT_READ | Data can be read.
PROT_WRITE | Data can be written.
PROT_EXEC | Data can be executed.
PROT_NONE | Data cannot be accessed.

If an implementation cannot support the combination of access types specified by prot, the call to mmap() shall fail.

An implementation may permit accesses other than those specified by prot; however, if the Memory Protection option is supported, the implementation shall not permit a write to succeed where PROT_WRITE has not been set or shall not permit any access where PROT_NONE alone has been set. The implementation shall support at least the following values of prot: PROT_NONE, PROT_READ, PROT_WRITE, and the bitwise-inclusive OR of PROT_READ and PROT_WRITE. If the Memory Protection option is not supported, the result of any access that conflicts with the specified protection is undefined. The file descriptor fildes shall have been opened with read permission, regardless of the protection options specified. If PROT_WRITE is specified, the application shall ensure that it has opened the file descriptor fildes with write permission unless MAP_PRIVATE is specified in the flags parameter as described below.

The parameter flags provides other information about the handling of the mapped data. The value of flags is the bitwise-inclusive OR of these options, defined in <sys/mman.h>:
Symbolic Constant | Description
MAP_SHARED | Changes are shared.
MAP_PRIVATE | Changes are private.
MAP_FIXED | Interpret addr exactly.

Implementations that do not support the Memory Mapped Files option are not required to support MAP_PRIVATE.

It is implementation-defined whether MAP_FIXED shall be supported. MAP_FIXED shall be supported on XSI-conformant systems.

MAP_SHARED and MAP_PRIVATE describe the disposition of write references to the memory object. If MAP_SHARED is specified, write references shall change the underlying object. If MAP_PRIVATE is specified, modifications to the mapped data by the calling process shall be visible only to the calling process and shall not change the underlying object. It is unspecified whether modifications to the underlying object done after the MAP_PRIVATE mapping is established are visible through the MAP_PRIVATE mapping. Either MAP_SHARED or MAP_PRIVATE can be specified, but not both. The mapping type is retained across fork().

When fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, mmap() shall, if there are enough resources available, map len bytes allocated from the corresponding typed memory object which were not previously allocated to any process in any processor that may access that typed memory object. If there are not enough resources available, the function shall fail. If fildes represents a typed memory object opened with the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, these allocated bytes shall be contiguous within the typed memory object. If fildes represents a typed memory object opened with the POSIX_TYPED_MEM_ALLOCATE flag, these allocated bytes may be composed of non-contiguous fragments within the typed memory object. If fildes represents a typed memory object opened with neither the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag nor the POSIX_TYPED_MEM_ALLOCATE flag, len bytes starting at offset off within the typed memory object are mapped, exactly as when mapping a file or shared memory object. In this case, if two processes map an area of typed memory using the same off and len values and using file descriptors that refer to the same memory pool (either from the same port or from a different port), both processes shall map the same region of storage.

When MAP_FIXED is set in the flags argument, the implementation is informed that the value of pa shall be addr, exactly. If MAP_FIXED is set, mmap() may return MAP_FAILED and set errno to [EINVAL]. If a MAP_FIXED request is successful, the mapping established by mmap() replaces any previous mappings for the process' pages in the range [pa,pa+len).

When MAP_FIXED is not set, the implementation uses addr in an implementation-defined manner to arrive at pa. The pa so chosen shall be an area of the address space that the implementation deems suitable for a mapping of len bytes to the file. All implementations interpret an addr value of 0 as granting the implementation complete freedom in selecting pa, subject to constraints described below. A non-zero value of addr is taken to be a suggestion of a process address near which the mapping should be placed. When the implementation selects a value for pa, it never places a mapping at address 0, nor does it replace any extant mapping.

The off argument is constrained to be aligned and sized according to the value returned by sysconf() when passed _SC_PAGESIZE or _SC_PAGE_SIZE. When MAP_FIXED is specified, the application shall ensure that the argument addr also meets these constraints. The implementation performs mapping operations over whole pages. Thus, while the argument len need not meet a size or alignment constraint, the implementation shall include, in any mapping operation, any partial page specified by the range [pa,pa+len).

The system shall always zero-fill any partial page at the end of an object. Further, the system shall never write out any modified portions of the last page of an object which are beyond its end. References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.

An implementation may generate SIGBUS signals when a reference would cause an error in the mapped object, such as out-of-space condition.

The mmap() function shall add an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference shall be removed when there are no more mappings to the file.

The st_atime field of the mapped file may be marked for update at any time between the mmap() call and the corresponding munmap() call. The initial read or write reference to a mapped region shall cause the file's st_atime field to be marked for update if it has not already been marked for update.

The st_ctime and st_mtime fields of a file that is mapped with MAP_SHARED and PROT_WRITE shall be marked for update at some point in the interval between a write reference to the mapped region and the next call to msync() with MS_ASYNC or MS_SYNC for that portion of the file by any process. If there is no such call and if the underlying file is modified as a result of a write reference, then these fields shall be marked for update at some time after the write reference.

There may be implementation-defined limits on the number of memory regions that can be mapped (per process or per system).

If such a limit is imposed, whether the number of memory regions that can be mapped by a process is decreased by the use of shmat() is implementation-defined.

If mmap() fails for reasons other than [EBADF], [EINVAL], or [ENOTSUP], some of the mappings in the address range starting at addr and continuing for len bytes may have been unmapped.

RETURN VALUE

Upon successful completion, the mmap() function shall return the address at which the mapping was placed ( pa); otherwise, it shall return a value of MAP_FAILED and set errno to indicate the error. The symbol MAP_FAILED is defined in the <sys/mman.h> header. No successful return from mmap() shall return the value MAP_FAILED.

ERRORS

The mmap() function shall fail if:

EACCES
The fildes argument is not open for read, regardless of the protection specified, or fildes is not open for write and PROT_WRITE was specified for a MAP_SHARED type mapping.
EAGAIN
The mapping could not be locked in memory, if required by mlockall(), due to a lack of resources.
EBADF
The fildes argument is not a valid open file descriptor.
EINVAL
The addr argument (if MAP_FIXED was specified) or off is not a multiple of the page size as returned by sysconf(), or is considered invalid by the implementation.
EINVAL
The value of flags is invalid (neither MAP_PRIVATE nor MAP_SHARED is set).
EMFILE
The number of mapped regions would exceed an implementation-defined limit (per process or per system).
ENODEV
The fildes argument refers to a file whose type is not supported by mmap().
ENOMEM
MAP_FIXED was specified, and the range [addr,addr+len) exceeds that allowed for the address space of a process; or, if MAP_FIXED was not specified and there is insufficient room in the address space to effect the mapping.
ENOMEM
The mapping could not be locked in memory, if required by mlockall(), because it would require more space than the system is able to supply.
ENOMEM
Not enough unallocated memory resources remain in the typed memory object designated by fildes to allocate len bytes.
ENOTSUP
MAP_FIXED or MAP_PRIVATE was specified in the flags argument and the implementation does not support this functionality.

The implementation does not support the combination of accesses requested in the prot argument.

ENXIO
Addresses in the range [off,off+len) are invalid for the object specified by fildes.
ENXIO
MAP_FIXED was specified in flags and the combination of addr, len, and off is invalid for the object specified by fildes.
ENXIO
The fildes argument refers to a typed memory object that is not accessible from the calling process.
EOVERFLOW
The file is a regular file and the value of off plus len exceeds the offset maximum established in the open file description associated with fildes.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Use of mmap() may reduce the amount of memory available to other memory allocation functions.

Use of MAP_FIXED may result in unspecified behavior in further use of malloc() and shmat(). The use of MAP_FIXED is discouraged, as it may prevent an implementation from making the most effective use of resources.

The application must ensure correct synchronization when using mmap() in conjunction with any other file access method, such as read() and write(), standard input/output, and shmat().

The mmap() function allows access to resources via address space manipulations, instead of read()/ write(). Once a file is mapped, all a process has to do to access it is use the data at the address to which the file was mapped. So, using pseudo-code to illustrate the way in which an existing program might be changed to use mmap(), the following:

fildes = open(...)
lseek(fildes, some_offset)
read(fildes, buf, len)
/* Use data in buf. */

becomes:

fildes = open(...)
address = mmap(0, len, PROT_READ, MAP_PRIVATE, fildes, some_offset)
/* Use data at address. */

RATIONALE

After considering several other alternatives, it was decided to adopt the mmap() definition found in SVR4 for mapping memory objects into process address spaces. The SVR4 definition is minimal, in that it describes only what has been built, and what appears to be necessary for a general and portable mapping facility.

Note that while mmap() was first designed for mapping files, it is actually a general-purpose mapping facility. It can be used to map any appropriate object, such as memory, files, devices, and so on, into the address space of a process.

When a mapping is established, it is possible that the implementation may need to map more than is requested into the address space of the process because of hardware requirements. An application, however, cannot count on this behavior. Implementations that do not use a paged architecture may simply allocate a common memory region and return the address of it; such implementations probably do not allocate any more than is necessary. References past the end of the requested area are unspecified.

If an application requests a mapping that would overlay existing mappings in the process, it might be desirable that an implementation detect this and inform the application. However, the default, portable (not MAP_FIXED) operation does not overlay existing mappings. On the other hand, if the program specifies a fixed address mapping (which requires some implementation knowledge to determine a suitable address, if the function is supported at all), then the program is presumed to be successfully managing its own address space and should be trusted when it asks to map over existing data structures. Furthermore, it is also desirable to make as few system calls as possible, and it might be considered onerous to require an munmap() before an mmap() to the same address range. This volume of IEEE Std 1003.1-2001 specifies that the new mappings replace any existing mappings, following existing practice in this regard.

It is not expected, when the Memory Protection option is supported, that all hardware implementations are able to support all combinations of permissions at all addresses. When this option is supported, implementations are required to disallow write access to mappings without write permission and to disallow access to mappings without any access permission. Other than these restrictions, implementations may allow access types other than those requested by the application. For example, if the application requests only PROT_WRITE, the implementation may also allow read access. A call to mmap() fails if the implementation cannot support allowing all the access requested by the application. For example, some implementations cannot support a request for both write access and execute access simultaneously. All implementations supporting the Memory Protection option must support requests for no access, read access, write access, and both read and write access. Strictly conforming code must only rely on the required checks. These restrictions allow for portability across a wide range of hardware.

The MAP_FIXED address treatment is likely to fail for non-page-aligned values and for certain architecture-dependent address ranges. Conforming implementations cannot count on being able to choose address values for MAP_FIXED without utilizing non-portable, implementation-defined knowledge. Nonetheless, MAP_FIXED is provided as a standard interface conforming to existing practice for utilizing such knowledge when it is available.

Similarly, in order to allow implementations that do not support virtual addresses, support for directly specifying any mapping addresses via MAP_FIXED is not required and thus a conforming application may not count on it.

The MAP_PRIVATE function can be implemented efficiently when memory protection hardware is available. When such hardware is not available, implementations can implement such "mappings" by simply making a real copy of the relevant data into process private memory, though this tends to behave similarly to read().

The function has been defined to allow for many different models of using shared memory. However, all uses are not equally portable across all machine architectures. In particular, the mmap() function allows the system as well as the application to specify the address at which to map a specific region of a memory object. The most portable way to use the function is always to let the system choose the address, specifying NULL as the value for the argument addr and not to specify MAP_FIXED.

If it is intended that a particular region of a memory object be mapped at the same address in a group of processes (on machines where this is even possible), then MAP_FIXED can be used to pass in the desired mapping address. The system can still be used to choose the desired address if the first such mapping is made without specifying MAP_FIXED, and then the resulting mapping address can be passed to subsequent processes for them to pass in via MAP_FIXED. The availability of a specific address range cannot be guaranteed, in general.

The mmap() function can be used to map a region of memory that is larger than the current size of the object. Memory access within the mapping but beyond the current end of the underlying objects may result in SIGBUS signals being sent to the process. The reason for this is that the size of the object can be manipulated by other processes and can change at any moment. The implementation should tell the application that a memory reference is outside the object where this can be detected; otherwise, written data may be lost and read data may not reflect actual data in the object.

Note that references beyond the end of the object do not extend the object as the new end cannot be determined precisely by most virtual memory hardware. Instead, the size can be directly manipulated by ftruncate().

Process memory locking does apply to shared memory regions, and the MEMLOCK_FUTURE argument to mlockall() can be relied upon to cause new shared memory regions to be automatically locked.

Existing implementations of mmap() return the value -1 when unsuccessful. Since the casting of this value to type void * cannot be guaranteed by the ISO C standard to be distinct from a successful value, this volume of IEEE Std 1003.1-2001 defines the symbol MAP_FAILED, which a conforming implementation does not return as the result of a successful call.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fcntl() , fork() , lockf() , msync() , munmap() , mprotect() , posix_typed_mem_open() , shmat() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcscspn(3p)

WCSCSPN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcscspn - get the length of a complementary wide substring

SYNOPSIS

#include <wchar.h>

size_t wcscspn(const wchar_t *ws1, const wchar_t *ws2);

DESCRIPTION

The wcscspn() function shall compute the length (in wide characters) of the maximum initial segment of the wide-character string pointed to by ws1 which consists entirely of wide-character codes not from the wide-character string pointed to by ws2.

RETURN VALUE

The wcscspn() function shall return the length of the initial substring of ws1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcsspn() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


chmod(3p)

CHMOD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

chmod - change mode of a file

SYNOPSIS

#include <sys/stat.h>

int chmod(const char *path, mode_t mode);

DESCRIPTION

The chmod() function shall change S_ISUID, S_ISGID, S_ISVTX, and the file permission bits of the file named by the pathname pointed to by the path argument to the corresponding bits in the mode argument. The application shall ensure that the effective user ID of the process matches the owner of the file or the process has appropriate privileges in order to do this.

S_ISUID, S_ISGID, S_ISVTX, and the file permission bits are described in <sys/stat.h>.

If the calling process does not have appropriate privileges, and if the group ID of the file does not match the effective group ID or one of the supplementary group IDs and if the file is a regular file, bit S_ISGID (set-group-ID on execution) in the file's mode shall be cleared upon successful return from chmod().

Additional implementation-defined restrictions may cause the S_ISUID and S_ISGID bits in mode to be ignored.

The effect on file descriptors for files open at the time of a call to chmod() is implementation-defined.

Upon successful completion, chmod() shall mark for update the st_ctime field of the file.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error. If -1 is returned, no change to the file mode occurs.

ERRORS

The chmod() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOTDIR
A component of the path prefix is not a directory.
ENOENT
A component of path does not name an existing file or path is an empty string.
EPERM
The effective user ID does not match the owner of the file and the process does not have appropriate privileges.
EROFS
The named file resides on a read-only file system.

The chmod() function may fail if:

EINTR
A signal was caught during execution of the function.
EINVAL
The value of the mode argument is invalid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname strings exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Setting Read Permissions for User, Group, and Others

The following example sets read permissions for the owner, group, and others.

#include <sys/stat.h>

const char *path;
...
chmod(path, S_IRUSR|S_IRGRP|S_IROTH);

Setting Read, Write, and Execute Permissions for the Owner Only

The following example sets read, write, and execute permissions for the owner, and no permissions for group and others.

#include <sys/stat.h>

const char *path;
...
chmod(path, S_IRWXU);

Setting Different Permissions for Owner, Group, and Other

The following example sets owner permissions for CHANGEFILE to read, write, and execute, group permissions to read and execute, and other permissions to read.

#include <sys/stat.h>

#define CHANGEFILE "/etc/myfile"
...
chmod(CHANGEFILE, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH);

Setting and Checking File Permissions

The following example sets the file permission bits for a file named /home/cnd/mod1, then calls the stat() function to verify the permissions.

#include <sys/types.h>
#include <sys/stat.h>

int status;
struct stat buffer
...
chmod("home/cnd/mod1", S_IRWXU|S_IRWXG|S_IROTH|S_IWOTH);
status = stat("home/cnd/mod1", &buffer;);

APPLICATION USAGE

In order to ensure that the S_ISUID and S_ISGID bits are set, an application requiring this should use stat() after a successful chmod() to verify this.

Any file descriptors currently open by any process on the file could possibly become invalid if the mode of the file is changed to a value which would deny access to that process. One situation where this could occur is on a stateless file system. This behavior will not occur in a conforming environment.

RATIONALE

This volume of IEEE Std 1003.1-2001 specifies that the S_ISGID bit is cleared by chmod() on a regular file under certain conditions. This is specified on the assumption that regular files may be executed, and the system should prevent users from making executable setgid() files perform with privileges that the caller does not have. On implementations that support execution of other file types, the S_ISGID bit should be cleared for those file types under the same circumstances.

Implementations that use the S_ISUID bit to indicate some other function (for example, mandatory record locking) on non-executable files need not clear this bit on writing. They should clear the bit for executable files and any other cases where the bit grants special powers to processes that change the file contents. Similar comments apply to the S_ISGID bit.

FUTURE DIRECTIONS

None.

SEE ALSO

chown() , mkdir() , mkfifo() , open() , stat() , statvfs() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nanf (3p)

 Continue to this page.


towupper(3p)

TOWUPPER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

towupper - transliterate lowercase wide-character code to uppercase

SYNOPSIS

#include <wctype.h>

wint_t towupper(wint_t wc);

DESCRIPTION

The towupper() function has as a domain a type wint_t, the value of which the application shall ensure is a character representable as a wchar_t, and a wide-character code corresponding to a valid character in the current locale or the value of WEOF. If the argument has any other value, the behavior is undefined. If the argument of towupper() represents a lowercase wide-character code, and there exists a corresponding uppercase wide-character code (as defined by character type information in the program locale category LC_CTYPE ), the result shall be the corresponding uppercase wide-character code. All other arguments in the domain are returned unchanged.

RETURN VALUE

Upon successful completion, towupper() shall return the uppercase letter corresponding to the argument passed. Otherwise, it shall return the argument unchanged.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wctype.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


expf (3p)

 Continue to this page.


nanl (3p)

 Continue to this page.


expl (3p)

 Continue to this page.


getsockopt(3p)

GETSOCKOPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getsockopt - get the socket options

SYNOPSIS

#include <sys/socket.h>

int getsockopt(int socket, int level, int option_name,
void *restrict option_value, socklen_t *restrict option_len);

DESCRIPTION

The getsockopt() function manipulates options associated with a socket.

The getsockopt() function shall retrieve the value for the option specified by the option_name argument for the socket specified by the socket argument. If the size of the option value is greater than option_len, the value stored in the object pointed to by the option_value argument shall be silently truncated. Otherwise, the object pointed to by the option_len argument shall be modified to indicate the actual length of the value.

The level argument specifies the protocol level at which the option resides. To retrieve options at the socket level, specify the level argument as SOL_SOCKET. To retrieve options at other levels, supply the appropriate level identifier for the protocol controlling the option. For example, to indicate that an option is interpreted by the TCP (Transmission Control Protocol), set level to IPPROTO_TCP as defined in the <netinet/in.h> header.

The socket in use may require the process to have appropriate privileges to use the getsockopt() function.

The option_name argument specifies a single option to be retrieved. It can be one of the following values defined in <sys/socket.h>:

SO_DEBUG
Reports whether debugging information is being recorded. This option shall store an int value. This is a Boolean option.
SO_ACCEPTCONN
Reports whether socket listening is enabled. This option shall store an int value. This is a Boolean option.
SO_BROADCAST
Reports whether transmission of broadcast messages is supported, if this is supported by the protocol. This option shall store an int value. This is a Boolean option.
SO_REUSEADDR
Reports whether the rules used in validating addresses supplied to bind() should allow reuse of local addresses, if this is supported by the protocol. This option shall store an int value. This is a Boolean option.
SO_KEEPALIVE
Reports whether connections are kept active with periodic transmission of messages, if this is supported by the protocol.

If the connected socket fails to respond to these messages, the connection shall be broken and threads writing to that socket shall be notified with a SIGPIPE signal. This option shall store an int value. This is a Boolean option.

SO_LINGER
Reports whether the socket lingers on close() if data is present. If SO_LINGER is set, the system blocks the process during close() until it can transmit the data or until the end of the interval indicated by the l_linger member, whichever comes first. If SO_LINGER is not specified, and close() is issued, the system handles the call in a way that allows the process to continue as quickly as possible. This option shall store a linger structure.
SO_OOBINLINE
Reports whether the socket leaves received out-of-band data (data marked urgent) inline. This option shall store an int value. This is a Boolean option.
SO_SNDBUF
Reports send buffer size information. This option shall store an int value.
SO_RCVBUF
Reports receive buffer size information. This option shall store an int value.
SO_ERROR
Reports information about error status and clears it. This option shall store an int value.
SO_TYPE
Reports the socket type. This option shall store an int value. Socket types are described in Socket Types .
SO_DONTROUTE
Reports whether outgoing messages bypass the standard routing facilities. The destination shall be on a directly-connected network, and messages are directed to the appropriate network interface according to the destination address. The effect, if any, of this option depends on what protocol is in use. This option shall store an int value. This is a Boolean option.
SO_RCVLOWAT
Reports the minimum number of bytes to process for socket input operations. The default value for SO_RCVLOWAT is 1. If SO_RCVLOWAT is set to a larger value, blocking receive calls normally wait until they have received the smaller of the low water mark value or the requested amount. (They may return less than the low water mark if an error occurs, a signal is caught, or the type of data next in the receive queue is different from that returned; for example, out-of-band data.) This option shall store an int value. Note that not all implementations allow this option to be retrieved.
SO_RCVTIMEO
Reports the timeout value for input operations. This option shall store a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data was received. The default for this option is zero, which indicates that a receive operation shall not time out. Note that not all implementations allow this option to be retrieved.
SO_SNDLOWAT
Reports the minimum number of bytes to process for socket output operations. Non-blocking output operations shall process no data if flow control does not allow the smaller of the send low water mark value or the entire request to be processed. This option shall store an int value. Note that not all implementations allow this option to be retrieved.
SO_SNDTIMEO
Reports the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent. If a send operation has blocked for this time, it shall return with a partial count or with errno set to [EAGAIN] or [EWOULDBLOCK] if no data was sent. The default for this option is zero, which indicates that a send operation shall not time out. The option shall store a timeval structure. Note that not all implementations allow this option to be retrieved.

For Boolean options, a zero value indicates that the option is disabled and a non-zero value indicates that the option is enabled.

RETURN VALUE

Upon successful completion, getsockopt() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The getsockopt() function shall fail if:

EBADF
The socket argument is not a valid file descriptor.
EINVAL
The specified option is invalid at the specified socket level.
ENOPROTOOPT

The option is not supported by the protocol.

ENOTSOCK
The socket argument does not refer to a socket.

The getsockopt() function may fail if:

EACCES
The calling process does not have the appropriate privileges.
EINVAL
The socket has been shut down.
ENOBUFS
Insufficient resources are available in the system to complete the function.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

bind() , close() , endprotoent() , setsockopt() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>, <netinet/in.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ttyname_r (3p)

 Continue to this page.


cos(3p)

COS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cos, cosf, cosl - cosine function

SYNOPSIS

#include <math.h>

double cos(double x);
float cosf(float x);
long double cosl(long double x);

DESCRIPTION

These functions shall compute the cosine of their argument x, measured in radians.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the cosine of x.

If x is NaN, a NaN shall be returned.

If x is ±0, the value 1.0 shall be returned.

If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is ±Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

Taking the Cosine of a 45-Degree Angle

#include <math.h>
...
double radians = 45 * M_PI / 180;
double result;
...
result = cos(radians);

APPLICATION USAGE

These functions may lose accuracy when their argument is near an odd multiple of pi/2 or is far from 0.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

acos() , feclearexcept() , fetestexcept() , isnan() , sin() , tan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


random(3p)

INITSTATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

initstate, random, setstate, srandom - pseudo-random number functions

SYNOPSIS

#include <stdlib.h>

char *initstate(unsigned seed, char *state,
size_t size);
long random(void);
char *setstate(const char *state);
void srandom(unsigned seed);

DESCRIPTION

The random() function shall use a non-linear additive feedback random-number generator employing a default state array size of 31 long integers to return successive pseudo-random numbers in the range from 0 to 2**31-1. The period of this random-number generator is approximately 16 x (2**31-1). The size of the state array determines the period of the random-number generator. Increasing the state array size shall increase the period.

With 256 bytes of state information, the period of the random-number generator shall be greater than 2**69.

Like rand(), random() shall produce by default a sequence of numbers that can be duplicated by calling srandom() with 1 as the seed.

The srandom() function shall initialize the current state array using the value of seed.

The initstate() and setstate() functions handle restarting and changing random-number generators. The initstate() function allows a state array, pointed to by the state argument, to be initialized for future use. The size argument, which specifies the size in bytes of the state array, shall be used by initstate() to decide what type of random-number generator to use; the larger the state array, the more random the numbers. Values for the amount of state information are 8, 32, 64, 128, and 256 bytes. Other values greater than 8 bytes are rounded down to the nearest one of these values. If initstate() is called with 8<=size<32, then random() shall use a simple linear congruential random number generator. The seed argument specifies a starting point for the random-number sequence and provides for restarting at the same point. The initstate() function shall return a pointer to the previous state information array.

If initstate() has not been called, then random() shall behave as though initstate() had been called with seed=1 and size=128.

Once a state has been initialized, setstate() allows switching between state arrays. The array defined by the state argument shall be used for further random-number generation until initstate() is called or setstate() is called again. The setstate() function shall return a pointer to the previous state array.

RETURN VALUE

If initstate() is called with size less than 8, it shall return NULL.

The random() function shall return the generated pseudo-random number.

The srandom() function shall not return a value.

Upon successful completion, initstate() and setstate() shall return a pointer to the previous state array; otherwise, a null pointer shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

After initialization, a state array can be restarted at a different point in one of two ways:

1.
The initstate() function can be used, with the desired seed, state array, and size of the array.

2.
The setstate() function, with the desired state, can be used, followed by srandom() with the desired seed. The advantage of using both of these functions is that the size of the state array does not have to be saved once it is initialized.

Although some implementations of random() have written messages to standard error, such implementations do not conform to IEEE Std 1003.1-2001.

Issue 5 restored the historical behavior of this function.

Threaded applications should use erand48(), nrand48(), or jrand48() instead of random() when an independent random number sequence in multiple threads is required.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

drand48() , rand() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isunordered(3p)

ISUNORDERED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isunordered - test if arguments are unordered

SYNOPSIS

#include <math.h>

int isunordered(real-floating x, real-floating y);

DESCRIPTION

The isunordered() macro shall determine whether its arguments are unordered.

RETURN VALUE

Upon successful completion, the isunordered() macro shall return 1 if its arguments are unordered, and 0 otherwise.

If x or y is NaN, 0 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values, exactly one of the relationships (less, greater, and equal) is true. Relational operators may raise the invalid floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. This macro is a quiet (non-floating-point exception raising) version of a relational operator. It facilitates writing efficient code that accounts for NaNs without suffering the invalid floating-point exception. In the SYNOPSIS section, real-floating indicates that the argument shall be an expression of real-floating type.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isgreater() , isgreaterequal() , isless() , islessequal() , islessgreater() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_getguardsize(3p)

PTHREAD_ATTR_GETGUARDSIZE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getguardsize, pthread_attr_setguardsize - get and set the thread guardsize attribute

SYNOPSIS

#include <pthread.h>

int pthread_attr_getguardsize(const pthread_attr_t *restrict attr,
size_t *restrict guardsize);
int pthread_attr_setguardsize(pthread_attr_t *attr,
size_t guardsize);

DESCRIPTION

The pthread_attr_getguardsize() function shall get the guardsize attribute in the attr object. This attribute shall be returned in the guardsize parameter.

The pthread_attr_setguardsize() function shall set the guardsize attribute in the attr object. The new value of this attribute shall be obtained from the guardsize parameter. If guardsize is zero, a guard area shall not be provided for threads created with attr. If guardsize is greater than zero, a guard area of at least size guardsize bytes shall be provided for each thread created with attr.

The guardsize attribute controls the size of the guard area for the created thread's stack. The guardsize attribute provides protection against overflow of the stack pointer. If a thread's stack is created with guard protection, the implementation allocates extra memory at the overflow end of the stack as a buffer against stack overflow of the stack pointer. If an application overflows into this buffer an error shall result (possibly in a SIGSEGV signal being delivered to the thread).

A conforming implementation may round up the value contained in guardsize to a multiple of the configurable system variable {PAGESIZE} (see <sys/mman.h>). If an implementation rounds up the value of guardsize to a multiple of {PAGESIZE}, a call to pthread_attr_getguardsize() specifying attr shall store in the guardsize parameter the guard size specified by the previous pthread_attr_setguardsize() function call.

The default value of the guardsize attribute is {PAGESIZE} bytes. The actual value of {PAGESIZE} is implementation-defined.

If the stackaddr or stack attribute has been set (that is, the caller is allocating and managing its own thread stacks), the guardsize attribute shall be ignored and no protection shall be provided by the implementation. It is the responsibility of the application to manage stack overflow along with stack allocation and management in this case.

RETURN VALUE

If successful, the pthread_attr_getguardsize() and pthread_attr_setguardsize() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_attr_getguardsize() and pthread_attr_setguardsize() functions shall fail if:

EINVAL
The attribute attr is invalid.
EINVAL
The parameter guardsize is invalid.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The guardsize attribute is provided to the application for two reasons:

1.
Overflow protection can potentially result in wasted system resources. An application that creates a large number of threads, and which knows its threads never overflow their stack, can save system resources by turning off guard areas.

2.
When threads allocate large data structures on the stack, large guard areas may be needed to detect stack overflow.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutex_lock(3p)

PTHREAD_MUTEX_LOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock - lock and unlock a mutex

SYNOPSIS

#include <pthread.h>

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

DESCRIPTION

The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock(). If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.

If the mutex type is PTHREAD_MUTEX_NORMAL, deadlock detection shall not be provided. Attempting to relock the mutex causes deadlock. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results.

If the mutex type is PTHREAD_MUTEX_ERRORCHECK, then error checking shall be provided. If a thread attempts to relock a mutex that it has already locked, an error shall be returned. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error shall be returned.

If the mutex type is PTHREAD_MUTEX_RECURSIVE, then the mutex shall maintain the concept of a lock count. When a thread successfully acquires a mutex for the first time, the lock count shall be set to one. Every time a thread relocks this mutex, the lock count shall be incremented by one. Each time the thread unlocks the mutex, the lock count shall be decremented by one. When the lock count reaches zero, the mutex shall become available for other threads to acquire. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error shall be returned.

If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behavior. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior. Attempting to unlock the mutex if it is not locked results in undefined behavior.

The pthread_mutex_trylock() function shall be equivalent to pthread_mutex_lock(), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately. If the mutex type is PTHREAD_MUTEX_RECURSIVE and the mutex is currently owned by the calling thread, the mutex lock count shall be incremented by one and the pthread_mutex_trylock() function shall immediately return success.

The pthread_mutex_unlock() function shall release the mutex object referenced by mutex. The manner in which a mutex is released is dependent upon the mutex's type attribute. If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.

(In the case of PTHREAD_MUTEX_RECURSIVE mutexes, the mutex shall become available when the count reaches zero and the calling thread no longer has any locks on this mutex.)

If a signal is delivered to a thread waiting for a mutex, upon return from the signal handler the thread shall resume waiting for the mutex as if it was not interrupted.

RETURN VALUE

If successful, the pthread_mutex_lock() and pthread_mutex_unlock() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

The pthread_mutex_trylock() function shall return zero if a lock on the mutex object referenced by mutex is acquired. Otherwise, an error number is returned to indicate the error.

ERRORS

The pthread_mutex_lock() and pthread_mutex_trylock() functions shall fail if:

EINVAL
The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread's priority is higher than the mutex's current priority ceiling.

The pthread_mutex_trylock() function shall fail if:

EBUSY
The mutex could not be acquired because it was already locked.

The pthread_mutex_lock(), pthread_mutex_trylock(), and pthread_mutex_unlock() functions may fail if:

EINVAL
The value specified by mutex does not refer to an initialized mutex object.
EAGAIN
The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.

The pthread_mutex_lock() function may fail if:

EDEADLK
The current thread already owns the mutex.

The pthread_mutex_unlock() function may fail if:

EPERM
The current thread does not own the mutex.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Mutex objects are intended to serve as a low-level primitive from which other thread synchronization functions can be built. As such, the implementation of mutexes should be as efficient as possible, and this has ramifications on the features available at the interface.

The mutex functions and the particular default settings of the mutex attributes have been motivated by the desire to not preclude fast, inlined implementations of mutex locking and unlocking.

For example, deadlocking on a double-lock is explicitly allowed behavior in order to avoid requiring more overhead in the basic mechanism than is absolutely necessary. (More "friendly" mutexes that detect deadlock or that allow multiple locking by the same thread are easily constructed by the user via the other mechanisms provided. For example, pthread_self() can be used to record mutex ownership.) Implementations might also choose to provide such extended features as options via special mutex attributes.

Since most attributes only need to be checked when a thread is going to be blocked, the use of attributes does not slow the (common) mutex-locking case.

Likewise, while being able to extract the thread ID of the owner of a mutex might be desirable, it would require storing the current thread ID when each mutex is locked, and this could incur unacceptable levels of overhead. Similar arguments apply to a mutex_tryunlock operation.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_mutex_destroy() , pthread_mutex_timedlock() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


unsetenv(3p)

UNSETENV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unsetenv - remove an environment variable

SYNOPSIS

#include <stdlib.h>

int unsetenv(const char *name);

DESCRIPTION

The unsetenv() function shall remove an environment variable from the environment of the calling process. The name argument points to a string, which is the name of the variable to be removed. The named argument shall not contain an '=' character. If the named variable does not exist in the current environment, the environment shall be unchanged and the function is considered to have completed successfully.

If the application modifies environ or the pointers to which it points, the behavior of unsetenv() is undefined. The unsetenv() function shall update the list of pointers to which environ points.

The unsetenv() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, zero shall be returned. Otherwise, -1 shall be returned, errno set to indicate the error, and the environment shall be unchanged.

ERRORS

The unsetenv() function shall fail if:

EINVAL
The name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to the RATIONALE section in setenv() .

FUTURE DIRECTIONS

None.

SEE ALSO

getenv() , setenv() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fpclassify(3p)

FPCLASSIFY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fpclassify - classify real floating type

SYNOPSIS

#include <math.h>

int fpclassify(real-floating x);

DESCRIPTION

The fpclassify() macro shall classify its argument value as NaN, infinite, normal, subnormal, zero, or into another implementation-defined category. First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then classification is based on the type of the argument.

RETURN VALUE

The fpclassify() macro shall return the value of the number classification macro appropriate to the value of its argument.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isfinite() , isinf() , isnan() , isnormal() , signbit() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getservbyport (3p)

 Continue to this page.


pthread_exit(3p)

PTHREAD_EXIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_exit - thread termination

SYNOPSIS

#include <pthread.h>

void pthread_exit(void *value_ptr);

DESCRIPTION

The pthread_exit() function shall terminate the calling thread and make the value value_ptr available to any successful join with the terminating thread. Any cancellation cleanup handlers that have been pushed and not yet popped shall be popped in the reverse order that they were pushed and then executed. After all cancellation cleanup handlers have been executed, if the thread has any thread-specific data, appropriate destructor functions shall be called in an unspecified order. Thread termination does not release any application visible process resources, including, but not limited to, mutexes and file descriptors, nor does it perform any process-level cleanup actions, including, but not limited to, calling any atexit() routines that may exist.

An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value shall serve as the thread's exit status.

The behavior of pthread_exit() is undefined if called from a cancellation cleanup handler or destructor function that was invoked as a result of either an implicit or explicit call to pthread_exit().

After a thread has terminated, the result of access to local (auto) variables of the thread is undefined. Thus, references to local variables of the exiting thread should not be used for the pthread_exit() value_ptr parameter value.

The process shall exit with an exit status of 0 after the last thread has been terminated. The behavior shall be as if the implementation called exit() with a zero argument at thread termination time.

RETURN VALUE

The pthread_exit() function cannot return to its caller.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The normal mechanism by which a thread terminates is to return from the routine that was specified in the pthread_create() call that started it. The pthread_exit() function provides the capability for a thread to terminate without requiring a return from the start routine of that thread, thereby providing a function analogous to exit().

Regardless of the method of thread termination, any cancellation cleanup handlers that have been pushed and not yet popped are executed, and the destructors for any existing thread-specific data are executed. This volume of IEEE Std 1003.1-2001 requires that cancellation cleanup handlers be popped and called in order. After all cancellation cleanup handlers have been executed, thread-specific data destructors are called, in an unspecified order, for each item of thread-specific data that exists in the thread. This ordering is necessary because cancellation cleanup handlers may rely on thread-specific data.

As the meaning of the status is determined by the application (except when the thread has been canceled, in which case it is PTHREAD_CANCELED), the implementation has no idea what an illegal status value is, which is why no address error checking is done.

FUTURE DIRECTIONS

None.

SEE ALSO

exit() , pthread_create() , pthread_join() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


div(3p)

DIV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

div - compute the quotient and remainder of an integer division

SYNOPSIS

#include <stdlib.h>

div_t div(int numer, int denom);

DESCRIPTION

The div() function shall compute the quotient and remainder of the division of the numerator numer by the denominator denom. If the division is inexact, the resulting quotient is the integer of lesser magnitude that is the nearest to the algebraic quotient. If the result cannot be represented, the behavior is undefined; otherwise, quot* denom+ rem shall equal numer.

RETURN VALUE

The div() function shall return a structure of type div_t, comprising both the quotient and the remainder. The structure includes the following members, in any order:

int  quot;  /* quotient */
int  rem;   /* remainder */

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ldiv() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutexattr_destroy (3p)

 Continue to this page.


swab(3p)

SWAB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

swab - swap bytes

SYNOPSIS

#include <unistd.h>

void swab(const void *restrict src, void *restrict dest,
ssize_t nbytes);

DESCRIPTION

The swab() function shall copy nbytes bytes, which are pointed to by src, to the object pointed to by dest, exchanging adjacent bytes. The nbytes argument should be even. If nbytes is odd, swab() copies and exchanges nbytes-1 bytes and the disposition of the last byte is unspecified. If copying takes place between objects that overlap, the behavior is undefined. If nbytes is negative, swab() does nothing.

RETURN VALUE

None.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcswcs(3p)

WCSWCS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcswcs - find a wide substring (LEGACY)

SYNOPSIS

#include <wchar.h>

wchar_t *wcswcs(const wchar_t *ws1, const wchar_t *ws2);

DESCRIPTION

The wcswcs() function shall locate the first occurrence in the wide-character string pointed to by ws1 of the sequence of wide-character codes (excluding the terminating null wide-character code) in the wide-character string pointed to by ws2.

RETURN VALUE

Upon successful completion, wcswcs() shall return a pointer to the located wide-character string or a null pointer if the wide-character string is not found.

If ws2 points to a wide-character string with zero length, the function shall return ws1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

This function was not included in the final ISO/IEC 9899:1990/Amendment 1:1995 (E). Application developers are strongly encouraged to use the wcsstr() function instead.

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

wcschr() , wcsstr() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


putchar(3p)

PUTCHAR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

putchar - put a byte on a stdout stream

SYNOPSIS

#include <stdio.h>

int putchar(int c);

DESCRIPTION

The function call putchar(c) shall be equivalent to putc(c,stdout).

RETURN VALUE

Refer to fputc() .

ERRORS

Refer to fputc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

putc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fflush(3p)

FFLUSH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fflush - flush a stream

SYNOPSIS

#include <stdio.h>

int fflush(FILE *stream);

DESCRIPTION

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() shall cause any unwritten data for that stream to be written to the file, and the st_ctime and st_mtime fields of the underlying file shall be marked for update.

If stream is a null pointer, fflush() shall perform this flushing action on all streams for which the behavior is defined above.

RETURN VALUE

Upon successful completion, fflush() shall return 0; otherwise, it shall set the error indicator for the stream, return EOF, and set errno to indicate the error.

ERRORS

The fflush() function shall fail if:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying stream and the process would be delayed in the write operation.
EBADF
The file descriptor underlying stream is not valid.
EFBIG
An attempt was made to write a file that exceeds the maximum file size.
EFBIG
An attempt was made to write a file that exceeds the process' file size limit.
EFBIG
The file is a regular file and an attempt was made to write at or beyond the offset maximum associated with the corresponding stream.
EINTR
The fflush() function was interrupted by a signal.
EIO
The process is a member of a background process group attempting to write to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the process group of the process is orphaned. This error may also be returned under implementation-defined conditions.
ENOSPC
There was no free space remaining on the device containing the file.
EPIPE
An attempt is made to write to a pipe or FIFO that is not open for reading by any process. A SIGPIPE signal shall also be sent to the thread.

The fflush() function may fail if:

ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The following sections are informative.

EXAMPLES

Sending Prompts to Standard Output

The following example uses printf() calls to print a series of prompts for information the user must enter from standard input. The fflush() calls force the output to standard output. The fflush() function is used because standard output is usually buffered and the prompt may not immediately be printed on the output or terminal. The gets() calls read strings from standard input and place the results in variables, for use later in the program.

#include <stdio.h>
...
char user[100];
char oldpasswd[100];
char newpasswd[100];
...
printf("User name: ");
fflush(stdout);
gets(user);

printf("Old password: ");
fflush(stdout);
gets(oldpasswd);

printf("New password: ");
fflush(stdout);
gets(newpasswd);
...

APPLICATION USAGE

None.

RATIONALE

Data buffered by the system may make determining the validity of the position of the current file descriptor impractical. Thus, enforcing the repositioning of the file descriptor after fflush() on streams open for read() is not mandated by IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

getrlimit() , ulimit() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


feholdexcept(3p)

FEHOLDEXCEPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

feholdexcept - save current floating-point environment

SYNOPSIS

#include <fenv.h>

int feholdexcept(fenv_t *envp);

DESCRIPTION

The feholdexcept() function shall save the current floating-point environment in the object pointed to by envp, clear the floating-point status flags, and then install a non-stop (continue on floating-point exceptions) mode, if available, for all floating-point exceptions.

RETURN VALUE

The feholdexcept() function shall return zero if and only if non-stop floating-point exception handling was successfully installed.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The feholdexcept() function should be effective on typical IEC 60559:1989 standard implementations which have the default non-stop mode and at least one other mode for trap handling or aborting. If the implementation provides only the non-stop mode, then installing the non-stop mode is trivial.

FUTURE DIRECTIONS

None.

SEE ALSO

fegetenv() , fesetenv() , feupdateenv() , the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventset_empty (3p)

 Continue to this page.


dlerror(3p)

DLERROR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dlerror - get diagnostic information

SYNOPSIS

#include <dlfcn.h>

char *dlerror(void);

DESCRIPTION

The dlerror() function shall return a null-terminated character string (with no trailing <newline>) that describes the last error that occurred during dynamic linking processing. If no dynamic linking errors have occurred since the last invocation of dlerror(), dlerror() shall return NULL. Thus, invoking dlerror() a second time, immediately following a prior invocation, shall result in NULL being returned.

The dlerror() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

If successful, dlerror() shall return a null-terminated character string; otherwise, NULL shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following example prints out the last dynamic linking error:

...
#include <dlfcn.h>

char *errstr;

errstr = dlerror();
if (errstr != NULL)
printf ("A dynamic linking error occurred: (%s)\n", errstr);
...

APPLICATION USAGE

The messages returned by dlerror() may reside in a static buffer that is overwritten on each call to dlerror(). Application code should not write to this buffer. Programs wishing to preserve an error message should make their own copies of that message. Depending on the application environment with respect to asynchronous execution events, such as signals or other asynchronous computation sharing the address space, conforming applications should use a critical section to retrieve the error pointer and buffer.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

dlclose() , dlopen() , dlsym() , the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


gcvt (3p)

 Continue to this page.


gethostent(3p)

ENDHOSTENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

endhostent, gethostent, sethostent - network host database functions

SYNOPSIS

#include <netdb.h>

void endhostent(void);
struct hostent *gethostent(void);
void sethostent(int stayopen);

DESCRIPTION

These functions shall retrieve information about hosts. This information is considered to be stored in a database that can be accessed sequentially or randomly. The implementation of this database is unspecified.

Note:
In many cases this database is implemented by the Domain Name System, as documented in RFC 1034, RFC 1035, and RFC 1886.

The sethostent() function shall open a connection to the database and set the next entry for retrieval to the first entry in the database. If the stayopen argument is non-zero, the connection shall not be closed by a call to gethostent(), gethostbyname(), or gethostbyaddr(), and the implementation may maintain an open file descriptor.

The gethostent() function shall read the next entry in the database, opening and closing a connection to the database as necessary.

Entries shall be returned in hostent structures. Refer to gethostbyaddr() for a definition of the hostent structure.

The endhostent() function shall close the connection to the database, releasing any open file descriptor.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, the gethostent() function shall return a pointer to a hostent structure if the requested entry was found, and a null pointer if the end of the database was reached or the requested entry was not found.

ERRORS

No errors are defined for endhostent(), gethostent(), and sethostent().

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The gethostent() function may return pointers to static data, which may be overwritten by subsequent calls to any of these functions.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

endservent() , gethostbyaddr() , the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswcntrl(3p)

ISWCNTRL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswcntrl - test for a control wide-character code

SYNOPSIS

#include <wctype.h>

int iswcntrl(wint_t wc);

DESCRIPTION

The iswcntrl() function shall test whether wc is a wide-character code representing a character of class cntrl in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswcntrl() function shall return non-zero if wc is a control wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fdetach(3p)

FDETACH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fdetach - detach a name from a STREAMS-based file descriptor (STREAMS)

SYNOPSIS

#include <stropts.h>

int fdetach(const char *path);

DESCRIPTION

The fdetach() function shall detach a STREAMS-based file from the file to which it was attached by a previous call to fattach(). The path argument points to the pathname of the attached STREAMS file. The process shall have appropriate privileges or be the owner of the file. A successful call to fdetach() shall cause all pathnames that named the attached STREAMS file to again name the file to which the STREAMS file was attached. All subsequent operations on path shall operate on the underlying file and not on the STREAMS file.

All open file descriptions established while the STREAMS file was attached to the file referenced by path shall still refer to the STREAMS file after the fdetach() has taken effect.

If there are no open file descriptors or other references to the STREAMS file, then a successful call to fdetach() shall be equivalent to performing the last close() on the attached file.

RETURN VALUE

Upon successful completion, fdetach() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The fdetach() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix.
EINVAL
The path argument names a file that is not currently attached.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The size of a pathname exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The effective user ID is not the owner of path and the process does not have appropriate privileges.

The fdetach() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

Detaching a File

The following example detaches the STREAMS-based file /tmp/named-STREAM from the file to which it was attached by a previous, successful call to fattach(). Subsequent calls to open this file refer to the underlying file, not to the STREAMS file.

#include <stropts.h>
...
    char *filename = "/tmp/named-STREAM";
    int ret;

    ret = fdetach(filename);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fattach() , the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_cond_broadcast (3p)

 Continue to this page.


isalnum(3p)

ISALNUM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isalnum - test for an alphanumeric character

SYNOPSIS

#include <ctype.h>

int isalnum(int c);

DESCRIPTION

The isalnum() function shall test whether c is a character of class alpha or digit in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isalnum() function shall return non-zero if c is an alphanumeric character; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalpha() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mq_timedsend (3p)

 Continue to this page.


conjf (3p)

 Continue to this page.


dup(3p)

DUP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dup, dup2 - duplicate an open file descriptor

SYNOPSIS

#include <unistd.h>

int dup(int fildes);
int dup2(int fildes, int fildes2);

DESCRIPTION

The dup() and dup2() functions provide an alternative interface to the service provided by fcntl() using the F_DUPFD command. The call:

fid = dup(fildes);

shall be equivalent to:

fid = fcntl(fildes, F_DUPFD, 0);

The call:

fid = dup2(fildes, fildes2);

shall be equivalent to:

close(fildes2);
fid = fcntl(fildes, F_DUPFD, fildes2);

except for the following:

*
If fildes2 is less than 0 or greater than or equal to {OPEN_MAX}, dup2() shall return -1 with errno set to [EBADF].

*
If fildes is a valid file descriptor and is equal to fildes2, dup2() shall return fildes2 without closing it.

*
If fildes is not a valid file descriptor, dup2() shall return -1 and shall not close fildes2.

*
The value returned shall be equal to the value of fildes2 upon successful completion, or -1 upon failure.

RETURN VALUE

Upon successful completion a non-negative integer, namely the file descriptor, shall be returned; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The dup() function shall fail if:

EBADF
The fildes argument is not a valid open file descriptor.
EMFILE
The number of file descriptors in use by this process would exceed {OPEN_MAX}.

The dup2() function shall fail if:

EBADF
The fildes argument is not a valid open file descriptor or the argument fildes2 is negative or greater than or equal to {OPEN_MAX}.
EINTR
The dup2() function was interrupted by a signal.

The following sections are informative.

EXAMPLES

Redirecting Standard Output to a File

The following example closes standard output for the current processes, re-assigns standard output to go to the file referenced by pfd, and closes the original file descriptor to clean up.

#include <unistd.h>
...
int pfd;
...
close(1);
dup(pfd);
close(pfd);
...

Redirecting Error Messages

The following example redirects messages from stderr to stdout.

#include <unistd.h>
...
dup2(1, 2);
...

APPLICATION USAGE

None.

RATIONALE

The dup() and dup2() functions are redundant. Their services are also provided by the fcntl() function. They have been included in this volume of IEEE Std 1003.1-2001 primarily for historical reasons, since many existing applications use them.

While the brief code segment shown is very similar in behavior to dup2(), a conforming implementation based on other functions defined in this volume of IEEE Std 1003.1-2001 is significantly more complex. Least obvious is the possible effect of a signal-catching function that could be invoked between steps and allocate or deallocate file descriptors. This could be avoided by blocking signals.

The dup2() function is not marked obsolescent because it presents a type-safe version of functionality provided in a type-unsafe version by fcntl(). It is used in the POSIX Ada binding.

The dup2() function is not intended for use in critical regions as a synchronization mechanism.

In the description of [EBADF], the case of fildes being out of range is covered by the given case of fildes not being valid. The descriptions for fildes and fildes2 are different because the only kind of invalidity that is relevant for fildes2 is whether it is out of range; that is, it does not matter whether fildes2 refers to an open file when the dup2() call is made.

FUTURE DIRECTIONS

None.

SEE ALSO

close() , fcntl() , open() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


conjl (3p)

 Continue to this page.


modf(3p)

MODF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

modf, modff, modfl - decompose a floating-point number

SYNOPSIS

#include <math.h>

double modf(double x, double *iptr);
float modff(float value, float *iptr);
long double modfl(long double value, long double *iptr);

DESCRIPTION

These functions shall break the argument x into integral and fractional parts, each of which has the same sign as the argument. It stores the integral part as a double (for the modf() function), a float (for the modff() function), or a long double (for the modfl() function), in the object pointed to by iptr.

RETURN VALUE

Upon successful completion, these functions shall return the signed fractional part of x.

If x is NaN, a NaN shall be returned, and *iptr shall be set to a NaN.

If x is ±Inf, ±0 shall be returned, and *iptr shall be set to ±Inf.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The modf() function computes the function result and *iptr such that:

a = modf(x, iptr) ;
x == a+*iptr ;

allowing for the usual floating-point inaccuracies.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

frexp() , isnan() , ldexp() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


gettimeofday(3p)

GETTIMEOFDAY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gettimeofday - get the date and time

SYNOPSIS

#include <sys/time.h>

int gettimeofday(struct timeval *restrict tp, void *restrict tzp);

DESCRIPTION

The gettimeofday() function shall obtain the current time, expressed as seconds and microseconds since the Epoch, and store it in the timeval structure pointed to by tp. The resolution of the system clock is unspecified.

If tzp is not a null pointer, the behavior is unspecified.

RETURN VALUE

The gettimeofday() function shall return 0 and no value shall be reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ctime() , ftime() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fork(3p)

FORK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fork - create a new process

SYNOPSIS

#include <unistd.h>

pid_t fork(void);

DESCRIPTION

The fork() function shall create a new process. The new process (child process) shall be an exact copy of the calling process (parent process) except as detailed below:

*
The child process shall have a unique process ID.

*
The child process ID also shall not match any active process group ID.

*
The child process shall have a different parent process ID, which shall be the process ID of the calling process.

*
The child process shall have its own copy of the parent's file descriptors. Each of the child's file descriptors shall refer to the same open file description with the corresponding file descriptor of the parent.

*
The child process shall have its own copy of the parent's open directory streams. Each open directory stream in the child process may share directory stream positioning with the corresponding directory stream of the parent.

*
The child process shall have its own copy of the parent's message catalog descriptors.

*
The child process' values of tms_utime, tms_stime, tms_cutime, and tms_cstime shall be set to 0.

*
The time left until an alarm clock signal shall be reset to zero, and the alarm, if any, shall be canceled; see alarm() .

*
All semadj values shall be cleared.

*
File locks set by the parent process shall not be inherited by the child process.

*
The set of signals pending for the child process shall be initialized to the empty set.

*
Interval timers shall be reset in the child process.

*
Any semaphores that are open in the parent process shall also be open in the child process.

*
The child process shall not inherit any address space memory locks established by the parent process via calls to mlockall() or mlock().

*
Memory mappings created in the parent shall be retained in the child process. MAP_PRIVATE mappings inherited from the parent shall also be MAP_PRIVATE mappings in the child, and any modifications to the data in these mappings made by the parent prior to calling fork() shall be visible to the child. Any modifications to the data in MAP_PRIVATE mappings made by the parent after fork() returns shall be visible only to the parent. Modifications to the data in MAP_PRIVATE mappings made by the child shall be visible only to the child.

*
For the SCHED_FIFO and SCHED_RR scheduling policies, the child process shall inherit the policy and priority settings of the parent process during a fork() function. For other scheduling policies, the policy and priority settings on fork() are implementation-defined.

*
Per-process timers created by the parent shall not be inherited by the child process.

*
The child process shall have its own copy of the message queue descriptors of the parent. Each of the message descriptors of the child shall refer to the same open message queue description as the corresponding message descriptor of the parent.

*
No asynchronous input or asynchronous output operations shall be inherited by the child process.

*
A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called. Fork handlers may be established by means of the pthread_atfork() function in order to maintain application invariants across fork() calls.

When the application calls fork() from a signal handler and any of the fork handlers registered by pthread_atfork() calls a function that is not asynch-signal-safe, the behavior is undefined.

*
If the Trace option and the Trace Inherit option are both supported:

If the calling process was being traced in a trace stream that had its inheritance policy set to POSIX_TRACE_INHERITED, the child process shall be traced into that trace stream, and the child process shall inherit the parent's mapping of trace event names to trace event type identifiers. If the trace stream in which the calling process was being traced had its inheritance policy set to POSIX_TRACE_CLOSE_FOR_CHILD, the child process shall not be traced into that trace stream. The inheritance policy is set by a call to the posix_trace_attr_setinherited() function.

*
If the Trace option is supported, but the Trace Inherit option is not supported:

The child process shall not be traced into any of the trace streams of its parent process.

*
If the Trace option is supported, the child process of a trace controller process shall not control the trace streams controlled by its parent process.

*
The initial value of the CPU-time clock of the child process shall be set to zero.

*
The initial value of the CPU-time clock of the single thread of the child process shall be set to zero.

All other process characteristics defined by IEEE Std 1003.1-2001 shall be the same in the parent and child processes. The inheritance of process characteristics not defined by IEEE Std 1003.1-2001 is unspecified by IEEE Std 1003.1-2001.

After fork(), both the parent and the child processes shall be capable of executing independently before either one terminates.

RETURN VALUE

Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process. Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.

ERRORS

The fork() function shall fail if:

EAGAIN
The system lacked the necessary resources to create another process, or the system-imposed limit on the total number of processes under execution system-wide or by a single user {CHILD_MAX} would be exceeded.

The fork() function may fail if:

ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Many historical implementations have timing windows where a signal sent to a process group (for example, an interactive SIGINT) just prior to or during execution of fork() is delivered to the parent following the fork() but not to the child because the fork() code clears the child's set of pending signals. This volume of IEEE Std 1003.1-2001 does not require, or even permit, this behavior. However, it is pragmatic to expect that problems of this nature may continue to exist in implementations that appear to conform to this volume of IEEE Std 1003.1-2001 and pass available verification suites. This behavior is only a consequence of the implementation failing to make the interval between signal generation and delivery totally invisible. From the application's perspective, a fork() call should appear atomic. A signal that is generated prior to the fork() should be delivered prior to the fork(). A signal sent to the process group after the fork() should be delivered to both parent and child. The implementation may actually initialize internal data structures corresponding to the child's set of pending signals to include signals sent to the process group during the fork(). Since the fork() call can be considered as atomic from the application's perspective, the set would be initialized as empty and such signals would have arrived after the fork(); see also <signal.h>.

One approach that has been suggested to address the problem of signal inheritance across fork() is to add an [EINTR] error, which would be returned when a signal is detected during the call. While this is preferable to losing signals, it was not considered an optimal solution. Although it is not recommended for this purpose, such an error would be an allowable extension for an implementation.

The [ENOMEM] error value is reserved for those implementations that detect and distinguish such a condition. This condition occurs when an implementation detects that there is not enough memory to create the process. This is intended to be returned when [EAGAIN] is inappropriate because there can never be enough memory (either primary or secondary storage) to perform the operation. Since fork() duplicates an existing process, this must be a condition where there is sufficient memory for one such process, but not for two. Many historical implementations actually return [ENOMEM] due to temporary lack of memory, a case that is not generally distinct from [EAGAIN] from the perspective of a conforming application.

Part of the reason for including the optional error [ENOMEM] is because the SVID specifies it and it should be reserved for the error condition specified there. The condition is not applicable on many implementations.

IEEE Std 1003.1-1988 neglected to require concurrent execution of the parent and child of fork(). A system that single-threads processes was clearly not intended and is considered an unacceptable "toy implementation" of this volume of IEEE Std 1003.1-2001. The only objection anticipated to the phrase "executing independently" is testability, but this assertion should be testable. Such tests require that both the parent and child can block on a detectable action of the other, such as a write to a pipe or a signal. An interactive exchange of such actions should be possible for the system to conform to the intent of this volume of IEEE Std 1003.1-2001.

The [EAGAIN] error exists to warn applications that such a condition might occur. Whether it occurs or not is not in any practical sense under the control of the application because the condition is usually a consequence of the user's use of the system, not of the application's code. Thus, no application can or should rely upon its occurrence under any circumstances, nor should the exact semantics of what concept of "user" is used be of concern to the application writer. Validation writers should be cognizant of this limitation.

There are two reasons why POSIX programmers call fork(). One reason is to create a new thread of control within the same program (which was originally only possible in POSIX by creating a new process); the other is to create a new process running a different program. In the latter case, the call to fork() is soon followed by a call to one of the exec functions.

The general problem with making fork() work in a multi-threaded world is what to do with all of the threads. There are two alternatives. One is to copy all of the threads into the new process. This causes the programmer or implementation to deal with threads that are suspended on system calls or that might be about to execute system calls that should not be executed in the new process. The other alternative is to copy only the thread that calls fork(). This creates the difficulty that the state of process-local resources is usually held in process memory. If a thread that is not calling fork() holds a resource, that resource is never released in the child process because the thread whose job it is to release the resource does not exist in the child process.

When a programmer is writing a multi-threaded program, the first described use of fork(), creating new threads in the same program, is provided by the pthread_create() function. The fork() function is thus used only to run new programs, and the effects of calling functions that require certain resources between the call to fork() and the call to an exec function are undefined.

The addition of the forkall() function to the standard was considered and rejected. The forkall() function lets all the threads in the parent be duplicated in the child. This essentially duplicates the state of the parent in the child. This allows threads in the child to continue processing and allows locks and the state to be preserved without explicit pthread_atfork() code. The calling process has to ensure that the threads processing state that is shared between the parent and child (that is, file descriptors or MAP_SHARED memory) behaves properly after forkall(). For example, if a thread is reading a file descriptor in the parent when forkall() is called, then two threads (one in the parent and one in the child) are reading the file descriptor after the forkall(). If this is not desired behavior, the parent process has to synchronize with such threads before calling forkall().

While the fork() function is async-signal-safe, there is no way for an implementation to determine whether the fork handlers established by pthread_atfork() are async-signal-safe. The fork handlers may attempt to execute portions of the implementation that are not async-signal-safe, such as those that are protected by mutexes, leading to a deadlock condition. It is therefore undefined for the fork handlers to execute functions that are not async-signal-safe when fork() is called from a signal handler.

When forkall() is called, threads, other than the calling thread, that are in functions that can return with an [EINTR] error may have those functions return [EINTR] if the implementation cannot ensure that the function behaves correctly in the parent and child. In particular, pthread_cond_wait() and pthread_cond_timedwait() need to return in order to ensure that the condition has not changed. These functions can be awakened by a spurious condition wakeup rather than returning [EINTR].

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , exec() , fcntl() , posix_trace_attr_getinherited() , posix_trace_trid_eventid_open() , pthread_atfork() , semop() , signal() , times() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setprotoent (3p)

 Continue to this page.


lfind (3p)

 Continue to this page.


tgammaf (3p)

 Continue to this page.


tgammal (3p)

 Continue to this page.


execle (3p)

 Continue to this page.


mq_open(3p)

MQ_OPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_open - open a message queue (REALTIME)

SYNOPSIS

#include <mqueue.h>

mqd_t mq_open(const char *name, int oflag, ...);

DESCRIPTION

The mq_open() function shall establish the connection between a process and a message queue with a message queue descriptor. It shall create an open message queue description that refers to the message queue, and a message queue descriptor that refers to that open message queue description. The message queue descriptor is used by other functions to refer to that message queue. The name argument points to a string naming a message queue. It is unspecified whether the name appears in the file system and is visible to other functions that take pathnames as arguments. The name argument shall conform to the construction rules for a pathname. If name begins with the slash character, then processes calling mq_open() with the same value of name shall refer to the same message queue object, as long as that name has not been removed. If name does not begin with the slash character, the effect is implementation-defined. The interpretation of slash characters other than the leading slash character in name is implementation-defined. If the name argument is not the name of an existing message queue and creation is not requested, mq_open() shall fail and return an error.

A message queue descriptor may be implemented using a file descriptor, in which case applications can open up to at least {OPEN_MAX} file and message queues.

The oflag argument requests the desired receive and/or send access to the message queue. The requested access permission to receive messages or send messages shall be granted if the calling process would be granted read or write access, respectively, to an equivalently protected file.

The value of oflag is the bitwise-inclusive OR of values from the following list. Applications shall specify exactly one of the first three values (access modes) below in the value of oflag:

O_RDONLY
Open the message queue for receiving messages. The process can use the returned message queue descriptor with mq_receive(), but not mq_send(). A message queue may be open multiple times in the same or different processes for receiving messages.
O_WRONLY
Open the queue for sending messages. The process can use the returned message queue descriptor with mq_send() but not mq_receive(). A message queue may be open multiple times in the same or different processes for sending messages.
O_RDWR
Open the queue for both receiving and sending messages. The process can use any of the functions allowed for O_RDONLY and O_WRONLY. A message queue may be open multiple times in the same or different processes for sending messages.

Any combination of the remaining flags may be specified in the value of oflag:

O_CREAT
Create a message queue. It requires two additional arguments: mode, which shall be of type mode_t, and attr, which shall be a pointer to an mq_attr structure. If the pathname name has already been used to create a message queue that still exists, then this flag shall have no effect, except as noted under O_EXCL. Otherwise, a message queue shall be created without any messages in it. The user ID of the message queue shall be set to the effective user ID of the process, and the group ID of the message queue shall be set to the effective group ID of the process. The file permission bits shall be set to the value of mode. When bits in mode other than file permission bits are set, the effect is implementation-defined. If attr is NULL, the message queue shall be created with implementation-defined default message queue attributes. If attr is non-NULL and the calling process has the appropriate privilege on name, the message queue mq_maxmsg and mq_msgsize attributes shall be set to the values of the corresponding members in the mq_attr structure referred to by attr. If attr is non-NULL, but the calling process does not have the appropriate privilege on name, the mq_open() function shall fail and return an error without creating the message queue.
O_EXCL
If O_EXCL and O_CREAT are set, mq_open() shall fail if the message queue name exists. The check for the existence of the message queue and the creation of the message queue if it does not exist shall be atomic with respect to other threads executing mq_open() naming the same name with O_EXCL and O_CREAT set. If O_EXCL is set and O_CREAT is not set, the result is undefined.
O_NONBLOCK
Determines whether an mq_send() or mq_receive() waits for resources or messages that are not currently available, or fails with errno set to [EAGAIN]; see mq_send() and mq_receive() for details.

The mq_open() function does not add or remove messages from the queue.

RETURN VALUE

Upon successful completion, the function shall return a message queue descriptor; otherwise, the function shall return (mqd_t)-1 and set errno to indicate the error.

ERRORS

The mq_open() function shall fail if:

EACCES
The message queue exists and the permissions specified by oflag are denied, or the message queue does not exist and permission to create the message queue is denied.
EEXIST
O_CREAT and O_EXCL are set and the named message queue already exists.
EINTR
The mq_open() function was interrupted by a signal.
EINVAL
The mq_open() function is not supported for the given name.
EINVAL
O_CREAT was specified in oflag, the value of attr is not NULL, and either mq_maxmsg or mq_msgsize was less than or equal to zero.
EMFILE
Too many message queue descriptors or file descriptors are currently in use by this process.
ENAMETOOLONG
The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
Too many message queues are currently open in the system.
ENOENT
O_CREAT is not set and the named message queue does not exist.
ENOSPC
There is insufficient space for the creation of the new message queue.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_close() , mq_getattr() , mq_receive() , mq_send() , mq_setattr() , mq_timedreceive() , mq_timedsend() , mq_unlink() , msgctl() , msgget() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


erf(3p)

ERF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

erf, erff, erfl - error functions

SYNOPSIS

#include <math.h>

double erf(double x);
float erff(float x);
long double erfl(long double x);

DESCRIPTION

These functions shall compute the error function of their argument x, defined as:

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the value of the error function.

If x is NaN, a NaN shall be returned.

If x is ±0, ±0 shall be returned.

If x is ±Inf, ±1 shall be returned.

If x is subnormal, a range error may occur, and 2 * x/ sqrt(pi) should be returned.

ERRORS

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Underflow occurs when |x| < DBL_MIN * ( sqrt(pi)/2).

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

erfc() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ffs(3p)

FFS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ffs - find first set bit

SYNOPSIS

#include <strings.h>

int ffs(int i);

DESCRIPTION

The ffs() function shall find the first bit set (beginning with the least significant bit) in i, and return the index of that bit. Bits are numbered starting at one (the least significant bit).

RETURN VALUE

The ffs() function shall return the index of the first bit set. If i is 0, then ffs() shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


execlp (3p)

 Continue to this page.


isalpha(3p)

ISALPHA

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isalpha - test for an alphabetic character

SYNOPSIS

#include <ctype.h>

int isalpha(int c);

DESCRIPTION

The isalpha() function shall test whether c is a character of class alpha in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isalpha() function shall return non-zero if c is an alphabetic character; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setsid(3p)

SETSID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setsid - create session and set process group ID

SYNOPSIS

#include <unistd.h>

pid_t setsid(void);

DESCRIPTION

The setsid() function shall create a new session, if the calling process is not a process group leader. Upon return the calling process shall be the session leader of this new session, shall be the process group leader of a new process group, and shall have no controlling terminal. The process group ID of the calling process shall be set equal to the process ID of the calling process. The calling process shall be the only process in the new process group and the only process in the new session.

RETURN VALUE

Upon successful completion, setsid() shall return the value of the new process group ID of the calling process. Otherwise, it shall return (pid_t)-1 and set errno to indicate the error.

ERRORS

The setsid() function shall fail if:

EPERM
The calling process is already a process group leader, or the process group ID of a process other than the calling process matches the process ID of the calling process.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The setsid() function is similar to the setpgrp() function of System V. System V, without job control, groups processes into process groups and creates new process groups via setpgrp(); only one process group may be part of a login session.

Job control allows multiple process groups within a login session. In order to limit job control actions so that they can only affect processes in the same login session, this volume of IEEE Std 1003.1-2001 adds the concept of a session that is created via setsid(). The setsid() function also creates the initial process group contained in the session. Additional process groups can be created via the setpgid() function. A System V process group would correspond to a POSIX System Interfaces session containing a single POSIX process group. Note that this function requires that the calling process not be a process group leader. The usual way to ensure this is true is to create a new process with fork() and have it call setsid(). The fork() function guarantees that the process ID of the new process does not match any existing process group ID.

FUTURE DIRECTIONS

None.

SEE ALSO

getsid() , setpgid() , setpgrp() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_fadvise(3p)

POSIX_FADVISE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_fadvise - file advisory information (ADVANCED REALTIME)

SYNOPSIS

#include <fcntl.h>

int posix_fadvise(int fd, off_t offset, size_t len, int advice);

DESCRIPTION

The posix_fadvise() function shall advise the implementation on the expected behavior of the application with respect to the data in the file associated with the open file descriptor, fd, starting at offset and continuing for len bytes. The specified range need not currently exist in the file. If len is zero, all data following offset is specified. The implementation may use this information to optimize handling of the specified data. The posix_fadvise() function shall have no effect on the semantics of other operations on the specified data, although it may affect the performance of other operations.

The advice to be applied to the data is specified by the advice parameter and may be one of the following values:

POSIX_FADV_NORMAL

Specifies that the application has no advice to give on its behavior with respect to the specified data. It is the default characteristic if no advice is given for an open file.

POSIX_FADV_SEQUENTIAL

Specifies that the application expects to access the specified data sequentially from lower offsets to higher offsets.

POSIX_FADV_RANDOM

Specifies that the application expects to access the specified data in a random order.

POSIX_FADV_WILLNEED

Specifies that the application expects to access the specified data in the near future.

POSIX_FADV_DONTNEED

Specifies that the application expects that it will not access the specified data in the near future.

POSIX_FADV_NOREUSE

Specifies that the application expects to access the specified data once and then not reuse it thereafter.

These values are defined in <fcntl.h>.

RETURN VALUE

Upon successful completion, posix_fadvise() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The posix_fadvise() function shall fail if:

EBADF
The fd argument is not a valid file descriptor.
EINVAL
The value of advice is invalid.
ESPIPE
The fd argument is associated with a pipe or FIFO.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The posix_fadvise() function is part of the Advisory Information option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_madvise() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


perror(3p)

PERROR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

perror - write error messages to standard error

SYNOPSIS

#include <stdio.h>

void perror(const char *s);

DESCRIPTION

The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message, which shall be written to the standard error stream as follows:

*
First (if s is not a null pointer and the character pointed to by s is not the null byte), the string pointed to by s followed by a colon and a <space>.

*
Then an error message string followed by a <newline>.

The contents of the error message strings shall be the same as those returned by strerror() with argument errno.

The perror() function shall mark the file associated with the standard error stream as having been written (st_ctime, st_mtime marked for update) at some time between its successful completion and exit(), abort(), or the completion of fflush() or fclose() on stderr.

The perror() function shall not change the orientation of the standard error stream.

RETURN VALUE

The perror() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Printing an Error Message for a Function

The following example replaces bufptr with a buffer that is the necessary size. If an error occurs, the perror() function prints a message and the program exits.

#include <stdio.h>
#include <stdlib.h>
...
char *bufptr;
size_t szbuf;
...
if ((bufptr = malloc(szbuf)) == NULL) {
    perror("malloc"); exit(2);
}
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strerror() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


regfree (3p)

 Continue to this page.


chown(3p)

CHOWN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

chown - change owner and group of a file

SYNOPSIS

#include <unistd.h>

int chown(const char *path, uid_t owner, gid_t group);

DESCRIPTION

The chown() function shall change the user and group ownership of a file.

The path argument points to a pathname naming a file. The user ID and group ID of the named file shall be set to the numeric values contained in owner and group, respectively.

Only processes with an effective user ID equal to the user ID of the file or with appropriate privileges may change the ownership of a file. If _POSIX_CHOWN_RESTRICTED is in effect for path:

*
Changing the user ID is restricted to processes with appropriate privileges.

*
Changing the group ID is permitted to a process with an effective user ID equal to the user ID of the file, but without appropriate privileges, if and only if owner is equal to the file's user ID or ( uid_t)-1 and group is equal either to the calling process' effective group ID or to one of its supplementary group IDs.

If the specified file is a regular file, one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set, and the process does not have appropriate privileges, the set-user-ID (S_ISUID) and set-group-ID (S_ISGID) bits of the file mode shall be cleared upon successful return from chown(). If the specified file is a regular file, one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set, and the process has appropriate privileges, it is implementation-defined whether the set-user-ID and set-group-ID bits are altered. If the chown() function is successfully invoked on a file that is not a regular file and one or more of the S_IXUSR, S_IXGRP, or S_IXOTH bits of the file mode are set, the set-user-ID and set-group-ID bits may be cleared.

If owner or group is specified as ( uid_t)-1 or ( gid_t)-1, respectively, the corresponding ID of the file shall not be changed. If both owner and group are -1, the times need not be updated.

Upon successful completion, chown() shall mark for update the st_ctime field of the file.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error. If -1 is returned, no changes are made in the user ID and group ID of the file.

ERRORS

The chown() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOTDIR
A component of the path prefix is not a directory.
ENOENT
A component of path does not name an existing file or path is an empty string.
EPERM
The effective user ID does not match the owner of the file, or the calling process does not have appropriate privileges and _POSIX_CHOWN_RESTRICTED indicates that such privilege is required.
EROFS
The named file resides on a read-only file system.

The chown() function may fail if:

EIO
An I/O error occurred while reading or writing to the file system.
EINTR
The chown() function was interrupted by a signal which was caught.
EINVAL
The owner or group ID supplied is not a value supported by the implementation.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Although chown() can be used on some implementations by the file owner to change the owner and group to any desired values, the only portable use of this function is to change the group of a file to the effective GID of the calling process or to a member of its group set.

RATIONALE

System III and System V allow a user to give away files; that is, the owner of a file may change its user ID to anything. This is a serious problem for implementations that are intended to meet government security regulations. Version 7 and 4.3 BSD permit only the superuser to change the user ID of a file. Some government agencies (usually not ones concerned directly with security) find this limitation too confining. This volume of IEEE Std 1003.1-2001 uses may to permit secure implementations while not disallowing System V.

System III and System V allow the owner of a file to change the group ID to anything. Version 7 permits only the superuser to change the group ID of a file. 4.3 BSD permits the owner to change the group ID of a file to its effective group ID or to any of the groups in the list of supplementary group IDs, but to no others.

The POSIX.1-1990 standard requires that the chown() function invoked by a non-appropriate privileged process clear the S_ISGID and the S_ISUID bits for regular files, and permits them to be cleared for other types of files. This is so that changes in accessibility do not accidentally cause files to become security holes. Unfortunately, requiring these bits to be cleared on non-executable data files also clears the mandatory file locking bit (shared with S_ISGID), which is an extension on many implementations (it first appeared in System V). These bits should only be required to be cleared on regular files that have one or more of their execute bits set.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , pathconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


catanhf (3p)

 Continue to this page.


catanhl (3p)

 Continue to this page.


fma(3p)

FMA

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fma, fmaf, fmal - floating-point multiply-add

SYNOPSIS

#include <math.h>

double fma(double x, double y, double z);
float fmaf(float x, float y, float z);
long double fmal(long double x, long double y, long double z);

DESCRIPTION

These functions shall compute (x * y) + z, rounded as one ternary operation: they shall compute the value (as if) to infinite precision and round once to the result format, according to the rounding mode characterized by the value of FLT_ROUNDS.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return (x * y) + z, rounded as one ternary operation.

If x or y are NaN, a NaN shall be returned.

If x multiplied by y is an exact infinity and z is also an infinity but with the opposite sign, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If one of x and y is infinite, the other is zero, and z is not a NaN, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If one of x and y is infinite, the other is zero, and z is a NaN, a NaN shall be returned and a domain error may occur.

If x* y is not 0*Inf nor Inf*0 and z is a NaN, a NaN shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The value of x* y+ z is invalid, or the value x* y is invalid and z is not a NaN.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Domain Error
The value x* y is invalid and z is a NaN.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

In many cases, clever use of floating (fused) multiply-add leads to much improved code; but its unexpected use by the compiler can undermine carefully written code. The FP_CONTRACT macro can be used to disallow use of floating multiply-add; and the fma() function guarantees its use where desired. Many current machines provide hardware floating multiply-add instructions; software implementation can be used for others.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setpriority (3p)

 Continue to this page.


exp(3p)

EXP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

exp, expf, expl - exponential function

SYNOPSIS

#include <math.h>

double exp(double x);
float expf(float x);
long double expl(long double x);

DESCRIPTION

These functions shall compute the base- e exponential of x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the exponential value of x.

If the correct value would cause overflow, a range error shall occur and exp(), expf(), and expl() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0, 1 shall be returned.

If x is -Inf, +0 shall be returned.

If x is +Inf, x shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

ERRORS

These functions shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Note that for IEEE Std 754-1985 double, 709.8 < x implies exp( x) has overflowed. The value x < -708.4 implies exp( x) has underflowed.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , log() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cargf (3p)

 Continue to this page.


vswprintf (3p)

 Continue to this page.


cargl (3p)

 Continue to this page.


sqrtf (3p)

 Continue to this page.


sqrtl (3p)

 Continue to this page.


pthread_rwlockattr_getpshared(3p)

PTHREAD_RWLOCKATTR_GETPSHARED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlockattr_getpshared, pthread_rwlockattr_setpshared - get and set the process-shared attribute of the read-write lock attributes object

SYNOPSIS

#include <pthread.h>

int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *
restrict attr, int *restrict pshared);
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr,
int pshared);

DESCRIPTION

The pthread_rwlockattr_getpshared() function shall obtain the value of the process-shared attribute from the initialized attributes object referenced by attr. The pthread_rwlockattr_setpshared() function shall set the process-shared attribute in an initialized attributes object referenced by attr.

The process-shared attribute shall be set to PTHREAD_PROCESS_SHARED to permit a read-write lock to be operated upon by any thread that has access to the memory where the read-write lock is allocated, even if the read-write lock is allocated in memory that is shared by multiple processes. If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the read-write lock shall only be operated upon by threads created within the same process as the thread that initialized the read-write lock; if threads of differing processes attempt to operate on such a read-write lock, the behavior is undefined. The default value of the process-shared attribute shall be PTHREAD_PROCESS_PRIVATE.

Additional attributes, their default values, and the names of the associated functions to get and set those attribute values are implementation-defined.

RETURN VALUE

Upon successful completion, the pthread_rwlockattr_getpshared() function shall return zero and store the value of the process-shared attribute of attr into the object referenced by the pshared parameter. Otherwise, an error number shall be returned to indicate the error.

If successful, the pthread_rwlockattr_setpshared() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_rwlockattr_getpshared() and pthread_rwlockattr_setpshared() functions may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_rwlockattr_setpshared() function may fail if:

EINVAL
The new value specified for the attribute is outside the range of legal values for that attribute.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_destroy() , pthread_rwlockattr_destroy() , pthread_rwlockattr_init() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


shutdown(3p)

SHUTDOWN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shutdown - shut down socket send and receive operations

SYNOPSIS

#include <sys/socket.h>

int shutdown(int socket, int how);

DESCRIPTION

The shutdown() function shall cause all or part of a full-duplex connection on the socket associated with the file descriptor socket to be shut down.

The shutdown() function takes the following arguments:

socket
Specifies the file descriptor of the socket.
how
Specifies the type of shutdown. The values are as follows:
SHUT_RD
Disables further receive operations.
SHUT_WR
Disables further send operations.
SHUT_RDWR
Disables further send and receive operations.

The shutdown() function disables subsequent send and/or receive operations on a socket, depending on the value of the how argument.

RETURN VALUE

Upon successful completion, shutdown() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The shutdown() function shall fail if:

EBADF
The socket argument is not a valid file descriptor.
EINVAL
The how argument is invalid.
ENOTCONN
The socket is not connected.
ENOTSOCK
The socket argument does not refer to a socket.

The shutdown() function may fail if:

ENOBUFS
Insufficient resources were available in the system to perform the operation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getsockopt() , read() , recv() , recvfrom() , recvmsg() , select() , send() , sendto() , setsockopt() , socket() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getc(3p)

GETC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getc - get a byte from a stream

SYNOPSIS

#include <stdio.h>

int getc(FILE *stream);

DESCRIPTION

The getc() function shall be equivalent to fgetc() , except that if it is implemented as a macro it may evaluate stream more than once, so the argument should never be an expression with side effects.

RETURN VALUE

Refer to fgetc() .

ERRORS

Refer to fgetc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the integer value returned by getc() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined.

Since it may be implemented as a macro, getc() may treat incorrectly a stream argument with side effects. In particular, getc(*f++) does not necessarily work as expected. Therefore, use of this function should be preceded by "#undef getc" in such situations; fgetc() could also be used.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fgetc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


execve (3p)

 Continue to this page.


seteuid(3p)

SETEUID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

seteuid - set effective user ID

SYNOPSIS

#include <unistd.h>

int seteuid(uid_t uid);

DESCRIPTION

If uid is equal to the real user ID or the saved set-user-ID, or if the process has appropriate privileges, seteuid() shall set the effective user ID of the calling process to uid; the real user ID and saved set-user-ID shall remain unchanged.

The seteuid() function shall not affect the supplementary group list in any way.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The seteuid() function shall fail if:

EINVAL
The value of the uid argument is invalid and is not supported by the implementation.
EPERM
The process does not have appropriate privileges and uid does not match the real group ID or the saved set-group-ID.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to the RATIONALE section in setuid() .

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getegid() , geteuid() , getgid() , getuid() , setegid() , setgid() , setregid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventid_equal (3p)

 Continue to this page.


execvp (3p)

 Continue to this page.


gets(3p)

GETS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gets - get a string from a stdin stream

SYNOPSIS

#include <stdio.h>

char *gets(char *s);

DESCRIPTION

The gets() function shall read bytes from the standard input stream, stdin, into the array pointed to by s, until a <newline> is read or an end-of-file condition is encountered. Any <newline> shall be discarded and a null byte shall be placed immediately after the last byte read into the array.

The gets() function may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fread(), getc(), getchar(), gets(), fscanf(), or scanf() using stream that returns data not supplied by a prior call to ungetc().

RETURN VALUE

Upon successful completion, gets() shall return s. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and gets() shall return a null pointer. If a read error occurs, the error indicator for the stream shall be set, gets() shall return a null pointer, and set errno to indicate the error.

ERRORS

Refer to fgetc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.

Since the user cannot specify the length of the buffer passed to gets(), use of this function is discouraged. The length of the string read is unlimited. It is possible to overflow this buffer in such a way as to cause applications to fail, or possible system security violations.

It is recommended that the fgets() function should be used to read input lines.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feof() , ferror() , fgets() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getutxid(3p)

ENDUTXENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

endutxent, getutxent, getutxid, getutxline, pututxline, setutxent - user accounting database functions

SYNOPSIS

#include <utmpx.h>

void endutxent(void);
struct utmpx *getutxent(void);
struct utmpx *getutxid(const struct utmpx *id);
struct utmpx *getutxline(const struct utmpx *line);
struct utmpx *pututxline(const struct utmpx *utmpx);
void setutxent(void);

DESCRIPTION

These functions shall provide access to the user accounting database.

The getutxent() function shall read the next entry from the user accounting database. If the database is not already open, it shall open it. If it reaches the end of the database, it shall fail.

The getutxid() function shall search forward from the current point in the database. If the ut_type value of the utmpx structure pointed to by id is BOOT_TIME, OLD_TIME, or NEW_TIME, then it shall stop when it finds an entry with a matching ut_type value. If the ut_type value is INIT_PROCESS, LOGIN_PROCESS, USER_PROCESS, or DEAD_PROCESS, then it shall stop when it finds an entry whose type is one of these four and whose ut_id member matches the ut_id member of the utmpx structure pointed to by id. If the end of the database is reached without a match, getutxid() shall fail.

The getutxline() function shall search forward from the current point in the database until it finds an entry of the type LOGIN_PROCESS or USER_PROCESS which also has a ut_line value matching that in the utmpx structure pointed to by line. If the end of the database is reached without a match, getutxline() shall fail.

The getutxid() or getutxline() function may cache data. For this reason, to use getutxline() to search for multiple occurrences, the application shall zero out the static data after each success, or getutxline() may return a pointer to the same utmpx structure.

There is one exception to the rule about clearing the structure before further reads are done. The implicit read done by pututxline() (if it finds that it is not already at the correct place in the user accounting database) shall not modify the static structure returned by getutxent(), getutxid(), or getutxline(), if the application has modified this structure and passed the pointer back to pututxline().

For all entries that match a request, the ut_type member indicates the type of the entry. Other members of the entry shall contain meaningful data based on the value of the ut_type member as follows:
ut_type Member | Other Members with Meaningful Data
EMPTY | No others
BOOT_TIME | ut_tv
OLD_TIME | ut_tv
NEW_TIME | ut_tv
USER_PROCESS | ut_id, ut_user (login name of the user), ut_line, ut_pid, ut_tv
INIT_PROCESS | ut_id, ut_pid, ut_tv
LOGIN_PROCESS | ut_id, ut_user (implementation-defined name of the login process), ut_pid, ut_tv
DEAD_PROCESS | ut_id, ut_pid, ut_tv

An implementation that provides extended security controls may impose implementation-defined restrictions on accessing the user accounting database. In particular, the system may deny the existence of some or all of the user accounting database entries associated with users other than the caller.

If the process has appropriate privileges, the pututxline() function shall write out the structure into the user accounting database. It shall use getutxid() to search for a record that satisfies the request. If this search succeeds, then the entry shall be replaced. Otherwise, a new entry shall be made at the end of the user accounting database.

The endutxent() function shall close the user accounting database.

The setutxent() function shall reset the input to the beginning of the database. This should be done before each search for a new entry if it is desired that the entire database be examined.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, getutxent(), getutxid(), and getutxline() shall return a pointer to a utmpx structure containing a copy of the requested entry in the user accounting database. Otherwise, a null pointer shall be returned.

The return value may point to a static area which is overwritten by a subsequent call to getutxid() or getutxline().

Upon successful completion, pututxline() shall return a pointer to a utmpx structure containing a copy of the entry added to the user accounting database. Otherwise, a null pointer shall be returned.

The endutxent() and setutxent() functions shall not return a value.

ERRORS

No errors are defined for the endutxent(), getutxent(), getutxid(), getutxline(), and setutxent() functions.

The pututxline() function may fail if:

EPERM
The process does not have appropriate privileges.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sizes of the arrays in the structure can be found using the sizeof operator.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <utmpx.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ftw(3p)

FTW

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ftw - traverse (walk) a file tree

SYNOPSIS

#include <ftw.h>

int ftw(const char *path, int (*fn)(const char *,
const struct stat *ptr, int flag), int ndirs);

DESCRIPTION

The ftw() function shall recursively descend the directory hierarchy rooted in path. For each object in the hierarchy, ftw() shall call the function pointed to by fn, passing it a pointer to a null-terminated character string containing the name of the object, a pointer to a stat structure containing information about the object, and an integer. Possible values of the integer, defined in the <ftw.h> header, are:

FTW_D
For a directory.
FTW_DNR
For a directory that cannot be read.
FTW_F
For a file.
FTW_SL
For a symbolic link (but see also FTW_NS below).
FTW_NS
For an object other than a symbolic link on which stat() could not successfully be executed. If the object is a symbolic link and stat() failed, it is unspecified whether ftw() passes FTW_SL or FTW_NS to the user-supplied function.

If the integer is FTW_DNR, descendants of that directory shall not be processed. If the integer is FTW_NS, the stat structure contains undefined values. An example of an object that would cause FTW_NS to be passed to the function pointed to by fn would be a file in a directory with read but without execute (search) permission.

The ftw() function shall visit a directory before visiting any of its descendants.

The ftw() function shall use at most one file descriptor for each level in the tree.

The argument ndirs should be in the range [1, {OPEN_MAX}].

The tree traversal shall continue until either the tree is exhausted, an invocation of fn returns a non-zero value, or some error, other than [EACCES], is detected within ftw().

The ndirs argument shall specify the maximum number of directory streams or file descriptors or both available for use by ftw() while traversing the tree. When ftw() returns it shall close any directory streams and file descriptors it uses not counting any opened by the application-supplied fn function.

The results are unspecified if the application-supplied fn function does not preserve the current working directory.

The ftw() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

If the tree is exhausted, ftw() shall return 0. If the function pointed to by fn returns a non-zero value, ftw() shall stop its tree traversal and return whatever value was returned by the function pointed to by fn. If ftw() detects an error, it shall return -1 and set errno to indicate the error.

If ftw() encounters an error other than [EACCES] (see FTW_DNR and FTW_NS above), it shall return -1 and set errno to indicate the error. The external variable errno may contain any error value that is possible when a directory is opened or when one of the stat functions is executed on a directory or file.

ERRORS

The ftw() function shall fail if:

EACCES
Search permission is denied for any component of path or read permission is denied for path.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of path is not a directory.
EOVERFLOW
A field in the stat structure cannot be represented correctly in the current programming environment for one or more files found in the file hierarchy.

The ftw() function may fail if:

EINVAL
The value of the ndirs argument is invalid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

In addition, if the function pointed to by fn encounters system errors, errno may be set accordingly.

The following sections are informative.

EXAMPLES

Walking a Directory Structure

The following example walks the current directory structure, calling the fn function for every directory entry, using at most 10 file descriptors:

#include <ftw.h>
...
if (ftw(".", fn, 10) != 0) {
    perror("ftw"); exit(2);
}

APPLICATION USAGE

The ftw() function may allocate dynamic storage during its operation. If ftw() is forcibly terminated, such as by longjmp() or siglongjmp() being executed by the function pointed to by fn or an interrupt routine, ftw() does not have a chance to free that storage, so it remains permanently allocated. A safe way to handle interrupts is to store the fact that an interrupt has occurred, and arrange to have the function pointed to by fn return a non-zero value at its next invocation.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

longjmp() , lstat() , malloc() , nftw() , opendir() , siglongjmp() , stat() , the Base Definitions volume of IEEE Std 1003.1-2001, <ftw.h>, <sys/stat.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


timer_gettime(3p)

TIMER_GETOVERRUN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

timer_getoverrun, timer_gettime, timer_settime - per-process timers (REALTIME)

SYNOPSIS

#include <time.h>

int timer_getoverrun(timer_t timerid);
int timer_gettime(timer_t timerid, struct itimerspec *value);
int timer_settime(timer_t timerid, int flags,
const struct itimerspec *restrict value,
struct itimerspec *restrict ovalue);

DESCRIPTION

The timer_gettime() function shall store the amount of time until the specified timer, timerid, expires and the reload value of the timer into the space pointed to by the value argument. The it_value member of this structure shall contain the amount of time before the timer expires, or zero if the timer is disarmed. This value is returned as the interval until timer expiration, even if the timer was armed with absolute time. The it_interval member of value shall contain the reload value last set by timer_settime().

The timer_settime() function shall set the time until the next expiration of the timer specified by timerid from the it_value member of the value argument and arm the timer if the it_value member of value is non-zero. If the specified timer was already armed when timer_settime() is called, this call shall reset the time until next expiration to the value specified. If the it_value member of value is zero, the timer shall be disarmed. The effect of disarming or resetting a timer with pending expiration notifications is unspecified.

If the flag TIMER_ABSTIME is not set in the argument flags, timer_settime() shall behave as if the time until next expiration is set to be equal to the interval specified by the it_value member of value. That is, the timer shall expire in it_value nanoseconds from when the call is made. If the flag TIMER_ABSTIME is set in the argument flags, timer_settime() shall behave as if the time until next expiration is set to be equal to the difference between the absolute time specified by the it_value member of value and the current value of the clock associated with timerid. That is, the timer shall expire when the clock reaches the value specified by the it_value member of value. If the specified time has already passed, the function shall succeed and the expiration notification shall be made.

The reload value of the timer shall be set to the value specified by the it_interval member of value. When a timer is armed with a non-zero it_interval, a periodic (or repetitive) timer is specified.

Time values that are between two consecutive non-negative integer multiples of the resolution of the specified timer shall be rounded up to the larger multiple of the resolution. Quantization error shall not cause the timer to expire earlier than the rounded time value.

If the argument ovalue is not NULL, the timer_settime() function shall store, in the location referenced by ovalue, a value representing the previous amount of time before the timer would have expired, or zero if the timer was disarmed, together with the previous timer reload value. Timers shall not expire before their scheduled time.

Only a single signal shall be queued to the process for a given timer at any point in time. When a timer for which a signal is still pending expires, no signal shall be queued, and a timer overrun shall occur. When a timer expiration signal is delivered to or accepted by a process, if the implementation supports the Realtime Signals Extension, the timer_getoverrun() function shall return the timer expiration overrun count for the specified timer. The overrun count returned contains the number of extra timer expirations that occurred between the time the signal was generated (queued) and when it was delivered or accepted, up to but not including an implementation-defined maximum of {DELAYTIMER_MAX}. If the number of such extra expirations is greater than or equal to {DELAYTIMER_MAX}, then the overrun count shall be set to {DELAYTIMER_MAX}. The value returned by timer_getoverrun() shall apply to the most recent expiration signal delivery or acceptance for the timer. If no expiration signal has been delivered for the timer, or if the Realtime Signals Extension is not supported, the return value of timer_getoverrun() is unspecified.

RETURN VALUE

If the timer_getoverrun() function succeeds, it shall return the timer expiration overrun count as explained above.

If the timer_gettime() or timer_settime() functions succeed, a value of 0 shall be returned.

If an error occurs for any of these functions, the value -1 shall be returned, and errno set to indicate the error.

ERRORS

The timer_getoverrun(), timer_gettime(), and timer_settime() functions shall fail if:

EINVAL
The timerid argument does not correspond to an ID returned by timer_create() but not yet deleted by timer_delete().

The timer_settime() function shall fail if:

EINVAL
A value structure specified a nanosecond value less than zero or greater than or equal to 1000 million, and the it_value member of that structure did not specify zero seconds and nanoseconds.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Practical clocks tick at a finite rate, with rates of 100 hertz and 1000 hertz being common. The inverse of this tick rate is the clock resolution, also called the clock granularity, which in either case is expressed as a time duration, being 10 milliseconds and 1 millisecond respectively for these common rates. The granularity of practical clocks implies that if one reads a given clock twice in rapid succession, one may get the same time value twice; and that timers must wait for the next clock tick after the theoretical expiration time, to ensure that a timer never returns too soon. Note also that the granularity of the clock may be significantly coarser than the resolution of the data format used to set and get time and interval values. Also note that some implementations may choose to adjust time and/or interval values to exactly match the ticks of the underlying clock.

This volume of IEEE Std 1003.1-2001 defines functions that allow an application to determine the implementation-supported resolution for the clocks and requires an implementation to document the resolution supported for timers and nanosleep() if they differ from the supported clock resolution. This is more of a procurement issue than a runtime application issue.

FUTURE DIRECTIONS

None.

SEE ALSO

clock_getres() , timer_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strxfrm(3p)

STRXFRM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strxfrm - string transformation

SYNOPSIS

#include <string.h>

size_t strxfrm(char *restrict s1, const char *restrict s2, size_t n);

DESCRIPTION

The strxfrm() function shall transform the string pointed to by s2 and place the resulting string into the array pointed to by s1. The transformation is such that if strcmp() is applied to two transformed strings, it shall return a value greater than, equal to, or less than 0, corresponding to the result of strcoll() applied to the same two original strings. No more than n bytes are placed into the resulting array pointed to by s1, including the terminating null byte. If n is 0, s1 is permitted to be a null pointer. If copying takes place between objects that overlap, the behavior is undefined.

The strxfrm() function shall not change the setting of errno if successful.

Since no return value is reserved to indicate an error, an application wishing to check for error situations should set errno to 0, then call strxfrm(), then check errno.

RETURN VALUE

Upon successful completion, strxfrm() shall return the length of the transformed string (not including the terminating null byte). If the value returned is n or more, the contents of the array pointed to by s1 are unspecified.

On error, strxfrm() may set errno but no return value is reserved to indicate an error.

ERRORS

The strxfrm() function may fail if:

EINVAL
The string pointed to by the s2 argument contains characters outside the domain of the collating sequence.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The transformation function is such that two transformed strings can be ordered by strcmp() as appropriate to collating sequence information in the program's locale (category LC_COLLATE ).

The fact that when n is 0 s1 is permitted to be a null pointer is useful to determine the size of the s1 array prior to making the transformation.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strcmp() , strcoll() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getmsg(3p)

GETMSG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getmsg, getpmsg - receive next message from a STREAMS file (STREAMS)

SYNOPSIS

#include <stropts.h>

int getmsg(int fildes, struct strbuf *restrict ctlptr,
struct strbuf *restrict dataptr, int *restrict flagsp);
int getpmsg(int fildes, struct strbuf *restrict ctlptr,
struct strbuf *restrict dataptr, int *restrict bandp,
int *restrict flagsp);

DESCRIPTION

The getmsg() function shall retrieve the contents of a message located at the head of the STREAM head read queue associated with a STREAMS file and place the contents into one or more buffers. The message contains either a data part, a control part, or both. The data and control parts of the message shall be placed into separate buffers, as described below. The semantics of each part are defined by the originator of the message.

The getpmsg() function shall be equivalent to getmsg(), except that it provides finer control over the priority of the messages received. Except where noted, all requirements on getmsg() also pertain to getpmsg().

The fildes argument specifies a file descriptor referencing a STREAMS-based file.

The ctlptr and dataptr arguments each point to a strbuf structure, in which the buf member points to a buffer in which the data or control information is to be placed, and the maxlen member indicates the maximum number of bytes this buffer can hold. On return, the len member shall contain the number of bytes of data or control information actually received. The len member shall be set to 0 if there is a zero-length control or data part and len shall be set to -1 if no data or control information is present in the message.

When getmsg() is called, flagsp should point to an integer that indicates the type of message the process is able to receive. This is described further below.

The ctlptr argument is used to hold the control part of the message, and dataptr is used to hold the data part of the message. If ctlptr (or dataptr) is a null pointer or the maxlen member is -1, the control (or data) part of the message shall not be processed and shall be left on the STREAM head read queue, and if the ctlptr (or dataptr) is not a null pointer, len shall be set to -1. If the maxlen member is set to 0 and there is a zero-length control (or data) part, that zero-length part shall be removed from the read queue and len shall be set to 0. If the maxlen member is set to 0 and there are more than 0 bytes of control (or data) information, that information shall be left on the read queue and len shall be set to 0. If the maxlen member in ctlptr (or dataptr) is less than the control (or data) part of the message, maxlen bytes shall be retrieved. In this case, the remainder of the message shall be left on the STREAM head read queue and a non-zero return value shall be provided.

By default, getmsg() shall process the first available message on the STREAM head read queue. However, a process may choose to retrieve only high-priority messages by setting the integer pointed to by flagsp to RS_HIPRI. In this case, getmsg() shall only process the next message if it is a high-priority message. When the integer pointed to by flagsp is 0, any available message shall be retrieved. In this case, on return, the integer pointed to by flagsp shall be set to RS_HIPRI if a high-priority message was retrieved, or 0 otherwise.

For getpmsg(), the flags are different. The flagsp argument points to a bitmask with the following mutually-exclusive flags defined: MSG_HIPRI, MSG_BAND, and MSG_ANY. Like getmsg(), getpmsg() shall process the first available message on the STREAM head read queue. A process may choose to retrieve only high-priority messages by setting the integer pointed to by flagsp to MSG_HIPRI and the integer pointed to by bandp to 0. In this case, getpmsg() shall only process the next message if it is a high-priority message. In a similar manner, a process may choose to retrieve a message from a particular priority band by setting the integer pointed to by flagsp to MSG_BAND and the integer pointed to by bandp to the priority band of interest. In this case, getpmsg() shall only process the next message if it is in a priority band equal to, or greater than, the integer pointed to by bandp, or if it is a high-priority message. If a process wants to get the first message off the queue, the integer pointed to by flagsp should be set to MSG_ANY and the integer pointed to by bandp should be set to 0. On return, if the message retrieved was a high-priority message, the integer pointed to by flagsp shall be set to MSG_HIPRI and the integer pointed to by bandp shall be set to 0. Otherwise, the integer pointed to by flagsp shall be set to MSG_BAND and the integer pointed to by bandp shall be set to the priority band of the message.

If O_NONBLOCK is not set, getmsg() and getpmsg() shall block until a message of the type specified by flagsp is available at the front of the STREAM head read queue. If O_NONBLOCK is set and a message of the specified type is not present at the front of the read queue, getmsg() and getpmsg() shall fail and set errno to [EAGAIN].

If a hangup occurs on the STREAM from which messages are retrieved, getmsg() and getpmsg() shall continue to operate normally, as described above, until the STREAM head read queue is empty. Thereafter, they shall return 0 in the len members of ctlptr and dataptr.

RETURN VALUE

Upon successful completion, getmsg() and getpmsg() shall return a non-negative value. A value of 0 indicates that a full message was read successfully. A return value of MORECTL indicates that more control information is waiting for retrieval. A return value of MOREDATA indicates that more data is waiting for retrieval. A return value of the bitwise-logical OR of MORECTL and MOREDATA indicates that both types of information remain. Subsequent getmsg() and getpmsg() calls shall retrieve the remainder of the message. However, if a message of higher priority has come in on the STREAM head read queue, the next call to getmsg() or getpmsg() shall retrieve that higher-priority message before retrieving the remainder of the previous message.

If the high priority control part of the message is consumed, the message shall be placed back on the queue as a normal message of band 0. Subsequent getmsg() and getpmsg() calls shall retrieve the remainder of the message. If, however, a priority message arrives or already exists on the STREAM head, the subsequent call to getmsg() or getpmsg() shall retrieve the higher-priority message before retrieving the remainder of the message that was put back.

Upon failure, getmsg() and getpmsg() shall return -1 and set errno to indicate the error.

ERRORS

The getmsg() and getpmsg() functions shall fail if:

EAGAIN
The O_NONBLOCK flag is set and no messages are available.
EBADF
The fildes argument is not a valid file descriptor open for reading.
EBADMSG
The queued message to be read is not valid for getmsg() or getpmsg() or a pending file descriptor is at the STREAM head.
EINTR
A signal was caught during getmsg() or getpmsg().
EINVAL
An illegal value was specified by flagsp, or the STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer.
ENOSTR
A STREAM is not associated with fildes.

In addition, getmsg() and getpmsg() shall fail if the STREAM head had processed an asynchronous error before the call. In this case, the value of errno does not reflect the result of getmsg() or getpmsg() but reflects the prior error.

The following sections are informative.

EXAMPLES

Getting Any Message

In the following example, the value of fd is assumed to refer to an open STREAMS file. The call to getmsg() retrieves any available message on the associated STREAM-head read queue, returning control and data information to the buffers pointed to by ctrlbuf and databuf, respectively.

#include <stropts.h>
...
int fd;
char ctrlbuf[128];
char databuf[512];
struct strbuf ctrl;
struct strbuf data;
int flags = 0;
int ret;

ctrl.buf = ctrlbuf;
ctrl.maxlen = sizeof(ctrlbuf);

data.buf = databuf;
data.maxlen = sizeof(databuf);

ret = getmsg (fd, &ctrl, &data, &flags);

Getting the First Message off the Queue

In the following example, the call to getpmsg() retrieves the first available message on the associated STREAM-head read queue.

#include <stropts.h>
...

int fd;
char ctrlbuf[128];
char databuf[512];
struct strbuf ctrl;
struct strbuf data;
int band = 0;
int flags = MSG_ANY;
int ret;

ctrl.buf = ctrlbuf;
ctrl.maxlen = sizeof(ctrlbuf);

data.buf = databuf;
data.maxlen = sizeof(databuf);

ret = getpmsg (fd, &ctrl, &data, &band, &flags);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

STREAMS , poll() , putmsg() , read() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getitimer(3p)

GETITIMER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getitimer, setitimer - get and set value of interval timer

SYNOPSIS

#include <sys/time.h>

int getitimer(int which, struct itimerval *value);
int setitimer(int which, const struct itimerval *restrict value,
struct itimerval *restrict ovalue);

DESCRIPTION

The getitimer() function shall store the current value of the timer specified by which into the structure pointed to by value. The setitimer() function shall set the timer specified by which to the value specified in the structure pointed to by value, and if ovalue is not a null pointer, store the previous value of the timer in the structure pointed to by ovalue.

A timer value is defined by the itimerval structure, specified in <sys/time.h>. If it_value is non-zero, it shall indicate the time to the next timer expiration. If it_interval is non-zero, it shall specify a value to be used in reloading it_value when the timer expires. Setting it_value to 0 shall disable a timer, regardless of the value of it_interval. Setting it_interval to 0 shall disable a timer after its next expiration (assuming it_value is non-zero).

Implementations may place limitations on the granularity of timer values. For each interval timer, if the requested timer value requires a finer granularity than the implementation supports, the actual timer value shall be rounded up to the next supported value.

An XSI-conforming implementation provides each process with at least three interval timers, which are indicated by the which argument:

ITIMER_REAL
Decrements in real time. A SIGALRM signal is delivered when this timer expires.
ITIMER_VIRTUAL
Decrements in process virtual time. It runs only when the process is executing. A SIGVTALRM signal is delivered when it expires.
ITIMER_PROF
Decrements both in process virtual time and when the system is running on behalf of the process. It is designed to be used by interpreters in statistically profiling the execution of interpreted programs. Each time the ITIMER_PROF timer expires, the SIGPROF signal is delivered.

The interaction between setitimer() and any of alarm(), sleep(), or usleep() is unspecified.

RETURN VALUE

Upon successful completion, getitimer() or setitimer() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The setitimer() function shall fail if:

EINVAL
The value argument is not in canonical form. (In canonical form, the number of microseconds is a non-negative integer less than 1000000 and the number of seconds is a non-negative integer.)

The getitimer() and setitimer() functions may fail if:

EINVAL
The which argument is not recognized.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , sleep() , timer_getoverrun() , ualarm() , usleep() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <sys/time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sync(3p)

SYNC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sync - schedule file system updates

SYNOPSIS

#include <unistd.h>

void sync(void);

DESCRIPTION

The sync() function shall cause all information in memory that updates file systems to be scheduled for writing out to all file systems.

The writing, although scheduled, is not necessarily complete upon return from sync().

RETURN VALUE

The sync() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fsync() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


free(3p)

FREE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

free - free allocated memory

SYNOPSIS

#include <stdlib.h>

void free(void *ptr);

DESCRIPTION

The free() function shall cause the space pointed to by ptr to be deallocated; that is, made available for further allocation. If ptr is a null pointer, no action shall occur. Otherwise, if the argument does not match a pointer earlier returned by the calloc(), malloc(), posix_memalign(), realloc(), or strdup() function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

Any use of a pointer that refers to freed space results in undefined behavior.

RETURN VALUE

The free() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

There is now no requirement for the implementation to support the inclusion of <malloc.h>.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

calloc() , malloc() , realloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_clear(3p)

POSIX_TRACE_CLEAR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_clear - clear trace stream and trace log (TRACING)

SYNOPSIS

#include <sys/types.h>
#include <trace.h>

int posix_trace_clear(trace_id_t trid);

DESCRIPTION

The posix_trace_clear() function shall reinitialize the trace stream identified by the argument trid as if it were returning from the posix_trace_create() function, except that the same allocated resources shall be reused, the mapping of trace event type identifiers to trace event names shall be unchanged, and the trace stream status shall remain unchanged (that is, if it was running, it remains running and if it was suspended, it remains suspended).

All trace events in the trace stream recorded before the call to posix_trace_clear() shall be lost. The posix_stream_full_status status shall be set to POSIX_TRACE_NOT_FULL. There is no guarantee that all trace events that occurred during the posix_trace_clear() call are recorded; the behavior with respect to trace points that may occur during this call is unspecified.

If the Trace Log option is supported and the trace stream has been created with a log, the posix_trace_clear() function shall reinitialize the trace stream with the same behavior as if the trace stream was created without the log, plus it shall reinitialize the trace log associated with the trace stream identified by the argument trid as if it were returning from the posix_trace_create_withlog() function, except that the same allocated resources, for the trace log, may be reused and the associated trace stream status remains unchanged. The first trace event recorded in the trace log after the call to posix_trace_clear() shall be the same as the first trace event recorded in the active trace stream after the call to posix_trace_clear(). The posix_log_full_status status shall be set to POSIX_TRACE_NOT_FULL. There is no guarantee that all trace events that occurred during the posix_trace_clear() call are recorded in the trace log; the behavior with respect to trace points that may occur during this call is unspecified. If the log full policy is POSIX_TRACE_APPEND, the effect of a call to this function is unspecified for the trace log associated with the trace stream identified by the trid argument.

RETURN VALUE

Upon successful completion, the posix_trace_clear() function shall return a value of zero. Otherwise, it shall return the corresponding error number.

ERRORS

The posix_trace_clear() function shall fail if:

EINVAL
The value of the trid argument does not correspond to an active trace stream.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_attr_init() , posix_trace_create() , posix_trace_flush() , posix_trace_get_attr() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


va_arg(3p)

VA_ARG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

va_arg, va_copy, va_end, va_start - handle variable argument list

SYNOPSIS

#include <stdarg.h>

type va_arg(va_list ap, type);
void va_copy(va_list dest, va_list src);
void va_end(va_list ap);
void va_start(va_list ap, argN);

DESCRIPTION

Refer to the Base Definitions volume of IEEE Std 1003.1-2001, <stdarg.h>.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wscanf(3p)

FWSCANF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fwscanf, swscanf, wscanf - convert formatted wide-character input

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

int fwscanf(FILE *restrict stream, const wchar_t *restrict format, ... );
int swscanf(const wchar_t *restrict ws,
const wchar_t *restrict format, ... );
int wscanf(const wchar_t *restrict format, ... );

DESCRIPTION

The fwscanf() function shall read from the named input stream. The wscanf() function shall read from the standard input stream stdin. The swscanf() function shall read from the wide-character string ws. Each function reads wide characters, interprets them according to a format, and stores the results in its arguments. Each expects, as arguments, a control wide-character string format described below, and a set of pointer arguments indicating where the converted input should be stored. The result is undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments are evaluated but are otherwise ignored.

Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier wide character % (see below) is replaced by the sequence "%n$" , where n is a decimal integer in the range [1,{NL_ARGMAX}]. This feature provides for the definition of format wide-character strings that select arguments in an order appropriate to specific languages. In format wide-character strings containing the "%n$" form of conversion specifications, it is unspecified whether numbered arguments in the argument list can be referenced from the format wide-character string more than once.

The format can contain either form of a conversion specification-that is, % or "%n$"- but the two forms cannot normally be mixed within a single format wide-character string. The only exception to this is that %% or %* can be mixed with the "%n$" form. When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the ( N-1)th, are pointers.

The fwscanf() function in all its forms allows for detection of a language-dependent radix character in the input string, encoded as a wide-character value. The radix character is defined in the program's locale (category LC_NUMERIC ). In the POSIX locale, or in a locale where the radix character is not defined, the radix character shall default to a period ( '.' ).

The format is a wide-character string composed of zero or more directives. Each directive is composed of one of the following: one or more white-space wide characters ( <space>s, <tab>s, <newline>s, <vertical-tab>s, or <form-feed>s); an ordinary wide character (neither '%' nor a white-space character); or a conversion specification. Each conversion specification is introduced by a '%' or the sequence "%n$" after which the following appear in sequence:

*
An optional assignment-suppressing character '*' .

*
An optional non-zero decimal integer that specifies the maximum field width.

*
An optional length modifier that specifies the size of the receiving object.

*
A conversion specifier wide character that specifies the type of conversion to be applied. The valid conversion specifiers are described below.

The fwscanf() functions shall execute each directive of the format in turn. If a directive fails, as detailed below, the function shall return. Failures are described as input failures (due to the unavailability of input bytes) or matching failures (due to inappropriate input).

A directive composed of one or more white-space wide characters is executed by reading input until no more valid input can be read, or up to the first wide character which is not a white-space wide character, which remains unread.

A directive that is an ordinary wide character shall be executed as follows. The next wide character is read from the input and compared with the wide character that comprises the directive; if the comparison shows that they are not equivalent, the directive shall fail, and the differing and subsequent wide characters remain unread. Similarly, if end-of-file, an encoding error, or a read error prevents a wide character from being read, the directive shall fail.

A directive that is a conversion specification defines a set of matching input sequences, as described below for each conversion wide character. A conversion specification is executed in the following steps.

Input white-space wide characters (as specified by iswspace() ) shall be skipped, unless the conversion specification includes a [ , c , or n conversion specifier.

An item shall be read from the input, unless the conversion specification includes an n conversion specifier wide character. An input item is defined as the longest sequence of input wide characters, not exceeding any specified field width, which is an initial subsequence of a matching sequence. The first wide character, if any, after the input item shall remain unread. If the length of the input item is zero, the execution of the conversion specification shall fail; this condition is a matching failure, unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.

Except in the case of a % conversion specifier, the input item (or, in the case of a %n conversion specification, the count of input wide characters) shall be converted to a type appropriate to the conversion wide character. If the input item is not a matching sequence, the execution of the conversion specification shall fail; this condition is a matching failure. Unless assignment suppression was indicated by a '*' , the result of the conversion shall be placed in the object pointed to by the first argument following the format argument that has not already received a conversion result if the conversion specification is introduced by % , or in the nth argument if introduced by the wide-character sequence "%n$". If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the space provided, the behavior is undefined.

The length modifiers and their meanings are:

hh
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to signed char or unsigned char.
h
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.
l (ell)
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to long or unsigned long; that a following a , A , e , E , f , F , g , or G conversion specifier applies to an argument with type pointer to double; or that a following c , s , or [ conversion specifier applies to an argument with type pointer to wchar_t.
ll (ell-ell)

Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to long long or unsigned long long.

j
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to intmax_t or uintmax_t.
z
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to size_t or the corresponding signed integer type.
t
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to ptrdiff_t or the corresponding unsigned type.
L
Specifies that a following a , A , e , E , f , F , g , or G conversion specifier applies to an argument with type pointer to long double.

If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.

The following conversion specifier wide characters are valid:

d
Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of wcstol() with the value 10 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to int.
i
Matches an optionally signed integer, whose format is the same as expected for the subject sequence of wcstol() with 0 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to int.
o
Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence of wcstoul() with the value 8 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to unsigned.
u
Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of wcstoul() with the value 10 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to unsigned.
x
Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of wcstoul() with the value 16 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to unsigned.
a, e, f, g

Matches an optionally signed floating-point number, infinity, or NaN whose format is the same as expected for the subject sequence of wcstod(). In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to float.

If the fwprintf() family of functions generates character string representations for infinity and NaN (a symbolic entity encoded in floating-point format) to support IEEE Std 754-1985, the fwscanf() family of functions shall recognize them as input.

s
Matches a sequence of non white-space wide characters. If no l (ell) qualifier is present, characters from the input field shall be converted as if by repeated calls to the wcrtomb() function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted. The application shall ensure that the corresponding argument is a pointer to a character array large enough to accept the sequence and the terminating null character, which shall be added automatically.

Otherwise, the application shall ensure that the corresponding argument is a pointer to an array of wchar_t large enough to accept the sequence and the terminating null wide character, which shall be added automatically.

[
Matches a non-empty sequence of wide characters from a set of expected wide characters (the scanset). If no l (ell) qualifier is present, wide characters from the input field shall be converted as if by repeated calls to the wcrtomb() function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted. The application shall ensure that the corresponding argument is a pointer to a character array large enough to accept the sequence and the terminating null character, which shall be added automatically.

If an l (ell) qualifier is present, the application shall ensure that the corresponding argument is a pointer to an array of wchar_t large enough to accept the sequence and the terminating null wide character, which shall be added automatically.

The conversion specification includes all subsequent wide characters in the format string up to and including the matching right square bracket ( ']' ). The wide characters between the square brackets (the scanlist) comprise the scanset, unless the wide character after the left square bracket is a circumflex ( '^' ), in which case the scanset contains all wide characters that do not appear in the scanlist between the circumflex and the right square bracket. If the conversion specification begins with "[]" or "[^]" , the right square bracket is included in the scanlist and the next right square bracket is the matching right square bracket that ends the conversion specification; otherwise, the first right square bracket is the one that ends the conversion specification. If a '-' is in the scanlist and is not the first wide character, nor the second where the first wide character is a '^' , nor the last wide character, the behavior is implementation-defined.

c
Matches a sequence of wide characters of exactly the number specified by the field width (1 if no field width is present in the conversion specification).

If no l (ell) length modifier is present, characters from the input field shall be converted as if by repeated calls to the wcrtomb() function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted. The corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence. No null character is added.

If an l (ell) length modifier is present, the corresponding argument shall be a pointer to the initial element of an array of wchar_t large enough to accept the sequence. No null wide character is added.

Otherwise, the application shall ensure that the corresponding argument is a pointer to an array of wchar_t large enough to accept the sequence. No null wide character is added.

p
Matches an implementation-defined set of sequences, which shall be the same as the set of sequences that is produced by the %p conversion specification of the corresponding fwprintf() functions. The application shall ensure that the corresponding argument is a pointer to a pointer to void. The interpretation of the input item is implementation-defined. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise, the behavior of the %p conversion is undefined.
n
No input is consumed. The application shall ensure that the corresponding argument is a pointer to the integer into which is to be written the number of wide characters read from the input so far by this call to the fwscanf() functions. Execution of a %n conversion specification shall not increment the assignment count returned at the completion of execution of the function. No argument shall be converted, but one shall be consumed. If the conversion specification includes an assignment-suppressing wide character or a field width, the behavior is undefined.
C
Equivalent to lc .
S
Equivalent to ls .
%
Matches a single '%' wide character; no conversion or assignment shall occur. The complete conversion specification shall be %% .

If a conversion specification is invalid, the behavior is undefined.

The conversion specifiers A , E , F , G , and X are also valid and shall be equivalent to, respectively, a , e , f , g , and x .

If end-of-file is encountered during input, conversion is terminated. If end-of-file occurs before any wide characters matching the current conversion specification (except for %n ) have been read (other than leading white-space, where permitted), execution of the current conversion specification shall terminate with an input failure. Otherwise, unless execution of the current conversion specification is terminated with a matching failure, execution of the following conversion specification (if any) shall be terminated with an input failure.

Reaching the end of the string in swscanf() shall be equivalent to encountering end-of-file for fwscanf().

If conversion terminates on a conflicting input, the offending input shall be left unread in the input. Any trailing white space (including <newline>) shall be left unread unless matched by a conversion specification. The success of literal matches and suppressed assignments is only directly determinable via the %n conversion specification.

The fwscanf() and wscanf() functions may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgetwc(), fgets(), fgetws(), fread(), getc(), getwc(), getchar(), getwchar(), gets(), fscanf(), or fwscanf() using stream that returns data not supplied by a prior call to ungetc().

RETURN VALUE

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set to indicate the error.

ERRORS

For the conditions under which the fwscanf() functions shall fail and may fail, refer to fgetwc() .

In addition, fwscanf() may fail if:

EILSEQ
Input byte sequence does not form a valid character.
EINVAL
There are insufficient arguments.

The following sections are informative.

EXAMPLES

The call:

int i, n; float x; char name[50];
n = wscanf(L"%d%f%s", &i, &x, name);

with the input line:

25 54.32E-1 Hamster

assigns to n the value 3, to i the value 25, to x the value 5.432, and name contains the string "Hamster" .

The call:

int i; float x; char name[50];
(void) wscanf(L"%2d%f%*d %[0123456789]", &i, &x, name);

with input:

56789 0123 56a72

assigns 56 to i, 789.0 to x, skips 0123, and places the string "56\0" in name. The next call to getchar() shall return the character 'a' .

APPLICATION USAGE

In format strings containing the '%' form of conversion specifications, each argument in the argument list is used exactly once.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getwc() , fwprintf() , setlocale() , wcstod() , wcstol() , wcstoul() , wcrtomb() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <langinfo.h>, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getwc(3p)

GETWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getwc - get a wide character from a stream

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

wint_t getwc(FILE *stream);

DESCRIPTION

The getwc() function shall be equivalent to fgetwc(), except that if it is implemented as a macro it may evaluate stream more than once, so the argument should never be an expression with side effects.

RETURN VALUE

Refer to fgetwc() .

ERRORS

Refer to fgetwc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Since it may be implemented as a macro, getwc() may treat incorrectly a stream argument with side effects. In particular, getwc(*f++) does not necessarily work as expected. Therefore, use of this function is not recommended; fgetwc() should be used instead.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fgetwc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getwd(3p)

GETWD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getwd - get the current working directory pathname (LEGACY)

SYNOPSIS

#include <unistd.h>

char *getwd(char *path_name);

DESCRIPTION

The getwd() function shall determine an absolute pathname of the current working directory of the calling process, and copy a string containing that pathname into the array pointed to by the path_name argument.

If the length of the pathname of the current working directory is greater than ({PATH_MAX}+1) including the null byte, getwd() shall fail and return a null pointer.

RETURN VALUE

Upon successful completion, a pointer to the string containing the absolute pathname of the current working directory shall be returned. Otherwise, getwd() shall return a null pointer and the contents of the array pointed to by path_name are undefined.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

For applications portability, the getcwd() function should be used to determine the current working directory instead of getwd().

RATIONALE

Since the user cannot specify the length of the buffer passed to getwd(), use of this function is discouraged. The length of a pathname described in {PATH_MAX} is file system-dependent and may vary from one mount point to another, or might even be unlimited. It is possible to overflow this buffer in such a way as to cause applications to fail, or possible system security violations.

It is recommended that the getcwd() function should be used to determine the current working directory.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

getcwd() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lcong48 (3p)

 Continue to this page.


getgrent(3p)

ENDGRENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

endgrent, getgrent, setgrent - group database entry functions

SYNOPSIS

#include <grp.h>

void endgrent(void);
struct group *getgrent(void);
void setgrent(void);

DESCRIPTION

The getgrent() function shall return a pointer to a structure containing the broken-out fields of an entry in the group database. When first called, getgrent() shall return a pointer to a group structure containing the first entry in the group database. Thereafter, it shall return a pointer to a group structure containing the next group structure in the group database, so successive calls may be used to search the entire database.

An implementation that provides extended security controls may impose further implementation-defined restrictions on accessing the group database. In particular, the system may deny the existence of some or all of the group database entries associated with groups other than those groups associated with the caller and may omit users other than the caller from the list of members of groups in database entries that are returned.

The setgrent() function shall rewind the group database to allow repeated searches.

The endgrent() function may be called to close the group database when processing is complete.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

When first called, getgrent() shall return a pointer to the first group structure in the group database. Upon subsequent calls it shall return the next group structure in the group database. The getgrent() function shall return a null pointer on end-of-file or an error and errno may be set to indicate the error.

The return value may point to a static area which is overwritten by a subsequent call to getgrgid(), getgrnam(), or getgrent().

ERRORS

The getgrent() function may fail if:

EINTR
A signal was caught during the operation.
EIO
An I/O error has occurred.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are provided due to their historical usage. Applications should avoid dependencies on fields in the group database, whether the database is a single file, or where in the file system name space the database resides. Applications should use getgrnam() and getgrgid() whenever possible because it avoids these dependencies.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getgrgid() , getgrnam() , getlogin() , getpwent() , the Base Definitions volume of IEEE Std 1003.1-2001, <grp.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


swapcontext (3p)

 Continue to this page.


casin(3p)

CASIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

casin, casinf, casinl - complex arc sine functions

SYNOPSIS

#include <complex.h>

double complex casin(double complex z);
float complex casinf(float complex z);
long double complex casinl(long double complex z);

DESCRIPTION

These functions shall compute the complex arc sine of z, with branch cuts outside the interval [-1, +1] along the real axis.

RETURN VALUE

These functions shall return the complex arc sine value, in the range of a strip mathematically unbounded along the imaginary axis and in the interval [-pi/2, +pi/2] along the real axis.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

csin() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lstat(3p)

LSTAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lstat - get symbolic link status

SYNOPSIS

#include <sys/stat.h>

int lstat(const char *restrict path, struct stat *restrict buf);

DESCRIPTION

The lstat() function shall be equivalent to stat(), except when path refers to a symbolic link. In that case lstat() shall return information about the link, while stat() shall return information about the file the link references.

For symbolic links, the st_mode member shall contain meaningful information when used with the file type macros, and the st_size member shall contain the length of the pathname contained in the symbolic link. File mode bits and the contents of the remaining members of the stat structure are unspecified. The value returned in the st_size member is the length of the contents of the symbolic link, and does not count any trailing null.

RETURN VALUE

Upon successful completion, lstat() shall return 0. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The lstat() function shall fail if:

EACCES
A component of the path prefix denies search permission.
EIO
An error occurred while reading from the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of a pathname exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOTDIR
A component of the path prefix is not a directory.
ENOENT
A component of path does not name an existing file or path is an empty string.
EOVERFLOW
The file size in bytes or the number of blocks allocated to the file or the file serial number cannot be represented correctly in the structure pointed to by buf.

The lstat() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
EOVERFLOW
One of the members is too large to store into the structure pointed to by the buf argument.

The following sections are informative.

EXAMPLES

Obtaining Symbolic Link Status Information

The following example shows how to obtain status information for a symbolic link named /modules/pass1. The structure variable buffer is defined for the stat structure. If the path argument specified the filename for the file pointed to by the symbolic link ( /home/cnd/mod1), the results of calling the function would be the same as those returned by a call to the stat() function.

#include <sys/stat.h>

struct stat buffer;
int status;
...
status = lstat("/modules/pass1", &buffer);

APPLICATION USAGE

None.

RATIONALE

The lstat() function is not required to update the time-related fields if the named file is not a symbolic link. While the st_uid, st_gid, st_atime, st_mtime, and st_ctime members of the stat structure may apply to a symbolic link, they are not required to do so. No functions in IEEE Std 1003.1-2001 are required to maintain any of these time fields.

FUTURE DIRECTIONS

None.

SEE ALSO

fstat() , readlink() , stat() , symlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getutxent (3p)

 Continue to this page.


setuid(3p)

SETUID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setuid - set user ID

SYNOPSIS

#include <unistd.h>

int setuid(uid_t uid);

DESCRIPTION

If the process has appropriate privileges, setuid() shall set the real user ID, effective user ID, and the saved set-user-ID of the calling process to uid.

If the process does not have appropriate privileges, but uid is equal to the real user ID or the saved set-user-ID, setuid() shall set the effective user ID to uid; the real user ID and saved set-user-ID shall remain unchanged.

The setuid() function shall not affect the supplementary group list in any way.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The setuid() function shall fail, return -1, and set errno to the corresponding value if one or more of the following are true:

EINVAL
The value of the uid argument is invalid and not supported by the implementation.
EPERM
The process does not have appropriate privileges and uid does not match the real user ID or the saved set-user-ID.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The various behaviors of the setuid() and setgid() functions when called by non-privileged processes reflect the behavior of different historical implementations. For portability, it is recommended that new non-privileged applications use the seteuid() and setegid() functions instead.

The saved set-user-ID capability allows a program to regain the effective user ID established at the last exec call. Similarly, the saved set-group-ID capability allows a program to regain the effective group ID established at the last exec call. These capabilities are derived from System V. Without them, a program might have to run as superuser in order to perform the same functions, because superuser can write on the user's files. This is a problem because such a program can write on any user's files, and so must be carefully written to emulate the permissions of the calling process properly. In System V, these capabilities have traditionally been implemented only via the setuid() and setgid() functions for non-privileged processes. The fact that the behavior of those functions was different for privileged processes made them difficult to use. The POSIX.1-1990 standard defined the setuid() function to behave differently for privileged and unprivileged users. When the caller had the appropriate privilege, the function set the calling process' real user ID, effective user ID, and saved set-user ID on implementations that supported it. When the caller did not have the appropriate privilege, the function set only the effective user ID, subject to permission checks. The former use is generally needed for utilities like login and su, which are not conforming applications and thus outside the scope of IEEE Std 1003.1-2001. These utilities wish to change the user ID irrevocably to a new value, generally that of an unprivileged user. The latter use is needed for conforming applications that are installed with the set-user-ID bit and need to perform operations using the real user ID.

IEEE Std 1003.1-2001 augments the latter functionality with a mandatory feature named _POSIX_SAVED_IDS. This feature permits a set-user-ID application to switch its effective user ID back and forth between the values of its exec-time real user ID and effective user ID. Unfortunately, the POSIX.1-1990 standard did not permit a conforming application using this feature to work properly when it happened to be executed with the (implementation-defined) appropriate privilege. Furthermore, the application did not even have a means to tell whether it had this privilege. Since the saved set-user-ID feature is quite desirable for applications, as evidenced by the fact that NIST required it in FIPS 151-2, it has been mandated by IEEE Std 1003.1-2001. However, there are implementors who have been reluctant to support it given the limitation described above.

The 4.3BSD system handles the problem by supporting separate functions: setuid() (which always sets both the real and effective user IDs, like setuid() in IEEE Std 1003.1-2001 for privileged users), and seteuid() (which always sets just the effective user ID, like setuid() in IEEE Std 1003.1-2001 for non-privileged users). This separation of functionality into distinct functions seems desirable. 4.3BSD does not support the saved set-user-ID feature. It supports similar functionality of switching the effective user ID back and forth via setreuid(), which permits reversing the real and effective user IDs. This model seems less desirable than the saved set-user-ID because the real user ID changes as a side effect. The current 4.4BSD includes saved effective IDs and uses them for seteuid() and setegid() as described above. The setreuid() and setregid() functions will be deprecated or removed.

The solution here is:

*
Require that all implementations support the functionality of the saved set-user-ID, which is set by the exec functions and by privileged calls to setuid().

*
Add the seteuid() and setegid() functions as portable alternatives to setuid() and setgid() for non-privileged and privileged processes.

Historical systems have provided two mechanisms for a set-user-ID process to change its effective user ID to be the same as its real user ID in such a way that it could return to the original effective user ID: the use of the setuid() function in the presence of a saved set-user-ID, or the use of the BSD setreuid() function, which was able to swap the real and effective user IDs. The changes included in IEEE Std 1003.1-2001 provide a new mechanism using seteuid() in conjunction with a saved set-user-ID. Thus, all implementations with the new seteuid() mechanism will have a saved set-user-ID for each process, and most of the behavior controlled by _POSIX_SAVED_IDS has been changed to agree with the case where the option was defined. The kill() function is an exception. Implementors of the new seteuid() mechanism will generally be required to maintain compatibility with the older mechanisms previously supported by their systems. However, compatibility with this use of setreuid() and with the _POSIX_SAVED_IDS behavior of kill() is unfortunately complicated. If an implementation with a saved set-user-ID allows a process to use setreuid() to swap its real and effective user IDs, but were to leave the saved set-user-ID unmodified, the process would then have an effective user ID equal to the original real user ID, and both real and saved set-user-ID would be equal to the original effective user ID. In that state, the real user would be unable to kill the process, even though the effective user ID of the process matches that of the real user, if the kill() behavior of _POSIX_SAVED_IDS was used. This is obviously not acceptable. The alternative choice, which is used in at least one implementation, is to change the saved set-user-ID to the effective user ID during most calls to setreuid(). The standard developers considered that alternative to be less correct than the retention of the old behavior of kill() in such systems. Current conforming applications shall accommodate either behavior from kill(), and there appears to be no strong reason for kill() to check the saved set-user-ID rather than the effective user ID.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getegid() , geteuid() , getgid() , getuid() , setegid() , seteuid() , setgid() , setregid() , setreuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


catan(3p)

CATAN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

catan, catanf, catanl - complex arc tangent functions

SYNOPSIS

#include <complex.h>

double complex catan(double complex z);
float complex catanf(float complex z);
long double complex catanl(long double complex z);

DESCRIPTION

These functions shall compute the complex arc tangent of z, with branch cuts outside the interval [-i, +i] along the imaginary axis.

RETURN VALUE

These functions shall return the complex arc tangent value, in the range of a strip mathematically unbounded along the imaginary axis and in the interval [-pi/2, +pi/2] along the real axis.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ctan() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_typed_mem_open(3p)

POSIX_TYPED_MEM_OPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_typed_mem_open - open a typed memory object (ADVANCED REALTIME)

SYNOPSIS

#include <sys/mman.h>

int posix_typed_mem_open(const char *name, int oflag, int tflag);

DESCRIPTION

The posix_typed_mem_open() function shall establish a connection between the typed memory object specified by the string pointed to by name and a file descriptor. It shall create an open file description that refers to the typed memory object and a file descriptor that refers to that open file description. The file descriptor is used by other functions to refer to that typed memory object. It is unspecified whether the name appears in the file system and is visible to other functions that take pathnames as arguments. The name argument shall conform to the construction rules for a pathname. If name begins with the slash character, then processes calling posix_typed_mem_open() with the same value of name shall refer to the same typed memory object. If name does not begin with the slash character, the effect is implementation-defined. The interpretation of slash characters other than the leading slash character in name is implementation-defined.

Each typed memory object supported in a system shall be identified by a name which specifies not only its associated typed memory pool, but also the path or port by which it is accessed. That is, the same typed memory pool accessed via several different ports shall have several different corresponding names. The binding between names and typed memory objects is established in an implementation-defined manner. Unlike shared memory objects, there is no way within IEEE Std 1003.1-2001 for a program to create a typed memory object.

The value of tflag shall determine how the typed memory object behaves when subsequently mapped by calls to mmap(). At most, one of the following flags defined in <sys/mman.h> may be specified:

POSIX_TYPED_MEM_ALLOCATE
Allocate on mmap().
POSIX_TYPED_MEM_ALLOCATE_CONTIG
Allocate contiguously on mmap().
POSIX_TYPED_MEM_MAP_ALLOCATABLE
Map on mmap(), without affecting allocatability.

If tflag has the flag POSIX_TYPED_MEM_ALLOCATE specified, any subsequent call to mmap() using the returned file descriptor shall result in allocation and mapping of typed memory from the specified typed memory pool. The allocated memory may be a contiguous previously unallocated area of the typed memory pool or several non-contiguous previously unallocated areas (mapped to a contiguous portion of the process address space). If tflag has the flag POSIX_TYPED_MEM_ALLOCATE_CONTIG specified, any subsequent call to mmap() using the returned file descriptor shall result in allocation and mapping of a single contiguous previously unallocated area of the typed memory pool (also mapped to a contiguous portion of the process address space). If tflag has none of the flags POSIX_TYPED_MEM_ALLOCATE or POSIX_TYPED_MEM_ALLOCATE_CONTIG specified, any subsequent call to mmap() using the returned file descriptor shall map an application-chosen area from the specified typed memory pool such that this mapped area becomes unavailable for allocation until unmapped by all processes. If tflag has the flag POSIX_TYPED_MEM_MAP_ALLOCATABLE specified, any subsequent call to mmap() using the returned file descriptor shall map an application-chosen area from the specified typed memory pool without an effect on the availability of that area for allocation; that is, mapping such an object leaves each byte of the mapped area unallocated if it was unallocated prior to the mapping or allocated if it was allocated prior to the mapping. The appropriate privilege to specify the POSIX_TYPED_MEM_MAP_ALLOCATABLE flag is implementation-defined.

If successful, posix_typed_mem_open() shall return a file descriptor for the typed memory object that is the lowest numbered file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other processes. It is unspecified whether the file offset is set. The FD_CLOEXEC file descriptor flag associated with the new file descriptor shall be cleared.

The behavior of msync(), ftruncate(), and all file operations other than mmap(), posix_mem_offset(), posix_typed_mem_get_info(), fstat(), dup(), dup2(), and close(), is unspecified when passed a file descriptor connected to a typed memory object by this function.

The file status flags of the open file description shall be set according to the value of oflag. Applications shall specify exactly one of the three access mode values described below and defined in the <fcntl.h> header, as the value of oflag.

O_RDONLY
Open for read access only.
O_WRONLY
Open for write access only.
O_RDWR
Open for read or write access.

RETURN VALUE

Upon successful completion, the posix_typed_mem_open() function shall return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The posix_typed_mem_open() function shall fail if:

EACCES
The typed memory object exists and the permissions specified by oflag are denied.
EINTR
The posix_typed_mem_open() operation was interrupted by a signal.
EINVAL
The flags specified in tflag are invalid (more than one of POSIX_TYPED_MEM_ALLOCATE, POSIX_TYPED_MEM_ALLOCATE_CONTIG, or POSIX_TYPED_MEM_MAP_ALLOCATABLE is specified).
EMFILE
Too many file descriptors are currently in use by this process.
ENAMETOOLONG
The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
Too many file descriptors are currently open in the system.
ENOENT
The named typed memory object does not exist.
EPERM
The caller lacks the appropriate privilege to specify the flag POSIX_TYPED_MEM_MAP_ALLOCATABLE in argument tflag.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

close() , dup() , exec() , fcntl() , fstat() , ftruncate() , mmap() , msync() , posix_mem_offset() , posix_typed_mem_get_info() , umask() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wctomb(3p)

WCTOMB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wctomb - convert a wide-character code to a character

SYNOPSIS

#include <stdlib.h>

int wctomb(char *s, wchar_t wchar);

DESCRIPTION

The wctomb() function shall determine the number of bytes needed to represent the character corresponding to the wide-character code whose value is wchar (including any change in the shift state). It shall store the character representation (possibly multiple bytes and any special bytes to change shift state) in the array object pointed to by s (if s is not a null pointer). At most {MB_CUR_MAX} bytes shall be stored. If wchar is 0, a null byte shall be stored, preceded by any shift sequence needed to restore the initial shift state, and wctomb() shall be left in the initial shift state.

The behavior of this function is affected by the LC_CTYPE category of the current locale. For a state-dependent encoding, this function shall be placed into its initial state by a call for which its character pointer argument, s, is a null pointer. Subsequent calls with s as other than a null pointer shall cause the internal state of the function to be altered as necessary. A call with s as a null pointer shall cause this function to return a non-zero value if encodings have state dependency, and 0 otherwise. Changing the LC_CTYPE category causes the shift state of this function to be unspecified.

The wctomb() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls wctomb().

RETURN VALUE

If s is a null pointer, wctomb() shall return a non-zero or 0 value, if character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, wctomb() shall return -1 if the value of wchar does not correspond to a valid character, or return the number of bytes that constitute the character corresponding to the value of wchar.

In no case shall the value returned be greater than the value of the {MB_CUR_MAX} macro.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mblen() , mbtowc() , mbstowcs() , wcstombs() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_condattr_getclock(3p)

PTHREAD_CONDATTR_GETCLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_condattr_getclock, pthread_condattr_setclock - get and set the clock selection condition variable attribute (ADVANCED REALTIME)

SYNOPSIS

#include <pthread.h>

int pthread_condattr_getclock(const pthread_condattr_t *restrict attr,
clockid_t *restrict clock_id);
int pthread_condattr_setclock(pthread_condattr_t *attr,
clockid_t clock_id);

DESCRIPTION

The pthread_condattr_getclock() function shall obtain the value of the clock attribute from the attributes object referenced by attr. The pthread_condattr_setclock() function shall set the clock attribute in an initialized attributes object referenced by attr. If pthread_condattr_setclock() is called with a clock_id argument that refers to a CPU-time clock, the call shall fail.

The clock attribute is the clock ID of the clock that shall be used to measure the timeout service of pthread_cond_timedwait(). The default value of the clock attribute shall refer to the system clock.

RETURN VALUE

If successful, the pthread_condattr_getclock() function shall return zero and store the value of the clock attribute of attr into the object referenced by the clock_id argument. Otherwise, an error number shall be returned to indicate the error.

If successful, the pthread_condattr_setclock() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_condattr_setclock() function may fail if:

EINVAL
The value specified by clock_id does not refer to a known clock, or is a CPU-time clock.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_destroy() , pthread_cond_timedwait() , pthread_condattr_destroy()
, pthread_condattr_getpshared() ,1 pthread_condattr_init()
, pthread_condattr_setpshared() ,1 pthread_create() ,
pthread_mutex_init() , the Base
Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcwidth(3p)

WCWIDTH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcwidth - number of column positions of a wide-character code

SYNOPSIS

#include <wchar.h>

int wcwidth(wchar_t wc);

DESCRIPTION

The wcwidth() function shall determine the number of column positions required for the wide character wc. The application shall ensure that the value of wc is a character representable as a wchar_t, and is a wide-character code corresponding to a valid character in the current locale.

RETURN VALUE

The wcwidth() function shall either return 0 (if wc is a null wide-character code), or return the number of column positions to be occupied by the wide-character code wc, or return -1 (if wc does not correspond to a printable wide-character code).

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

This function was removed from the final ISO/IEC 9899:1990/Amendment 1:1995 (E), and the return value for a non-printable wide character is not specified.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcswidth() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strtoull (3p)

 Continue to this page.


ctanhf (3p)

 Continue to this page.


remainderf (3p)

 Continue to this page.


ctanhl (3p)

 Continue to this page.


remainderl (3p)

 Continue to this page.


l64a (3p)

 Continue to this page.


msgrcv(3p)

MSGRCV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

msgrcv - XSI message receive operation

SYNOPSIS

#include <sys/msg.h>

ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
int msgflg);

DESCRIPTION

The msgrcv() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The msgrcv() function shall read a message from the queue associated with the message queue identifier specified by msqid and place it in the user-defined buffer pointed to by msgp.

The application shall ensure that the argument msgp points to a user-defined buffer that contains first a field of type long specifying the type of the message, and then a data portion that holds the data bytes of the message. The structure below is an example of what this user-defined buffer might look like:

struct mymsg {
    long    mtype;     /* Message type. */
    char    mtext[1];  /* Message text. */
}

The structure member mtype is the received message's type as specified by the sending process.

The structure member mtext is the text of the message.

The argument msgsz specifies the size in bytes of mtext. The received message shall be truncated to msgsz bytes if it is larger than msgsz and (msgflg & MSG_NOERROR) is non-zero. The truncated part of the message shall be lost and no indication of the truncation shall be given to the calling process.

If the value of msgsz is greater than {SSIZE_MAX}, the result is implementation-defined.

The argument msgtyp specifies the type of message requested as follows:

*
If msgtyp is 0, the first message on the queue shall be received.

*
If msgtyp is greater than 0, the first message of type msgtyp shall be received.

*
If msgtyp is less than 0, the first message of the lowest type that is less than or equal to the absolute value of msgtyp shall be received.

The argument msgflg specifies the action to be taken if a message of the desired type is not on the queue. These are as follows:

*
If (msgflg & IPC_NOWAIT) is non-zero, the calling thread shall return immediately with a return value of -1 and errno set to [ENOMSG].

*
If (msgflg & IPC_NOWAIT) is 0, the calling thread shall suspend execution until one of the following occurs:
*
A message of the desired type is placed on the queue.

*
The message queue identifier msqid is removed from the system; when this occurs, errno shall be set equal to [EIDRM] and -1 shall be returned.

*
The calling thread receives a signal that is to be caught; in this case a message is not received and the calling thread resumes execution in the manner prescribed in sigaction() .

Upon successful completion, the following actions are taken with respect to the data structure associated with msqid:

*
msg_qnum shall be decremented by 1.

*
msg_lrpid shall be set equal to the process ID of the calling process.

*
msg_rtime shall be set equal to the current time.

RETURN VALUE

Upon successful completion, msgrcv() shall return a value equal to the number of bytes actually placed into the buffer mtext. Otherwise, no message shall be received, msgrcv() shall return (ssize_t)-1, and errno shall be set to indicate the error.

ERRORS

The msgrcv() function shall fail if:

E2BIG
The value of mtext is greater than msgsz and (msgflg & MSG_NOERROR) is 0.
EACCES
Operation permission is denied to the calling process; see XSI Interprocess Communication .
EIDRM
The message queue identifier msqid is removed from the system.
EINTR
The msgrcv() function was interrupted by a signal.
EINVAL
msqid is not a valid message queue identifier.
ENOMSG
The queue does not contain a message of the desired type and (msgflg & IPC_NOWAIT) is non-zero.

The following sections are informative.

EXAMPLES

Receiving a Message

The following example receives the first message on the queue (based on the value of the msgtyp argument, 0). The queue is identified by the msqid argument (assuming that the value has previously been set). This call specifies that an error should be reported if no message is available, but not if the message is too large. The message size is calculated directly using the sizeof operator.

#include <sys/msg.h>
...
int result;
int msqid;
struct message {
    long type;
    char text[20];
} msg;
long msgtyp = 0;
...
result = msgrcv(msqid, (void *) &msg, sizeof(msg.text),
         msgtyp, MSG_NOERROR | IPC_NOWAIT);

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication (IPC). Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , mq_close() , mq_getattr() , mq_notify() , mq_open() , mq_receive() , mq_send() , mq_setattr() , mq_unlink() , msgctl() , msgget() , msgsnd() , sigaction() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/msg.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


clock_gettime(3p)

CLOCK_GETRES

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

clock_getres, clock_gettime, clock_settime - clock and timer functions (REALTIME)

SYNOPSIS

#include <time.h>

int clock_getres(clockid_t clock_id, struct timespec *res);
int clock_gettime(clockid_t clock_id, struct timespec *tp);
int clock_settime(clockid_t clock_id, const struct timespec *tp);

DESCRIPTION

The clock_getres() function shall return the resolution of any clock. Clock resolutions are implementation-defined and cannot be set by a process. If the argument res is not NULL, the resolution of the specified clock shall be stored in the location pointed to by res. If res is NULL, the clock resolution is not returned. If the time argument of clock_settime() is not a multiple of res, then the value is truncated to a multiple of res.

The clock_gettime() function shall return the current value tp for the specified clock, clock_id.

The clock_settime() function shall set the specified clock, clock_id, to the value specified by tp. Time values that are between two consecutive non-negative integer multiples of the resolution of the specified clock shall be truncated down to the smaller multiple of the resolution.

A clock may be system-wide (that is, visible to all processes) or per-process (measuring time that is meaningful only within a process). All implementations shall support a clock_id of CLOCK_REALTIME as defined in <time.h>. This clock represents the realtime clock for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch. An implementation may also support additional clocks. The interpretation of time values for these clocks is unspecified.

If the value of the CLOCK_REALTIME clock is set via clock_settime(), the new value of the clock shall be used to determine the time of expiration for absolute time services based upon the CLOCK_REALTIME clock. This applies to the time at which armed absolute timers expire. If the absolute time requested at the invocation of such a time service is before the new value of the clock, the time service shall expire immediately as if the clock had reached the requested time normally.

Setting the value of the CLOCK_REALTIME clock via clock_settime() shall have no effect on threads that are blocked waiting for a relative time service based upon this clock, including the nanosleep() function; nor on the expiration of relative timers based upon this clock. Consequently, these time services shall expire when the requested relative interval elapses, independently of the new or old value of the clock.

If the Monotonic Clock option is supported, all implementations shall support a clock_id of CLOCK_MONOTONIC defined in <time.h>. This clock represents the monotonic clock for the system. For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time. The value of the CLOCK_MONOTONIC clock cannot be set via clock_settime(). This function shall fail if it is invoked with a clock_id argument of CLOCK_MONOTONIC.

The effect of setting a clock via clock_settime() on armed per-process timers associated with a clock other than CLOCK_REALTIME is implementation-defined.

If the value of the CLOCK_REALTIME clock is set via clock_settime(), the new value of the clock shall be used to determine the time at which the system shall awaken a thread blocked on an absolute clock_nanosleep() call based upon the CLOCK_REALTIME clock. If the absolute time requested at the invocation of such a time service is before the new value of the clock, the call shall return immediately as if the clock had reached the requested time normally.

Setting the value of the CLOCK_REALTIME clock via clock_settime() shall have no effect on any thread that is blocked on a relative clock_nanosleep() call. Consequently, the call shall return when the requested relative interval elapses, independently of the new or old value of the clock.

The appropriate privilege to set a particular clock is implementation-defined.

If _POSIX_CPUTIME is defined, implementations shall support clock ID values obtained by invoking clock_getcpuclockid(), which represent the CPU-time clock of a given process. Implementations shall also support the special clockid_t value CLOCK_PROCESS_CPUTIME_ID, which represents the CPU-time clock of the calling process when invoking one of the clock_*() or timer_*() functions. For these clock IDs, the values returned by clock_gettime() and specified by clock_settime() represent the amount of execution time of the process associated with the clock. Changing the value of a CPU-time clock via clock_settime() shall have no effect on the behavior of the sporadic server scheduling policy (see Scheduling Policies ).

If _POSIX_THREAD_CPUTIME is defined, implementations shall support clock ID values obtained by invoking pthread_getcpuclockid(), which represent the CPU-time clock of a given thread. Implementations shall also support the special clockid_t value CLOCK_THREAD_CPUTIME_ID, which represents the CPU-time clock of the calling thread when invoking one of the clock_*() or timer_*() functions. For these clock IDs, the values returned by clock_gettime() and specified by clock_settime() shall represent the amount of execution time of the thread associated with the clock. Changing the value of a CPU-time clock via clock_settime() shall have no effect on the behavior of the sporadic server scheduling policy (see Scheduling Policies ).

RETURN VALUE

A return value of 0 shall indicate that the call succeeded. A return value of -1 shall indicate that an error occurred, and errno shall be set to indicate the error.

ERRORS

The clock_getres(), clock_gettime(), and clock_settime() functions shall fail if:

EINVAL
The clock_id argument does not specify a known clock.

The clock_settime() function shall fail if:

EINVAL
The tp argument to clock_settime() is outside the range for the given clock ID.
EINVAL
The tp argument specified a nanosecond value less than zero or greater than or equal to 1000 million.
EINVAL
The value of the clock_id argument is CLOCK_MONOTONIC.

The clock_settime() function may fail if:

EPERM
The requesting process does not have the appropriate privilege to set the specified clock.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Timers option and need not be available on all implementations.

Note that the absolute value of the monotonic clock is meaningless (because its origin is arbitrary), and thus there is no need to set it. Furthermore, realtime applications can rely on the fact that the value of this clock is never set and, therefore, that time intervals measured with this clock will not be affected by calls to clock_settime().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clock_getcpuclockid() , clock_nanosleep() , ctime()
, mq_timedreceive() , mq_timedsend() , nanosleep()
, pthread_mutex_timedlock() , sem_timedwait() , time()
, timer_create() , timer_getoverrun() , the Base
Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


connect(3p)

CONNECT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

connect - connect a socket

SYNOPSIS

#include <sys/socket.h>

int connect(int socket, const struct sockaddr *address,
socklen_t address_len);

DESCRIPTION

The connect() function shall attempt to make a connection on a socket. The function takes the following arguments:

socket
Specifies the file descriptor associated with the socket.
address
Points to a sockaddr structure containing the peer address. The length and format of the address depend on the address family of the socket.
address_len
Specifies the length of the sockaddr structure pointed to by the address argument.

If the socket has not already been bound to a local address, connect() shall bind it to an address which, unless the socket's address family is AF_UNIX, is an unused local address.

If the initiating socket is not connection-mode, then connect() shall set the socket's peer address, and no connection is made. For SOCK_DGRAM sockets, the peer address identifies where all datagrams are sent on subsequent send() functions, and limits the remote sender for subsequent recv() functions. If address is a null address for the protocol, the socket's peer address shall be reset.

If the initiating socket is connection-mode, then connect() shall attempt to establish a connection to the address specified by the address argument. If the connection cannot be established immediately and O_NONBLOCK is not set for the file descriptor for the socket, connect() shall block for up to an unspecified timeout interval until the connection is established. If the timeout interval expires before the connection is established, connect() shall fail and the connection attempt shall be aborted. If connect() is interrupted by a signal that is caught while blocked waiting to establish a connection, connect() shall fail and set errno to [EINTR], but the connection request shall not be aborted, and the connection shall be established asynchronously.

If the connection cannot be established immediately and O_NONBLOCK is set for the file descriptor for the socket, connect() shall fail and set errno to [EINPROGRESS], but the connection request shall not be aborted, and the connection shall be established asynchronously. Subsequent calls to connect() for the same socket, before the connection is established, shall fail and set errno to [EALREADY].

When the connection has been established asynchronously, select() and poll() shall indicate that the file descriptor for the socket is ready for writing.

The socket in use may require the process to have appropriate privileges to use the connect() function.

RETURN VALUE

Upon successful completion, connect() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The connect() function shall fail if:

EADDRNOTAVAIL
The specified address is not available from the local machine.
EAFNOSUPPORT
The specified address is not a valid address for the address family of the specified socket.
EALREADY
A connection request is already in progress for the specified socket.
EBADF
The socket argument is not a valid file descriptor.
ECONNREFUSED
The target address was not listening for connections or refused the connection request.
EINPROGRESS
O_NONBLOCK is set for the file descriptor for the socket and the connection cannot be immediately established; the connection shall be established asynchronously.
EINTR
The attempt to establish a connection was interrupted by delivery of a signal that was caught; the connection shall be established asynchronously.
EISCONN
The specified socket is connection-mode and is already connected.
ENETUNREACH
No route to the network is present.
ENOTSOCK
The socket argument does not refer to a socket.
EPROTOTYPE
The specified address has a different type than the socket bound to the specified peer address.
ETIMEDOUT
The attempt to connect timed out before a connection was made.

If the address family of the socket is AF_UNIX, then connect() shall fail if:

EIO
An I/O error occurred while reading from or writing to the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the pathname in address.
ENAMETOOLONG
A component of a pathname exceeded {NAME_MAX} characters, or an entire pathname exceeded {PATH_MAX} characters.
ENOENT
A component of the pathname does not name an existing file or the pathname is an empty string.
ENOTDIR
A component of the path prefix of the pathname in address is not a directory.

The connect() function may fail if:

EACCES
Search permission is denied for a component of the path prefix; or write access to the named socket is denied.
EADDRINUSE
Attempt to establish a connection that uses addresses that are already in use.
ECONNRESET
Remote host reset the connection request.
EHOSTUNREACH
The destination host cannot be reached (probably because the host is down or a remote router cannot reach it).
EINVAL
The address_len argument is not a valid length for the address family; or invalid address family in the sockaddr structure.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the pathname in address.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.
ENETDOWN
The local network interface used to reach the destination is down.
ENOBUFS
No buffer space is available.
EOPNOTSUPP
The socket is listening and cannot be connected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If connect() fails, the state of the socket is unspecified. Conforming applications should close the file descriptor and create a new socket before attempting to reconnect.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

accept() , bind() , close() , getsockname() , poll() , select() , send() , shutdown() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_get_attr (3p)

 Continue to this page.


imaxabs(3p)

IMAXABS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

imaxabs - return absolute value

SYNOPSIS

#include <inttypes.h>

intmax_t imaxabs(intmax_t j);

DESCRIPTION

The imaxabs() function shall compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.

RETURN VALUE

The imaxabs() function shall return the absolute value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The absolute value of the most negative number cannot be represented in two's complement.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

imaxdiv() , the Base Definitions volume of IEEE Std 1003.1-2001, <inttypes.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fputc(3p)

FPUTC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fputc - put a byte on a stream

SYNOPSIS

#include <stdio.h>

int fputc(int c, FILE *stream);

DESCRIPTION

The fputc() function shall write the byte specified by c (converted to an unsigned char) to the output stream pointed to by stream, at the position indicated by the associated file-position indicator for the stream (if defined), and shall advance the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the byte shall be appended to the output stream.

The st_ctime and st_mtime fields of the file shall be marked for update between the successful execution of fputc() and the next successful completion of a call to fflush() or fclose() on the same stream or a call to exit() or abort().

RETURN VALUE

Upon successful completion, fputc() shall return the value it has written. Otherwise, it shall return EOF, the error indicator for the stream shall be set, and errno shall be set to indicate the error.

ERRORS

The fputc() function shall fail if either the stream is unbuffered or the stream's buffer needs to be flushed, and:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying stream and the process would be delayed in the write operation.
EBADF
The file descriptor underlying stream is not a valid file descriptor open for writing.
EFBIG
An attempt was made to write to a file that exceeds the maximum file size.
EFBIG
An attempt was made to write to a file that exceeds the process' file size limit.
EFBIG
The file is a regular file and an attempt was made to write at or beyond the offset maximum.
EINTR
The write operation was terminated due to the receipt of a signal, and no data was transferred.
EIO
A physical I/O error has occurred, or the process is a member of a background process group attempting to write to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the process group of the process is orphaned. This error may also be returned under implementation-defined conditions.
ENOSPC
There was no free space remaining on the device containing the file.
EPIPE
An attempt is made to write to a pipe or FIFO that is not open for reading by any process. A SIGPIPE signal shall also be sent to the thread.

The fputc() function may fail if:

ENOMEM
Insufficient storage space is available.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ferror() , fopen() , getrlimit() , putc() , puts() , setbuf() , ulimit() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getgrgid(3p)

GETGRGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getgrgid, getgrgid_r - get group database entry for a group ID

SYNOPSIS

#include <grp.h>

struct group *getgrgid(gid_t gid);

int getgrgid_r(gid_t gid, struct group *grp, char *buffer,
size_t bufsize, struct group **result);

DESCRIPTION

The getgrgid() function shall search the group database for an entry with a matching gid.

The getgrgid() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The getgrgid_r() function shall update the group structure pointed to by grp and store a pointer to that structure at the location pointed to by result. The structure shall contain an entry from the group database with a matching gid. Storage referenced by the group structure is allocated from the memory provided with the buffer parameter, which is bufsize bytes in size. The maximum size needed for this buffer can be determined with the {_SC_GETGR_R_SIZE_MAX} sysconf() parameter. A NULL pointer shall be returned at the location pointed to by result on error or if the requested entry is not found.

RETURN VALUE

Upon successful completion, getgrgid() shall return a pointer to a struct group with the structure defined in <grp.h> with a matching entry if one is found. The getgrgid() function shall return a null pointer if either the requested entry was not found, or an error occurred. On error, errno shall be set to indicate the error.

The return value may point to a static area which is overwritten by a subsequent call to getgrent(), getgrgid(), or getgrnam().

If successful, the getgrgid_r() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The getgrgid() and getgrgid_r() functions may fail if:

EIO
An I/O error has occurred.
EINTR
A signal was caught during getgrgid().
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.

The getgrgid_r() function may fail if:

ERANGE
Insufficient storage was supplied via buffer and bufsize to contain the data to be referenced by the resulting group structure.

The following sections are informative.

EXAMPLES

Finding an Entry in the Group Database

The following example uses getgrgid() to search the group database for a group ID that was previously stored in a stat structure, then prints out the group name if it is found. If the group is not found, the program prints the numeric value of the group for the entry.

#include <sys/types.h>
#include <grp.h>
#include <stdio.h>
...
struct stat statbuf;
struct group *grp;
...
if ((grp = getgrgid(statbuf.st_gid)) != NULL)
    printf(" %-8.8s", grp->gr_name);
else
    printf(" %-8d", statbuf.st_gid);
...

APPLICATION USAGE

Applications wishing to check for error situations should set errno to 0 before calling getgrgid(). If errno is set on return, an error occurred.

The getgrgid_r() function is thread-safe and shall return values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

endgrent() , getgrnam() , the Base Definitions volume of IEEE Std 1003.1-2001, <grp.h>, <limits.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getopt(3p)

GETOPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getopt, optarg, opterr, optind, optopt - command option parsing

SYNOPSIS

#include <unistd.h>

int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;

DESCRIPTION

The getopt() function is a command-line parser that shall follow Utility Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 in the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines.

The parameters argc and argv are the argument count and argument array as passed to main() (see exec() ). The argument optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument. All option characters allowed by Utility Syntax Guideline 3 are allowed in optstring. The implementation may accept other characters as an extension.

The variable optind is the index of the next element of the argv[] vector to be processed. It shall be initialized to 1 by the system, and getopt() shall update it when it finishes with each element of argv[]. When an element of argv[] contains multiple option characters, it is unspecified how getopt() determines which options have already been processed.

The getopt() function shall return the next option character (if one is found) from argv that matches a character in optstring, if there is one that matches. If the option takes an argument, getopt() shall set the variable optarg to point to the option-argument as follows:

1.
If the option was the last character in the string pointed to by an element of argv, then optarg shall contain the next element of argv, and optind shall be incremented by 2. If the resulting value of optind is greater than argc, this indicates a missing option-argument, and getopt() shall return an error indication.

2.
Otherwise, optarg shall point to the string following the option character in that element of argv, and optind shall be incremented by 1.

If, when getopt() is called:

argv[optind]  is a null pointer*
argv[optind]  is not the character -
argv[optind]  points to the string "-"

getopt() shall return -1 without changing optind. If:

argv[optind]   points to the string "--"

getopt() shall return -1 after incrementing optind.

If getopt() encounters an option character that is not contained in optstring, it shall return the question-mark ( '?' ) character. If it detects a missing option-argument, it shall return the colon character ( ':' ) if the first character of optstring was a colon, or a question-mark character ( '?' ) otherwise. In either case, getopt() shall set the variable optopt to the option character that caused the error. If the application has not set the variable opterr to 0 and the first character of optstring is not a colon, getopt() shall also print a diagnostic message to stderr in the format specified for the getopts utility.

The getopt() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The getopt() function shall return the next option character specified on the command line.

A colon ( ':' ) shall be returned if getopt() detects a missing argument and the first character of optstring was a colon ( ':' ).

A question mark ( '?' ) shall be returned if getopt() encounters an option character not in optstring or detects a missing argument and the first character of optstring was not a colon ( ':' ).

Otherwise, getopt() shall return -1 when all command line options are parsed.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Parsing Command Line Options

The following code fragment shows how you might process the arguments for a utility that can take the mutually-exclusive options a and b and the options f and o, both of which require arguments:

#include <unistd.h>

int
main(int argc, char *argv[ ])
{
    int c;
    int bflg, aflg, errflg;
    char *ifile;
    char *ofile;
    extern char *optarg;
    extern int optind, optopt;
    . . .
    while ((c = getopt(argc, argv, ":abf:o:")) != -1) {
        switch(c) {
        case 'a':
            if (bflg)
                errflg++;
            else
                aflg++;
            break;
        case 'b':
            if (aflg)
                errflg++;
            else {
                bflg++;
                bproc();
            }
            break;
        case 'f':
            ifile = optarg;
            break;
        case 'o':
            ofile = optarg;
            break;
            case ':':       /* -f or -o without operand */
                    fprintf(stderr,
                            "Option -%c requires an operand\n", optopt);
                    errflg++;
                    break;
        case '?':
                    fprintf(stderr,
                            "Unrecognized option: -%c\n", optopt);
            errflg++;
        }
    }
    if (errflg) {
        fprintf(stderr, "usage: . . . ");
        exit(2);
    }
    for ( ; optind < argc; optind++) {
        if (access(argv[optind], R_OK)) {
    . . .
}

This code accepts any of the following as equivalent:

cmd -ao arg path path
cmd -a -o arg path path
cmd -o arg -a path path
cmd -a -o arg -- path path
cmd -a -oarg path path
cmd -aoarg path path

Checking Options and Arguments

The following example parses a set of command line options and prints messages to standard output for each option and argument that it encounters.

#include <unistd.h>
#include <stdio.h>
...
int c;
char *filename;
extern char *optarg;
extern int optind, optopt, opterr;
...
while ((c = getopt(argc, argv, ":abf:")) != -1) {
    switch(c) {
    case 'a':
        printf("a is set\n");
        break;
    case 'b':
        printf("b is set\n");
        break;
    case 'f':
        filename = optarg;
        printf("filename is %s\n", filename);
        break;
    case ':':
        printf("-%c without filename\n", optopt);
        break;
    case '?':
        printf("unknown arg %c\n", optopt);
        break;
    }
}

Selecting Options from the Command Line

The following example selects the type of database routines the user wants to use based on the Options argument.

#include <unistd.h>
#include <string.h>
...
char *Options = "hdbtl";
...
int dbtype, i;
char c;
char *st;
...
dbtype = 0;
while ((c = getopt(argc, argv, Options)) != -1) {
    if ((st = strchr(Options, c)) != NULL) {
        dbtype = st - Options;
        break;
    }
}

APPLICATION USAGE

The getopt() function is only required to support option characters included in Utility Syntax Guideline 3. Many historical implementations of getopt() support other characters as options. This is an allowed extension, but applications that use extensions are not maximally portable. Note that support for multi-byte option characters is only possible when such characters can be represented as type int.

RATIONALE

The optopt variable represents historical practice and allows the application to obtain the identity of the invalid option.

The description has been written to make it clear that getopt(), like the getopts utility, deals with option-arguments whether separated from the option by <blank>s or not. Note that the requirements on getopt() and getopts are more stringent than the Utility Syntax Guidelines.

The getopt() function shall return -1, rather than EOF, so that <stdio.h> is not required.

The special significance of a colon as the first character of optstring makes getopt() consistent with the getopts utility. It allows an application to make a distinction between a missing argument and an incorrect option letter without having to examine the option letter. It is true that a missing argument can only be detected in one case, but that is a case that has to be considered.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nftw(3p)

NFTW

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nftw - walk a file tree

SYNOPSIS

#include <ftw.h>

int nftw(const char *path, int (*fn)(const char *,
const struct stat *, int, struct FTW *), int depth, int flags);

DESCRIPTION

The nftw() function shall recursively descend the directory hierarchy rooted in path. The nftw() function has a similar effect to ftw() except that it takes an additional argument flags, which is a bitwise-inclusive OR of zero or more of the following flags:

FTW_CHDIR
If set, nftw() shall change the current working directory to each directory as it reports files in that directory. If clear, nftw() shall not change the current working directory.
FTW_DEPTH
If set, nftw() shall report all files in a directory before reporting the directory itself. If clear, nftw() shall report any directory before reporting the files in that directory.
FTW_MOUNT
If set, nftw() shall only report files in the same file system as path. If clear, nftw() shall report all files encountered during the walk.
FTW_PHYS
If set, nftw() shall perform a physical walk and shall not follow symbolic links.

If FTW_PHYS is clear and FTW_DEPTH is set, nftw() shall follow links instead of reporting them, but shall not report any directory that would be a descendant of itself. If FTW_PHYS is clear and FTW_DEPTH is clear, nftw() shall follow links instead of reporting them, but shall not report the contents of any directory that would be a descendant of itself.

At each file it encounters, nftw() shall call the user-supplied function fn with four arguments:

*
The first argument is the pathname of the object.

*
The second argument is a pointer to the stat buffer containing information on the object.

*
The third argument is an integer giving additional information. Its value is one of the following:
FTW_F
The object is a file.
FTW_D
The object is a directory.
FTW_DP
The object is a directory and subdirectories have been visited. (This condition shall only occur if the FTW_DEPTH flag is included in flags.)
FTW_SL
The object is a symbolic link. (This condition shall only occur if the FTW_PHYS flag is included in flags.)
FTW_SLN
The object is a symbolic link that does not name an existing file. (This condition shall only occur if the FTW_PHYS flag is not included in flags.)
FTW_DNR
The object is a directory that cannot be read. The fn function shall not be called for any of its descendants.
FTW_NS
The stat() function failed on the object because of lack of appropriate permission. The stat buffer passed to fn is undefined. Failure of stat() for any other reason is considered an error and nftw() shall return -1.

*
The fourth argument is a pointer to an FTW structure. The value of base is the offset of the object's filename in the pathname passed as the first argument to fn. The value of level indicates depth relative to the root of the walk, where the root level is 0.

The results are unspecified if the application-supplied fn function does not preserve the current working directory.

The argument depth sets the maximum number of file descriptors that shall be used by nftw() while traversing the file tree. At most one file descriptor shall be used for each directory level.

The nftw() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The nftw() function shall continue until the first of the following conditions occurs:

*
An invocation of fn shall return a non-zero value, in which case nftw() shall return that value.

*
The nftw() function detects an error other than [EACCES] (see FTW_DNR and FTW_NS above), in which case nftw() shall return -1 and set errno to indicate the error.

*
The tree is exhausted, in which case nftw() shall return 0.

ERRORS

The nftw() function shall fail if:

EACCES
Search permission is denied for any component of path or read permission is denied for path, or fn returns -1 and does not reset errno.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of path is not a directory.
EOVERFLOW
A field in the stat structure cannot be represented correctly in the current programming environment for one or more files found in the file hierarchy.

The nftw() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.
ENFILE
Too many files are currently open in the system.

In addition, errno may be set if the function pointed to by fn causes errno to be set.

The following sections are informative.

EXAMPLES

The following example walks the /tmp directory and its subdirectories, calling the nftw() function for every directory entry, to a maximum of 5 levels deep.

#include <ftw.h>
...
int nftwfunc(const char *, const struct stat *, int, struct FTW *);

int nftwfunc(const char *filename, const struct stat *statptr,
    int fileflags, struct FTW *pfwt)
{
    return 0;
}
...
char *startpath = "/tmp";
int depth = 5;
int flags = FTW_CHDIR | FTW_DEPTH | FTW_MOUNT;
int ret;

ret = nftw(startpath, nftwfunc, depth, flags);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

lstat() , opendir() , readdir() , stat() , the Base Definitions volume of IEEE Std 1003.1-2001, <ftw.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_getschedparam(3p)

POSIX_SPAWNATTR_GETSCHEDPARAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawnattr_getschedparam, posix_spawnattr_setschedparam - get and set the spawn-schedparam attribute of a spawn attributes object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>
#include <sched.h>

int posix_spawnattr_getschedparam(const posix_spawnattr_t *
restrict attr, struct sched_param *restrict schedparam);
int posix_spawnattr_setschedparam(posix_spawnattr_t *restrict attr,
const struct sched_param *restrict schedparam);

DESCRIPTION

The posix_spawnattr_getschedparam() function shall obtain the value of the spawn-schedparam attribute from the attributes object referenced by attr.

The posix_spawnattr_setschedparam() function shall set the spawn-schedparam attribute in an initialized attributes object referenced by attr.

The spawn-schedparam attribute represents the scheduling parameters to be assigned to the new process image in a spawn operation (if POSIX_SPAWN_SETSCHEDULER or POSIX_SPAWN_SETSCHEDPARAM is set in the spawn-flags attribute). The default value of this attribute is unspecified.

RETURN VALUE

Upon successful completion, posix_spawnattr_getschedparam() shall return zero and store the value of the spawn-schedparam attribute of attr into the object referenced by the schedparam parameter; otherwise, an error number shall be returned to indicate the error.

Upon successful completion, posix_spawnattr_setschedparam() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The posix_spawnattr_setschedparam() function may fail if:

EINVAL
The value of the attribute being set is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn and Process Scheduling options and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnattr_destroy() , posix_spawnattr_init()
, posix_spawnattr_getsigdefault() , posix_spawnattr_getflags()
, posix_spawnattr_getpgroup() , posix_spawnattr_getschedpolicy()
, posix_spawnattr_getsigmask() , posix_spawnattr_setsigdefault()
, posix_spawnattr_setflags() , posix_spawnattr_setpgroup()
, posix_spawnattr_setschedpolicy() , posix_spawnattr_setsigmask()
, posix_spawnp() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>,
<spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wmemmove(3p)

WMEMMOVE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wmemmove - copy wide characters in memory with overlapping areas

SYNOPSIS

#include <wchar.h>

wchar_t *wmemmove(wchar_t *ws1, const wchar_t *ws2, size_t n);

DESCRIPTION

The wmemmove() function shall copy n wide characters from the object pointed to by ws2 to the object pointed to by ws1. Copying shall take place as if the n wide characters from the object pointed to by ws2 are first copied into a temporary array of n wide characters that does not overlap the objects pointed to by ws1 or ws2, and then the n wide characters from the temporary array are copied into the object pointed to by ws1.

This function shall not be affected by locale and all wchar_t values shall be treated identically. The null wide character and wchar_t values not corresponding to valid characters shall not be treated specially.

If n is zero, the application shall ensure that ws1 and ws2 are valid pointers, and the function shall copy zero wide characters.

RETURN VALUE

The wmemmove() function shall return the value of ws1.

ERRORS

No errors are defined

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wmemchr() , wmemcmp() , wmemcpy() , wmemset() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mblen(3p)

MBLEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mblen - get number of bytes in a character

SYNOPSIS

#include <stdlib.h>

int mblen(const char *s, size_t n);

DESCRIPTION

If s is not a null pointer, mblen() shall determine the number of bytes constituting the character pointed to by s. Except that the shift state of mbtowc() is not affected, it shall be equivalent to:

mbtowc((wchar_t *)0, s, n);

The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls mblen().

The behavior of this function is affected by the LC_CTYPE category of the current locale. For a state-dependent encoding, this function shall be placed into its initial state by a call for which its character pointer argument, s, is a null pointer. Subsequent calls with s as other than a null pointer shall cause the internal state of the function to be altered as necessary. A call with s as a null pointer shall cause this function to return a non-zero value if encodings have state dependency, and 0 otherwise. If the implementation employs special bytes to change the shift state, these bytes shall not produce separate wide-character codes, but shall be grouped with an adjacent character. Changing the LC_CTYPE category causes the shift state of this function to be unspecified.

RETURN VALUE

If s is a null pointer, mblen() shall return a non-zero or 0 value, if character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, mblen() shall either return 0 (if s points to the null byte), or return the number of bytes that constitute the character (if the next n or fewer bytes form a valid character), or return -1 (if they do not form a valid character) and may set errno to indicate the error. In no case shall the value returned be greater than n or the value of the {MB_CUR_MAX} macro.

ERRORS

The mblen() function may fail if:

EILSEQ
Invalid character sequence is detected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mbtowc() , mbstowcs() , wctomb() , wcstombs() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fputs(3p)

FPUTS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fputs - put a string on a stream

SYNOPSIS

#include <stdio.h>

int fputs(const char *restrict s, FILE *restrict stream);

DESCRIPTION

The fputs() function shall write the null-terminated string pointed to by s to the stream pointed to by stream. The terminating null byte shall not be written.

The st_ctime and st_mtime fields of the file shall be marked for update between the successful execution of fputs() and the next successful completion of a call to fflush() or fclose() on the same stream or a call to exit() or abort().

RETURN VALUE

Upon successful completion, fputs() shall return a non-negative number. Otherwise, it shall return EOF, set an error indicator for the stream, and set errno to indicate the error.

ERRORS

Refer to fputc() .

The following sections are informative.

EXAMPLES

Printing to Standard Output

The following example gets the current time, converts it to a string using localtime() and asctime(), and prints it to standard output using fputs(). It then prints the number of minutes to an event for which it is waiting.

#include <time.h>
#include <stdio.h>
...
time_t now;
int minutes_to_event;
...
time(&now);
printf("The time is ");
fputs(asctime(localtime(&now)), stdout);
printf("There are still %d minutes to the event.\n",
    minutes_to_event);
...

APPLICATION USAGE

The puts() function appends a <newline> while fputs() does not.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , putc() , puts() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_flush (3p)

 Continue to this page.


pthread_setschedparam (3p)

 Continue to this page.


getpid(3p)

GETPID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getpid - get the process ID

SYNOPSIS

#include <unistd.h>

pid_t getpid(void);

DESCRIPTION

The getpid() function shall return the process ID of the calling process.

RETURN VALUE

The getpid() function shall always be successful and no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fork() , getpgrp() , getppid() , kill() , setpgid() , setsid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fwprintf (3p)

 Continue to this page.


posix_trace_attr_getinherited(3p)

POSIX_TRACE_ATTR_GETINHERITED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_attr_getinherited, posix_trace_attr_getlogfullpolicy, posix_trace_attr_getstreamfullpolicy, posix_trace_attr_setinherited, posix_trace_attr_setlogfullpolicy, posix_trace_attr_setstreamfullpolicy - retrieve and set the behavior of a trace stream (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_attr_getinherited(const trace_attr_t *restrict attr,
int *restrict inheritancepolicy);

int posix_trace_attr_getlogfullpolicy(const trace_attr_t *restrict attr,
int *restrict logpolicy);

int posix_trace_attr_getstreamfullpolicy(const trace_attr_t *attr,
int *streampolicy);

int posix_trace_attr_setinherited(trace_attr_t *attr,
int inheritancepolicy);

int posix_trace_attr_setlogfullpolicy(trace_attr_t *attr,
int logpolicy);

int posix_trace_attr_setstreamfullpolicy(trace_attr_t *attr,
int streampolicy);

DESCRIPTION

The posix_trace_attr_getinherited() and posix_trace_attr_setinherited() functions, respectively, shall get and set the inheritance policy stored in the inheritance attribute for traced processes across the fork() and spawn() operations. The inheritance attribute of the attributes object pointed to by the attr argument shall be set to one of the following values defined by manifest constants in the <trace.h> header:

POSIX_TRACE_CLOSE_FOR_CHILD

After a fork() or spawn() operation, the child shall not be traced, and tracing of the parent shall continue.

POSIX_TRACE_INHERITED

After a fork() or spawn() operation, if the parent is being traced, its child shall be concurrently traced using the same trace stream.

The default value for the inheritance attribute is POSIX_TRACE_CLOSE_FOR_CHILD.

The posix_trace_attr_getlogfullpolicy() and posix_trace_attr_setlogfullpolicy() functions, respectively, shall get and set the trace log full policy stored in the log-full-policy attribute of the attributes object pointed to by the attr argument.

The log-full-policy attribute shall be set to one of the following values defined by manifest constants in the <trace.h> header:

POSIX_TRACE_LOOP

The trace log shall loop until the associated trace stream is stopped. This policy means that when the trace log gets full, the file system shall reuse the resources allocated to the oldest trace events that were recorded. In this way, the trace log will always contain the most recent trace events flushed.

POSIX_TRACE_UNTIL_FULL

The trace stream shall be flushed to the trace log until the trace log is full. This condition can be deduced from the posix_log_full_status member status (see the posix_trace_status_info structure defined in <trace.h>). The last recorded trace event shall be the POSIX_TRACE_STOP trace event.

POSIX_TRACE_APPEND

The associated trace stream shall be flushed to the trace log without log size limitation. If the application specifies POSIX_TRACE_APPEND, the implementation shall ignore the log-max-size attribute.

The default value for the log-full-policy attribute is POSIX_TRACE_LOOP.

The posix_trace_attr_getstreamfullpolicy() and posix_trace_attr_setstreamfullpolicy() functions, respectively, shall get and set the trace stream full policy stored in the stream-full-policy attribute of the attributes object pointed to by the attr argument.

The stream-full-policy attribute shall be set to one of the following values defined by manifest constants in the <trace.h> header:

POSIX_TRACE_LOOP

The trace stream shall loop until explicitly stopped by the posix_trace_stop() function. This policy means that when the trace stream is full, the trace system shall reuse the resources allocated to the oldest trace events recorded. In this way, the trace stream will always contain the most recent trace events recorded.

POSIX_TRACE_UNTIL_FULL

The trace stream will run until the trace stream resources are exhausted. Then the trace stream will stop. This condition can be deduced from posix_stream_status and posix_stream_full_status (see the posix_trace_status_info structure defined in <trace.h>). When this trace stream is read, a POSIX_TRACE_STOP trace event shall be reported after reporting the last recorded trace event. The trace system shall reuse the resources allocated to any trace events already reported-see the posix_trace_getnext_event(), posix_trace_trygetnext_event(), and posix_trace_timedgetnext_event() functions-or already flushed for an active trace stream with log if the Trace Log option is supported; see the posix_trace_flush() function. The trace system shall restart the trace stream when it is empty and may restart it sooner. A POSIX_TRACE_START trace event shall be reported before reporting the next recorded trace event.

POSIX_TRACE_FLUSH

If the Trace Log option is supported, this policy is identical to the POSIX_TRACE_UNTIL_FULL trace stream full policy except that the trace stream shall be flushed regularly as if posix_trace_flush() had been explicitly called. Defining this policy for an active trace stream without log shall be invalid.

The default value for the stream-full-policy attribute shall be POSIX_TRACE_LOOP for an active trace stream without log.

If the Trace Log option is supported, the default value for the stream-full-policy attribute shall be POSIX_TRACE_FLUSH for an active trace stream with log.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

If successful, the posix_trace_attr_getinherited() function shall store the inheritance attribute value in the object pointed to by inheritancepolicy. Otherwise, the content of this object is undefined.

If successful, the posix_trace_attr_getlogfullpolicy() function shall store the log-full-policy attribute value in the object pointed to by logpolicy. Otherwise, the content of this object is undefined.

If successful, the posix_trace_attr_getstreamfullpolicy() function shall store the stream-full-policy attribute value in the object pointed to by streampolicy. Otherwise, the content of this object is undefined.

ERRORS

These functions may fail if:

EINVAL
The value specified by at least one of the arguments is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fork() , posix_trace_attr_init() , posix_trace_create()
, posix_trace_flush() , posix_trace_get_attr() , posix_trace_getnext_event()
, posix_trace_start() , posix_trace_timedgetnext_event()
, the Base Definitions volume of
IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fcntl(3p)

FCNTL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fcntl - file control

SYNOPSIS

#include <unistd.h>
#include <fcntl.h>

int fcntl(int fildes, int cmd, ...);

DESCRIPTION

The fcntl() function shall perform the operations described below on open files. The fildes argument is a file descriptor.

The available values for cmd are defined in <fcntl.h> and are as follows:

F_DUPFD
Return a new file descriptor which shall be the lowest numbered available (that is, not already open) file descriptor greater than or equal to the third argument, arg, taken as an integer of type int. The new file descriptor shall refer to the same open file description as the original file descriptor, and shall share any locks. The FD_CLOEXEC flag associated with the new file descriptor shall be cleared to keep the file open across calls to one of the exec functions.
F_GETFD
Get the file descriptor flags defined in <fcntl.h> that are associated with the file descriptor fildes. File descriptor flags are associated with a single file descriptor and do not affect other file descriptors that refer to the same file.
F_SETFD
Set the file descriptor flags defined in <fcntl.h>, that are associated with fildes, to the third argument, arg, taken as type int. If the FD_CLOEXEC flag in the third argument is 0, the file shall remain open across the exec functions; otherwise, the file shall be closed upon successful execution of one of the exec functions.
F_GETFL
Get the file status flags and file access modes, defined in <fcntl.h>, for the file description associated with fildes. The file access modes can be extracted from the return value using the mask O_ACCMODE, which is defined in <fcntl.h>. File status flags and file access modes are associated with the file description and do not affect other file descriptors that refer to the same file with different open file descriptions.
F_SETFL
Set the file status flags, defined in <fcntl.h>, for the file description associated with fildes from the corresponding bits in the third argument, arg, taken as type int. Bits corresponding to the file access mode and the file creation flags, as defined in <fcntl.h>, that are set in arg shall be ignored. If any bits in arg other than those mentioned here are changed by the application, the result is unspecified.
F_GETOWN
If fildes refers to a socket, get the process or process group ID specified to receive SIGURG signals when out-of-band data is available. Positive values indicate a process ID; negative values, other than -1, indicate a process group ID. If fildes does not refer to a socket, the results are unspecified.
F_SETOWN
If fildes refers to a socket, set the process or process group ID specified to receive SIGURG signals when out-of-band data is available, using the value of the third argument, arg, taken as type int. Positive values indicate a process ID; negative values, other than -1, indicate a process group ID. If fildes does not refer to a socket, the results are unspecified.

The following values for cmd are available for advisory record locking. Record locking shall be supported for regular files, and may be supported for other files.

F_GETLK
Get the first lock which blocks the lock description pointed to by the third argument, arg, taken as a pointer to type struct flock, defined in <fcntl.h>. The information retrieved shall overwrite the information passed to fcntl() in the structure flock. If no lock is found that would prevent this lock from being created, then the structure shall be left unchanged except for the lock type which shall be set to F_UNLCK.
F_SETLK
Set or clear a file segment lock according to the lock description pointed to by the third argument, arg, taken as a pointer to type struct flock, defined in <fcntl.h>. F_SETLK can establish shared (or read) locks (F_RDLCK) or exclusive (or write) locks (F_WRLCK), as well as to remove either type of lock (F_UNLCK). F_RDLCK, F_WRLCK, and F_UNLCK are defined in <fcntl.h>. If a shared or exclusive lock cannot be set, fcntl() shall return immediately with a return value of -1.
F_SETLKW
This command shall be equivalent to F_SETLK except that if a shared or exclusive lock is blocked by other locks, the thread shall wait until the request can be satisfied. If a signal that is to be caught is received while fcntl() is waiting for a region, fcntl() shall be interrupted. Upon return from the signal handler, fcntl() shall return -1 with errno set to [EINTR], and the lock operation shall not be done.

Additional implementation-defined values for cmd may be defined in <fcntl.h>. Their names shall start with F_.

When a shared lock is set on a segment of a file, other processes shall be able to set shared locks on that segment or a portion of it. A shared lock prevents any other process from setting an exclusive lock on any portion of the protected area. A request for a shared lock shall fail if the file descriptor was not opened with read access.

An exclusive lock shall prevent any other process from setting a shared lock or an exclusive lock on any portion of the protected area. A request for an exclusive lock shall fail if the file descriptor was not opened with write access.

The structure flock describes the type ( l_type), starting offset ( l_whence), relative offset ( l_start), size ( l_len), and process ID ( l_pid) of the segment of the file to be affected.

The value of l_whence is SEEK_SET, SEEK_CUR, or SEEK_END, to indicate that the relative offset l_start bytes shall be measured from the start of the file, current position, or end of the file, respectively. The value of l_len is the number of consecutive bytes to be locked. The value of l_len may be negative (where the definition of off_t permits negative values of l_len). The l_pid field is only used with F_GETLK to return the process ID of the process holding a blocking lock. After a successful F_GETLK request, when a blocking lock is found, the values returned in the flock structure shall be as follows:

l_type
Type of blocking lock found.
l_whence
SEEK_SET.
l_start
Start of the blocking lock.
l_len
Length of the blocking lock.
l_pid
Process ID of the process that holds the blocking lock.

If the command is F_SETLKW and the process must wait for another process to release a lock, then the range of bytes to be locked shall be determined before the fcntl() function blocks. If the file size or file descriptor seek offset change while fcntl() is blocked, this shall not affect the range of bytes locked.

If l_len is positive, the area affected shall start at l_start and end at l_start+ l_len-1. If l_len is negative, the area affected shall start at l_start+ l_len and end at l_start-1. Locks may start and extend beyond the current end of a file, but shall not extend before the beginning of the file. A lock shall be set to extend to the largest possible value of the file offset for that file by setting l_len to 0. If such a lock also has l_start set to 0 and l_whence is set to SEEK_SET, the whole file shall be locked.

There shall be at most one type of lock set for each byte in the file. Before a successful return from an F_SETLK or an F_SETLKW request when the calling process has previously existing locks on bytes in the region specified by the request, the previous lock type for each byte in the specified region shall be replaced by the new lock type. As specified above under the descriptions of shared locks and exclusive locks, an F_SETLK or an F_SETLKW request (respectively) shall fail or block when another process has existing locks on bytes in the specified region and the type of any of those locks conflicts with the type specified in the request.

All locks associated with a file for a given process shall be removed when a file descriptor for that file is closed by that process or the process holding that file descriptor terminates. Locks are not inherited by a child process.

A potential for deadlock occurs if a process controlling a locked region is put to sleep by attempting to lock another process' locked region. If the system detects that sleeping until a locked region is unlocked would cause a deadlock, fcntl() shall fail with an [EDEADLK] error.

An unlock (F_UNLCK) request in which l_len is non-zero and the offset of the last byte of the requested segment is the maximum value for an object of type off_t, when the process has an existing lock in which l_len is 0 and which includes the last byte of the requested segment, shall be treated as a request to unlock from the start of the requested segment with an l_len equal to 0. Otherwise, an unlock (F_UNLCK) request shall attempt to unlock only the requested segment.

When the file descriptor fildes refers to a shared memory object, the behavior of fcntl() shall be the same as for a regular file except the effect of the following values for the argument cmd shall be unspecified: F_SETFL, F_GETLK, F_SETLK, and F_SETLKW.

If fildes refers to a typed memory object, the result of the fcntl() function is unspecified.

RETURN VALUE

Upon successful completion, the value returned shall depend on cmd as follows:

F_DUPFD
A new file descriptor.
F_GETFD
Value of flags defined in <fcntl.h>. The return value shall not be negative.
F_SETFD
Value other than -1.
F_GETFL
Value of file status flags and access modes. The return value is not negative.
F_SETFL
Value other than -1.
F_GETLK
Value other than -1.
F_SETLK
Value other than -1.
F_SETLKW
Value other than -1.
F_GETOWN
Value of the socket owner process or process group; this will not be -1.
F_SETOWN
Value other than -1.

Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The fcntl() function shall fail if:

EACCES or EAGAIN

The cmd argument is F_SETLK; the type of lock ( l_type) is a shared (F_RDLCK) or exclusive (F_WRLCK) lock and the segment of a file to be locked is already exclusive-locked by another process, or the type is an exclusive lock and some portion of the segment of a file to be locked is already shared-locked or exclusive-locked by another process.

EBADF
The fildes argument is not a valid open file descriptor, or the argument cmd is F_SETLK or F_SETLKW, the type of lock, l_type, is a shared lock (F_RDLCK), and fildes is not a valid file descriptor open for reading, or the type of lock, l_type, is an exclusive lock (F_WRLCK), and fildes is not a valid file descriptor open for writing.
EINTR
The cmd argument is F_SETLKW and the function was interrupted by a signal.
EINVAL
The cmd argument is invalid, or the cmd argument is F_DUPFD and arg is negative or greater than or equal to {OPEN_MAX}, or the cmd argument is F_GETLK, F_SETLK, or F_SETLKW and the data pointed to by arg is not valid, or fildes refers to a file that does not support locking.
EMFILE
The argument cmd is F_DUPFD and {OPEN_MAX} file descriptors are currently open in the calling process, or no file descriptors greater than or equal to arg are available.
ENOLCK
The argument cmd is F_SETLK or F_SETLKW and satisfying the lock or unlock request would result in the number of locked regions in the system exceeding a system-imposed limit.
EOVERFLOW
One of the values to be returned cannot be represented correctly.
EOVERFLOW
The cmd argument is F_GETLK, F_SETLK, or F_SETLKW and the smallest or, if l_len is non-zero, the largest offset of any byte in the requested segment cannot be represented correctly in an object of type off_t.

The fcntl() function may fail if:

EDEADLK
The cmd argument is F_SETLKW, the lock is blocked by a lock from another process, and putting the calling process to sleep to wait for that lock to become free would cause a deadlock.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The ellipsis in the SYNOPSIS is the syntax specified by the ISO C standard for a variable number of arguments. It is used because System V uses pointers for the implementation of file locking functions.

The arg values to F_GETFD, F_SETFD, F_GETFL, and F_SETFL all represent flag values to allow for future growth. Applications using these functions should do a read-modify-write operation on them, rather than assuming that only the values defined by this volume of IEEE Std 1003.1-2001 are valid. It is a common error to forget this, particularly in the case of F_SETFD.

This volume of IEEE Std 1003.1-2001 permits concurrent read and write access to file data using the fcntl() function; this is a change from the 1984 /usr/group standard and early proposals. Without concurrency controls, this feature may not be fully utilized without occasional loss of data.

Data losses occur in several ways. One case occurs when several processes try to update the same record, without sequencing controls; several updates may occur in parallel and the last writer "wins". Another case is a bit-tree or other internal list-based database that is undergoing reorganization. Without exclusive use to the tree segment by the updating process, other reading processes chance getting lost in the database when the index blocks are split, condensed, inserted, or deleted. While fcntl() is useful for many applications, it is not intended to be overly general and does not handle the bit-tree example well.

This facility is only required for regular files because it is not appropriate for many devices such as terminals and network connections.

Since fcntl() works with "any file descriptor associated with that file, however it is obtained", the file descriptor may have been inherited through a fork() or exec operation and thus may affect a file that another process also has open.

The use of the open file description to identify what to lock requires extra calls and presents problems if several processes are sharing an open file description, but there are too many implementations of the existing mechanism for this volume of IEEE Std 1003.1-2001 to use different specifications.

Another consequence of this model is that closing any file descriptor for a given file (whether or not it is the same open file description that created the lock) causes the locks on that file to be relinquished for that process. Equivalently, any close for any file/process pair relinquishes the locks owned on that file for that process. But note that while an open file description may be shared through fork(), locks are not inherited through fork(). Yet locks may be inherited through one of the exec functions.

The identification of a machine in a network environment is outside the scope of this volume of IEEE Std 1003.1-2001. Thus, an l_sysid member, such as found in System V, is not included in the locking structure.

Changing of lock types can result in a previously locked region being split into smaller regions.

Mandatory locking was a major feature of the 1984 /usr/group standard.

For advisory file record locking to be effective, all processes that have access to a file must cooperate and use the advisory mechanism before doing I/O on the file. Enforcement-mode record locking is important when it cannot be assumed that all processes are cooperating. For example, if one user uses an editor to update a file at the same time that a second user executes another process that updates the same file and if only one of the two processes is using advisory locking, the processes are not cooperating. Enforcement-mode record locking would protect against accidental collisions.

Secondly, advisory record locking requires a process using locking to bracket each I/O operation with lock (or test) and unlock operations. With enforcement-mode file and record locking, a process can lock the file once and unlock when all I/O operations have been completed. Enforcement-mode record locking provides a base that can be enhanced; for example, with sharable locks. That is, the mechanism could be enhanced to allow a process to lock a file so other processes could read it, but none of them could write it.

Mandatory locks were omitted for several reasons:

1.
Mandatory lock setting was done by multiplexing the set-group-ID bit in most implementations; this was confusing, at best.

2.
The relationship to file truncation as supported in 4.2 BSD was not well specified.

3.
Any publicly readable file could be locked by anyone. Many historical implementations keep the password database in a publicly readable file. A malicious user could thus prohibit logins. Another possibility would be to hold open a long-distance telephone line.

4.
Some demand-paged historical implementations offer memory mapped files, and enforcement cannot be done on that type of file.

Since sleeping on a region is interrupted with any signal, alarm() may be used to provide a timeout facility in applications requiring it. This is useful in deadlock detection. Since implementation of full deadlock detection is not always feasible, the [EDEADLK] error was made optional.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , close() , exec() , open() , sigaction() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <signal.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


coshf (3p)

 Continue to this page.


coshl (3p)

 Continue to this page.


symlink(3p)

SYMLINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

symlink - make a symbolic link to a file

SYNOPSIS

#include <unistd.h>

int symlink(const char *path1, const char *path2);

DESCRIPTION

The symlink() function shall create a symbolic link called path2 that contains the string pointed to by path1 ( path2 is the name of the symbolic link created, path1 is the string contained in the symbolic link).

The string pointed to by path1 shall be treated only as a character string and shall not be validated as a pathname.

If the symlink() function fails for any reason other than [EIO], any file named by path2 shall be unaffected.

RETURN VALUE

Upon successful completion, symlink() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The symlink() function shall fail if:

EACCES
Write permission is denied in the directory where the symbolic link is being created, or search permission is denied for a component of the path prefix of path2.
EEXIST
The path2 argument names an existing file or symbolic link.
EIO
An I/O error occurs while reading from or writing to the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the path2 argument.
ENAMETOOLONG
The length of the path2 argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX} or the length of the path1 argument is longer than {SYMLINK_MAX}.
ENOENT
A component of path2 does not name an existing file or path2 is an empty string.
ENOSPC
The directory in which the entry for the new symbolic link is being placed cannot be extended because no space is left on the file system containing the directory, or the new symbolic link cannot be created because no space is left on the file system which shall contain the link, or the file system is out of file-allocation resources.
ENOTDIR
A component of the path prefix of path2 is not a directory.
EROFS
The new symbolic link would reside on a read-only file system.

The symlink() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path2 argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path2 argument, the length of the substituted pathname string exceeded {PATH_MAX} bytes (including the terminating null byte), or the length of the string pointed to by path1 exceeded {SYMLINK_MAX}.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Like a hard link, a symbolic link allows a file to have multiple logical names. The presence of a hard link guarantees the existence of a file, even after the original name has been removed. A symbolic link provides no such assurance; in fact, the file named by the path1 argument need not exist when the link is created. A symbolic link can cross file system boundaries.

Normal permission checks are made on each component of the symbolic link pathname during its resolution.

RATIONALE

Since IEEE Std 1003.1-2001 does not require any association of file times with symbolic links, there is no requirement that file times be updated by symlink().

FUTURE DIRECTIONS

None.

SEE ALSO

lchown() , link() , lstat() , open() , readlink() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


log10f (3p)

 Continue to this page.


log10l (3p)

 Continue to this page.


pselect (3p)

 Continue to this page.


ftok(3p)

FTOK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ftok - generate an IPC key

SYNOPSIS

#include <sys/ipc.h>

key_t ftok(const char *path, int id);

DESCRIPTION

The ftok() function shall return a key based on path and id that is usable in subsequent calls to msgget(), semget(), and shmget(). The application shall ensure that the path argument is the pathname of an existing file that the process is able to stat().

The ftok() function shall return the same key value for all paths that name the same file, when called with the same id value, and return different key values when called with different id values or with paths that name different files existing on the same file system at the same time. It is unspecified whether ftok() shall return the same key value when called again after the file named by path is removed and recreated with the same name.

Only the low-order 8-bits of id are significant. The behavior of ftok() is unspecified if these bits are 0.

RETURN VALUE

Upon successful completion, ftok() shall return a key. Otherwise, ftok() shall return (key_t)-1 and set errno to indicate the error.

ERRORS

The ftok() function shall fail if:

EACCES
Search permission is denied for a component of the path prefix.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.

The ftok() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

Getting an IPC Key

The following example gets a unique key that can be used by the IPC functions semget(), msgget(), and shmget(). The key returned by ftok() for this example is based on the ID value S and the pathname /tmp.

#include <sys/ipc.h>
...
key_t key;
char *path = "/tmp";
int id = 'S';

key = ftok(path, id);

Saving an IPC Key

The following example gets a unique key based on the pathname /tmp and the ID value a. It also assigns the value of the resulting key to the semkey variable so that it will be available to a later call to semget(), msgget(), or shmget().

#include <sys/ipc.h>
...
key_t semkey;

if ((semkey = ftok("/tmp", 'a')) == (key_t) -1) {
    perror("IPC error: ftok"); exit(1);
}

APPLICATION USAGE

For maximum portability, id should be a single-byte character.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

msgget() , semget() , shmget() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/ipc.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nice(3p)

NICE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nice - change the nice value of a process

SYNOPSIS

#include <unistd.h>

int nice(int incr);

DESCRIPTION

The nice() function shall add the value of incr to the nice value of the calling process. A process' nice value is a non-negative number for which a more positive value shall result in less favorable scheduling.

A maximum nice value of 2*{NZERO}-1 and a minimum nice value of 0 shall be imposed by the system. Requests for values above or below these limits shall result in the nice value being set to the corresponding limit. Only a process with appropriate privileges can lower the nice value.

Calling the nice() function has no effect on the priority of processes or threads with policy SCHED_FIFO or SCHED_RR. The effect on processes or threads with other scheduling policies is implementation-defined.

The nice value set with nice() shall be applied to the process. If the process is multi-threaded, the nice value shall affect all system scope threads in the process.

As -1 is a permissible return value in a successful situation, an application wishing to check for error situations should set errno to 0, then call nice(), and if it returns -1, check to see whether errno is non-zero.

RETURN VALUE

Upon successful completion, nice() shall return the new nice value -{NZERO}. Otherwise, -1 shall be returned, the process' nice value shall not be changed, and errno shall be set to indicate the error.

ERRORS

The nice() function shall fail if:

EPERM
The incr argument is negative and the calling process does not have appropriate privileges.

The following sections are informative.

EXAMPLES

Changing the Nice Value

The following example adds the value of the incr argument, -20, to the nice value of the calling process.

#include <unistd.h>
...
int incr = -20;
int ret;

ret = nice(incr);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getpriority() , setpriority() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


catopen(3p)

CATOPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

catopen - open a message catalog

SYNOPSIS

#include <nl_types.h>

nl_catd catopen(const char *name, int oflag);

DESCRIPTION

The catopen() function shall open a message catalog and return a message catalog descriptor. The name argument specifies the name of the message catalog to be opened. If name contains a '/' , then name specifies a complete name for the message catalog. Otherwise, the environment variable NLSPATH is used with name substituted for the %N conversion specification (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables). If NLSPATH exists in the environment when the process starts, then if the process has appropriate privileges, the behavior of catopen() is undefined. If NLSPATH does not exist in the environment, or if a message catalog cannot be found in any of the components specified by NLSPATH, then an implementation-defined default path shall be used. This default may be affected by the setting of LC_MESSAGES if the value of oflag is NL_CAT_LOCALE, or the LANG environment variable if oflag is 0.

A message catalog descriptor shall remain valid in a process until that process closes it, or a successful call to one of the exec functions. A change in the setting of the LC_MESSAGES category may invalidate existing open catalogs.

If a file descriptor is used to implement message catalog descriptors, the FD_CLOEXEC flag shall be set; see <fcntl.h>.

If the value of the oflag argument is 0, the LANG environment variable is used to locate the catalog without regard to the LC_MESSAGES category. If the oflag argument is NL_CAT_LOCALE, the LC_MESSAGES category is used to locate the message catalog (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables).

RETURN VALUE

Upon successful completion, catopen() shall return a message catalog descriptor for use on subsequent calls to catgets() and catclose(). Otherwise, catopen() shall return ( nl_catd) -1 and set errno to indicate the error.

ERRORS

The catopen() function may fail if:

EACCES
Search permission is denied for the component of the path prefix of the message catalog or read permission is denied for the message catalog.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG
The length of a pathname of the message catalog exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.
ENFILE
Too many files are currently open in the system.
ENOENT
The message catalog does not exist or the name argument points to an empty string.
ENOMEM
Insufficient storage space is available.
ENOTDIR
A component of the path prefix of the message catalog is not a directory.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Some implementations of catopen() use malloc() to allocate space for internal buffer areas. The catopen() function may fail if there is insufficient storage space available to accommodate these buffers.

Conforming applications must assume that message catalog descriptors are not valid after a call to one of the exec functions.

Application writers should be aware that guidelines for the location of message catalogs have not yet been developed. Therefore they should take care to avoid conflicting with catalogs used by other applications and the standard utilities.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

catclose() , catgets() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <nl_types.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


msgsnd(3p)

MSGSND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

msgsnd - XSI message send operation

SYNOPSIS

#include <sys/msg.h>

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

DESCRIPTION

The msgsnd() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The msgsnd() function shall send a message to the queue associated with the message queue identifier specified by msqid.

The application shall ensure that the argument msgp points to a user-defined buffer that contains first a field of type long specifying the type of the message, and then a data portion that holds the data bytes of the message. The structure below is an example of what this user-defined buffer might look like:

struct mymsg {
    long   mtype;       /* Message type. */
    char   mtext[1];    /* Message text. */
}

The structure member mtype is a non-zero positive type long that can be used by the receiving process for message selection.

The structure member mtext is any text of length msgsz bytes. The argument msgsz can range from 0 to a system-imposed maximum.

The argument msgflg specifies the action to be taken if one or more of the following is true:

*
The number of bytes already on the queue is equal to msg_qbytes; see <sys/msg.h>.

*
The total number of messages on all queues system-wide is equal to the system-imposed limit.

These actions are as follows:

*
If (msgflg & IPC_NOWAIT) is non-zero, the message shall not be sent and the calling thread shall return immediately.

*
If (msgflg & IPC_NOWAIT) is 0, the calling thread shall suspend execution until one of the following occurs:
*
The condition responsible for the suspension no longer exists, in which case the message is sent.

*
The message queue identifier msqid is removed from the system; when this occurs, errno shall be set equal to [EIDRM] and -1 shall be returned.

*
The calling thread receives a signal that is to be caught; in this case the message is not sent and the calling thread resumes execution in the manner prescribed in sigaction() .

Upon successful completion, the following actions are taken with respect to the data structure associated with msqid; see <sys/msg.h>:

*
msg_qnum shall be incremented by 1.

*
msg_lspid shall be set equal to the process ID of the calling process.

*
msg_stime shall be set equal to the current time.

RETURN VALUE

Upon successful completion, msgsnd() shall return 0; otherwise, no message shall be sent, msgsnd() shall return -1, and errno shall be set to indicate the error.

ERRORS

The msgsnd() function shall fail if:

EACCES
Operation permission is denied to the calling process; see XSI Interprocess Communication .
EAGAIN
The message cannot be sent for one of the reasons cited above and (msgflg & IPC_NOWAIT) is non-zero.
EIDRM
The message queue identifier msqid is removed from the system.
EINTR
The msgsnd() function was interrupted by a signal.
EINVAL
The value of msqid is not a valid message queue identifier, or the value of mtype is less than 1; or the value of msgsz is less than 0 or greater than the system-imposed limit.

The following sections are informative.

EXAMPLES

Sending a Message

The following example sends a message to the queue identified by the msqid argument (assuming that value has previously been set). This call specifies that an error should be reported if no message is available. The message size is calculated directly using the sizeof operator.

#include <sys/msg.h>
...
int result;
int msqid;
struct message {
    long type;
    char text[20];
} msg;

msg.type = 1;
strcpy(msg.text, "This is message 1");
...
result = msgsnd(msqid, (void *) &msg, sizeof(msg.text), IPC_NOWAIT);

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication (IPC). Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , mq_close() , mq_getattr() , mq_notify() , mq_open() , mq_receive() , mq_send() , mq_setattr() , mq_unlink() , msgctl() , msgget() , msgrcv() , sigaction() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/msg.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


srand48 (3p)

 Continue to this page.


qsort(3p)

QSORT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

qsort - sort a table of data

SYNOPSIS

#include <stdlib.h>

void qsort(void *base, size_t nel, size_t width,
int (*compar)(const void *, const void *));

DESCRIPTION

The qsort() function shall sort an array of nel objects, the initial element of which is pointed to by base. The size of each object, in bytes, is specified by the width argument. If the nel argument has the value zero, the comparison function pointed to by compar shall not be called and no rearrangement shall take place.

The application shall ensure that the comparison function pointed to by compar does not alter the contents of the array. The implementation may reorder elements of the array between calls to the comparison function, but shall not alter the contents of any individual element.

When the same objects (consisting of width bytes, irrespective of their current positions in the array) are passed more than once to the comparison function, the results shall be consistent with one another. That is, they shall define a total ordering on the array.

The contents of the array shall be sorted in ascending order according to a comparison function. The compar argument is a pointer to the comparison function, which is called with two arguments that point to the elements being compared. The application shall ensure that the function returns an integer less than, equal to, or greater than 0, if the first argument is considered respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is unspecified.

RETURN VALUE

The qsort() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The comparison function need not compare every byte, so arbitrary data may be contained in the elements in addition to the values being compared.

RATIONALE

The requirement that each argument (hereafter referred to as p) to the comparison function is a pointer to elements of the array implies that for every call, for each argument separately, all of the following expressions are nonzero:

((char *)p - (char *)base) % width == 0
(char *)p >= (char *)base
(char *)p < (char *)base + nel * width

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pathconf(3p)

FPATHCONF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fpathconf, pathconf - get configurable pathname variables

SYNOPSIS

#include <unistd.h>

long fpathconf(int fildes, int name);
long pathconf(const char *path, int name);

DESCRIPTION

The fpathconf() and pathconf() functions shall determine the current value of a configurable limit or option (variable) that is associated with a file or directory.

For pathconf(), the path argument points to the pathname of a file or directory.

For fpathconf(), the fildes argument is an open file descriptor.

The name argument represents the variable to be queried relative to that file or directory. Implementations shall support all of the variables listed in the following table and may support others. The variables in the following table come from <limits.h> or <unistd.h> and the symbolic constants, defined in <unistd.h>, are the corresponding values used for name.
Variable | Value of name | Requirements
{FILESIZEBITS} | _PC_FILESIZEBITS | 3,4
{LINK_MAX} | _PC_LINK_MAX | 1
{MAX_CANON} | _PC_MAX_CANON | 2
{MAX_INPUT} | _PC_MAX_INPUT | 2
{NAME_MAX} | _PC_NAME_MAX | 3,4
{PATH_MAX} | _PC_PATH_MAX | 4,5
{PIPE_BUF} | _PC_PIPE_BUF | 6
{POSIX_ALLOC_SIZE_MIN} | _PC_ALLOC_SIZE_MIN |
{POSIX_REC_INCR_XFER_SIZE} | _PC_REC_INCR_XFER_SIZE |
{POSIX_REC_MAX_XFER_SIZE} | _PC_REC_MAX_XFER_SIZE |
{POSIX_REC_MIN_XFER_SIZE} | _PC_REC_MIN_XFER_SIZE |
{POSIX_REC_XFER_ALIGN} | _PC_REC_XFER_ALIGN |
{SYMLINK_MAX} | _PC_SYMLINK_MAX | 4,9
_POSIX_CHOWN_RESTRICTED | _PC_CHOWN_RESTRICTED | 7
_POSIX_NO_TRUNC | _PC_NO_TRUNC | 3,4
_POSIX_VDISABLE | _PC_VDISABLE | 2
_POSIX_ASYNC_IO | _PC_ASYNC_IO | 8
_POSIX_PRIO_IO | _PC_PRIO_IO | 8
_POSIX_SYNC_IO | _PC_SYNC_IO | 8

Requirements

1.
If path or fildes refers to a directory, the value returned shall apply to the directory itself.

2.
If path or fildes does not refer to a terminal file, it is unspecified whether an implementation supports an association of the variable name with the specified file.

3.
If path or fildes refers to a directory, the value returned shall apply to filenames within the directory.

4.
If path or fildes does not refer to a directory, it is unspecified whether an implementation supports an association of the variable name with the specified file.

5.
If path or fildes refers to a directory, the value returned shall be the maximum length of a relative pathname when the specified directory is the working directory.

6.
If path refers to a FIFO, or fildes refers to a pipe or FIFO, the value returned shall apply to the referenced object. If path or fildes refers to a directory, the value returned shall apply to any FIFO that exists or can be created within the directory. If path or fildes refers to any other type of file, it is unspecified whether an implementation supports an association of the variable name with the specified file.

7.
If path or fildes refers to a directory, the value returned shall apply to any files, other than directories, that exist or can be created within the directory.

8.
If path or fildes refers to a directory, it is unspecified whether an implementation supports an association of the variable name with the specified file.

9.
If path or fildes refers to a directory, the value returned shall be the maximum length of the string that a symbolic link in that directory can contain.

RETURN VALUE

If name is an invalid value, both pathconf() and fpathconf() shall return -1 and set errno to indicate the error.

If the variable corresponding to name has no limit for the path or file descriptor, both pathconf() and fpathconf() shall return -1 without changing errno. If the implementation needs to use path to determine the value of name and the implementation does not support the association of name with the file specified by path, or if the process did not have appropriate privileges to query the file specified by path, or path does not exist, pathconf() shall return -1 and set errno to indicate the error.

If the implementation needs to use fildes to determine the value of name and the implementation does not support the association of name with the file specified by fildes, or if fildes is an invalid file descriptor, fpathconf() shall return -1 and set errno to indicate the error.

Otherwise, pathconf() or fpathconf() shall return the current variable value for the file or directory without changing errno. The value returned shall not be more restrictive than the corresponding value available to the application when it was compiled with the implementation's <limits.h> or <unistd.h>.

ERRORS

The pathconf() function shall fail if:

EINVAL
The value of name is not valid.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.

The pathconf() function may fail if:

EACCES
Search permission is denied for a component of the path prefix.
EINVAL
The implementation does not support an association of the variable name with the specified file.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.

The fpathconf() function shall fail if:

EINVAL
The value of name is not valid.

The fpathconf() function may fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINVAL
The implementation does not support an association of the variable name with the specified file.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The pathconf() function was proposed immediately after the sysconf() function when it was realized that some configurable values may differ across file system, directory, or device boundaries.

For example, {NAME_MAX} frequently changes between System V and BSD-based file systems; System V uses a maximum of 14, BSD 255. On an implementation that provides both types of file systems, an application would be forced to limit all pathname components to 14 bytes, as this would be the value specified in <limits.h> on such a system.

Therefore, various useful values can be queried on any pathname or file descriptor, assuming that the appropriate permissions are in place.

The value returned for the variable {PATH_MAX} indicates the longest relative pathname that could be given if the specified directory is the process' current working directory. A process may not always be able to generate a name that long and use it if a subdirectory in the pathname crosses into a more restrictive file system.

The value returned for the variable _POSIX_CHOWN_RESTRICTED also applies to directories that do not have file systems mounted on them. The value may change when crossing a mount point, so applications that need to know should check for each directory. (An even easier check is to try the chown() function and look for an error in case it happens.)

Unlike the values returned by sysconf(), the pathname-oriented variables are potentially more volatile and are not guaranteed to remain constant throughout the process' lifetime. For example, in between two calls to pathconf(), the file system in question may have been unmounted and remounted with different characteristics.

Also note that most of the errors are optional. If one of the variables always has the same value on an implementation, the implementation need not look at path or fildes to return that value and is, therefore, not required to detect any of the errors except the meaning of [EINVAL] that indicates that the value of name is not valid for that variable.

If the value of any of the limits is unspecified (logically infinite), they will not be defined in <limits.h> and the pathconf() and fpathconf() functions return -1 without changing errno. This can be distinguished from the case of giving an unrecognized name argument because errno is set to [EINVAL] in this case.

Since -1 is a valid return value for the pathconf() and fpathconf() functions, applications should set errno to zero before calling them and check errno only if the return value is -1.

For the case of {SYMLINK_MAX}, since both pathconf() and open() follow symbolic links, there is no way that path or fildes could refer to a symbolic link.

FUTURE DIRECTIONS

None.

SEE ALSO

confstr() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <unistd.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswxdigit(3p)

ISWXDIGIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswxdigit - test for a hexadecimal digit wide-character code

SYNOPSIS

#include <wctype.h>

int iswxdigit(wint_t wc);

DESCRIPTION

The iswxdigit() function shall test whether wc is a wide-character code representing a character of class xdigit in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswxdigit() function shall return non-zero if wc is a hexadecimal digit wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswupper(3p)

ISWUPPER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswupper - test for an uppercase letter wide-character code

SYNOPSIS

#include <wctype.h>

int iswupper(wint_t wc);

DESCRIPTION

The iswupper() function shall test whether wc is a wide-character code representing a character of class upper in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswupper() function shall return non-zero if wc is an uppercase letter wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


va_end (3p)

 Continue to this page.


putwchar(3p)

PUTWCHAR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

putwchar - put a wide character on a stdout stream

SYNOPSIS

#include <wchar.h>

wint_t putwchar(wchar_t wc);

DESCRIPTION

The function call putwchar(wc) shall be equivalent to putwc(wc,stdout).

RETURN VALUE

Refer to fputwc() .

ERRORS

Refer to fputwc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fputwc() , putwc() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


bsearch(3p)

BSEARCH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bsearch - binary search a sorted table

SYNOPSIS

#include <stdlib.h>

void *bsearch(const void *key, const void *base, size_t nel,
size_t width, int (*compar)(const void *, const void *));

DESCRIPTION

The bsearch() function shall search an array of nel objects, the initial element of which is pointed to by base, for an element that matches the object pointed to by key. The size of each element in the array is specified by width. If the nel argument has the value zero, the comparison function pointed to by compar shall not be called and no match shall be found.

The comparison function pointed to by compar shall be called with two arguments that point to the key object and to an array element, in that order.

The application shall ensure that the comparison function pointed to by compar does not alter the contents of the array. The implementation may reorder elements of the array between calls to the comparison function, but shall not alter the contents of any individual element.

The implementation shall ensure that the first argument is always a pointer to the key.

When the same objects (consisting of width bytes, irrespective of their current positions in the array) are passed more than once to the comparison function, the results shall be consistent with one another. That is, the same object shall always compare the same way with the key.

The application shall ensure that the function returns an integer less than, equal to, or greater than 0 if the key object is considered, respectively, to be less than, to match, or to be greater than the array element. The application shall ensure that the array consists of all the elements that compare less than, all the elements that compare equal to, and all the elements that compare greater than the key object, in that order.

RETURN VALUE

The bsearch() function shall return a pointer to a matching member of the array, or a null pointer if no match is found. If two or more members compare equal, which member is returned is unspecified.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The example below searches a table containing pointers to nodes consisting of a string and its length. The table is ordered alphabetically on the string in the node pointed to by each entry.

The code fragment below reads in strings and either finds the corresponding node and prints out the string and its length, or prints an error message.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TABSIZE    1000

struct node {                  /* These are stored in the table. */
    char *string;
    int length;
};
struct node table[TABSIZE];    /* Table to be searched. */
    .
    .
    .
{
    struct node *node_ptr, node;
    /* Routine to compare 2 nodes. */
    int node_compare(const void *, const void *);
    char str_space[20];   /* Space to read string into. */
    .
    .
    .
    node.string = str_space;
    while (scanf("%s", node.string) != EOF) {
        node_ptr = (struct node *)bsearch((void *)(&node),
               (void *)table, TABSIZE,
               sizeof(struct node), node_compare);
        if (node_ptr != NULL) {
            (void)printf("string = %20s, length = %d\n",
                node_ptr->string, node_ptr->length);
        } else {
            (void)printf("not found: %s\n", node.string);
        }
    }
}
/*
    This routine compares two nodes based on an
    alphabetical ordering of the string field.
*/
int
node_compare(const void *node1, const void *node2)
{
    return strcoll(((const struct node *)node1)->string,
        ((const struct node *)node2)->string);
}

APPLICATION USAGE

The pointers to the key and the element at the base of the table should be of type pointer-to-element.

The comparison function need not compare every byte, so arbitrary data may be contained in the elements in addition to the values being compared.

In practice, the array is usually sorted according to the comparison function.

RATIONALE

The requirement that the second argument (hereafter referred to as p) to the comparison function is a pointer to an element of the array implies that for every call all of the following expressions are non-zero:

((char *)p - (char *(base) % width == 0
(char *)p >= (char *)base
(char *)p < (char *)base + nel * width

FUTURE DIRECTIONS

None.

SEE ALSO

hcreate() , lsearch() , qsort() , tsearch() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


optarg (3p)

 Continue to this page.


strcoll(3p)

STRCOLL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strcoll - string comparison using collating information

SYNOPSIS

#include <string.h>

int strcoll(const char *s1, const char *s2);

DESCRIPTION

The strcoll() function shall compare the string pointed to by s1 to the string pointed to by s2, both interpreted as appropriate to the LC_COLLATE category of the current locale.

The strcoll() function shall not change the setting of errno if successful.

Since no return value is reserved to indicate an error, an application wishing to check for error situations should set errno to 0, then call strcoll(), then check errno.

RETURN VALUE

Upon successful completion, strcoll() shall return an integer greater than, equal to, or less than 0, according to whether the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2 when both are interpreted as appropriate to the current locale. On error, strcoll() may set errno, but no return value is reserved to indicate an error.

ERRORS

The strcoll() function may fail if:

EINVAL
The s1 or s2 arguments contain characters outside the domain of the collating sequence.

The following sections are informative.

EXAMPLES

Comparing Nodes

The following example uses an application-defined function, node_compare(), to compare two nodes based on an alphabetical ordering of the string field.

#include <string.h>
...
struct node { /* These are stored in the table. */
    char *string;
    int length;
};
...
int node_compare(const void *node1, const void *node2)
{
    return strcoll(((const struct node *)node1)->string,
        ((const struct node *)node2)->string);
}
...

APPLICATION USAGE

The strxfrm() and strcmp() functions should be used for sorting large lists.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strcmp() , strxfrm() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fesetround (3p)

 Continue to this page.


hypotf (3p)

 Continue to this page.


hypotl (3p)

 Continue to this page.


toupper(3p)

TOUPPER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

toupper - transliterate lowercase characters to uppercase

SYNOPSIS

#include <ctype.h>

int toupper(int c);

DESCRIPTION

The toupper() function has as a domain a type int, the value of which is representable as an unsigned char or the value of EOF. If the argument has any other value, the behavior is undefined. If the argument of toupper() represents a lowercase letter, and there exists a corresponding uppercase letter (as defined by character type information in the program locale category LC_CTYPE ), the result shall be the corresponding uppercase letter. All other arguments in the domain are returned unchanged.

RETURN VALUE

Upon successful completion, toupper() shall return the uppercase letter corresponding to the argument passed.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


acosf (3p)

 Continue to this page.


sched_yield(3p)

SCHED_YIELD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched_yield - yield the processor

SYNOPSIS

#include <sched.h>

int sched_yield(void);

DESCRIPTION

The sched_yield() function shall force the running thread to relinquish the processor until it again becomes the head of its thread list. It takes no arguments.

RETURN VALUE

The sched_yield() function shall return 0 if it completes successfully; otherwise, it shall return a value of -1 and set errno to indicate the error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


acosh(3p)

ACOSH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

acosh, acoshf, acoshl - inverse hyperbolic cosine functions

SYNOPSIS

#include <math.h>

double acosh(double x);
float acoshf(float x);
long double acoshl(long double x);

DESCRIPTION

These functions shall compute the inverse hyperbolic cosine of their argument x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the inverse hyperbolic cosine of their argument.

For finite values of x < 1, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is +1, +0 shall be returned.

If x is +Inf, +Inf shall be returned.

If x is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is finite and less than +1.0, or is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cosh() , feclearexcept() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


acosl (3p)

 Continue to this page.


sigemptyset(3p)

SIGEMPTYSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigemptyset - initialize and empty a signal set

SYNOPSIS

#include <signal.h>

int sigemptyset(sigset_t *set);

DESCRIPTION

The sigemptyset() function initializes the signal set pointed to by set, such that all signals defined in IEEE Std 1003.1-2001 are excluded.

RETURN VALUE

Upon successful completion, sigemptyset() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The implementation of the sigemptyset() (or sigfillset()) function could quite trivially clear (or set) all the bits in the signal set. Alternatively, it would be reasonable to initialize part of the structure, such as a version field, to permit binary-compatibility between releases where the size of the set varies. For such reasons, either sigemptyset() or sigfillset() must be called prior to any other use of the signal set, even if such use is read-only (for example, as an argument to sigpending()). This function is not intended for dynamic allocation.

The sigfillset() and sigemptyset() functions require that the resulting signal set include (or exclude) all the signals defined in this volume of IEEE Std 1003.1-2001. Although it is outside the scope of this volume of IEEE Std 1003.1-2001 to place this requirement on signals that are implemented as extensions, it is recommended that implementation-defined signals also be affected by these functions. However, there may be a good reason for a particular signal not to be affected. For example, blocking or ignoring an implementation-defined signal may have undesirable side effects, whereas the default action for that signal is harmless. In such a case, it would be preferable for such a signal to be excluded from the signal set returned by sigfillset().

In early proposals there was no distinction between invalid and unsupported signals (the names of optional signals that were not supported by an implementation were not defined by that implementation). The [EINVAL] error was thus specified as a required error for invalid signals. With that distinction, it is not necessary to require implementations of these functions to determine whether an optional signal is actually supported, as that could have a significant performance impact for little value. The error could have been required for invalid signals and optional for unsupported signals, but this seemed unnecessarily complex. Thus, the error is optional in both cases.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , sigaction() , sigaddset() , sigdelset() , sigfillset() , sigismember() , sigpending() , sigprocmask() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


timer_settime (3p)

 Continue to this page.


sigdelset(3p)

SIGDELSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigdelset - delete a signal from a signal set

SYNOPSIS

#include <signal.h>

int sigdelset(sigset_t *set, int signo);

DESCRIPTION

The sigdelset() function deletes the individual signal specified by signo from the signal set pointed to by set.

Applications should call either sigemptyset() or sigfillset() at least once for each object of type sigset_t prior to any other use of that object. If such an object is not initialized in this way, but is nonetheless supplied as an argument to any of pthread_sigmask(), sigaction(), sigaddset(), sigdelset(), sigismember(), sigpending(), sigprocmask(), sigsuspend(), sigtimedwait(), sigwait(), or sigwaitinfo(), the results are undefined.

RETURN VALUE

Upon successful completion, sigdelset() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The sigdelset() function may fail if:

EINVAL
The signo argument is not a valid signal number, or is an unsupported signal number.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , sigaction() , sigaddset() , sigemptyset() , sigfillset() , sigismember() , sigpending() , sigprocmask() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_barrierattr_init(3p)

PTHREAD_BARRIERATTR_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_barrierattr_destroy, pthread_barrierattr_init - destroy and initialize the barrier attributes object (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_barrierattr_destroy(pthread_barrierattr_t *attr);
int pthread_barrierattr_init(pthread_barrierattr_t *attr);

DESCRIPTION

The pthread_barrierattr_destroy() function shall destroy a barrier attributes object. A destroyed attr attributes object can be reinitialized using pthread_barrierattr_init(); the results of otherwise referencing the object after it has been destroyed are undefined. An implementation may cause pthread_barrierattr_destroy() to set the object referenced by attr to an invalid value.

The pthread_barrierattr_init() function shall initialize a barrier attributes object attr with the default value for all of the attributes defined by the implementation.

Results are undefined if pthread_barrierattr_init() is called specifying an already initialized attr attributes object.

After a barrier attributes object has been used to initialize one or more barriers, any function affecting the attributes object (including destruction) shall not affect any previously initialized barrier.

RETURN VALUE

If successful, the pthread_barrierattr_destroy() and pthread_barrierattr_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_barrierattr_destroy() function may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_barrierattr_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the barrier attributes object.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_barrierattr_destroy() and pthread_barrierattr_init() functions are part of the Barriers option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_barrierattr_getpshared() , pthread_barrierattr_setpshared() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>.

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


confstr(3p)

CONFSTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

confstr - get configurable variables

SYNOPSIS

#include <unistd.h>

size_t confstr(int name, char *buf, size_t len);

DESCRIPTION

The confstr() function shall return configuration-defined string values. Its use and purpose are similar to sysconf(), but it is used where string values rather than numeric values are returned.

The name argument represents the system variable to be queried. The implementation shall support the following name values, defined in <unistd.h>. It may support others:

_CS_PATH
_CS_POSIX_V6_ILP32_OFF32_CFLAGS
_CS_POSIX_V6_ILP32_OFF32_LDFLAGS
_CS_POSIX_V6_ILP32_OFF32_LIBS
_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS
_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS
_CS_POSIX_V6_ILP32_OFFBIG_LIBS
_CS_POSIX_V6_LP64_OFF64_CFLAGS
_CS_POSIX_V6_LP64_OFF64_LDFLAGS
_CS_POSIX_V6_LP64_OFF64_LIBS
_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS
_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS
_CS_POSIX_V6_LPBIG_OFFBIG_LIBS
_CS_POSIX_V6_WIDTH_RESTRICTED_ENVS

_CS_XBS5_ILP32_OFF32_CFLAGS (LEGACY)
_CS_XBS5_ILP32_OFF32_LDFLAGS (LEGACY)
_CS_XBS5_ILP32_OFF32_LIBS (LEGACY)
_CS_XBS5_ILP32_OFF32_LINTFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_CFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LDFLAGS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LIBS (LEGACY)
_CS_XBS5_ILP32_OFFBIG_LINTFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_CFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_LDFLAGS (LEGACY)
_CS_XBS5_LP64_OFF64_LIBS (LEGACY)
_CS_XBS5_LP64_OFF64_LINTFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_CFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LDFLAGS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LIBS (LEGACY)
_CS_XBS5_LPBIG_OFFBIG_LINTFLAGS (LEGACY)

If len is not 0, and if name has a configuration-defined value, confstr() shall copy that value into the len-byte buffer pointed to by buf. If the string to be returned is longer than len bytes, including the terminating null, then confstr() shall truncate the string to len-1 bytes and null-terminate the result. The application can detect that the string was truncated by comparing the value returned by confstr() with len.

If len is 0 and buf is a null pointer, then confstr() shall still return the integer value as defined below, but shall not return a string. If len is 0 but buf is not a null pointer, the result is unspecified.

If the implementation supports the POSIX shell option, the string stored in buf after a call to:

confstr(_CS_PATH, buf, sizeof(buf))

can be used as a value of the PATH environment variable that accesses all of the standard utilities of IEEE Std 1003.1-2001, if the return value is less than or equal to sizeof( buf).

RETURN VALUE

If name has a configuration-defined value, confstr() shall return the size of buffer that would be needed to hold the entire configuration-defined value including the terminating null. If this return value is greater than len, the string returned in buf is truncated.

If name is invalid, confstr() shall return 0 and set errno to indicate the error.

If name does not have a configuration-defined value, confstr() shall return 0 and leave errno unchanged.

ERRORS

The confstr() function shall fail if:

EINVAL
The value of the name argument is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

An application can distinguish between an invalid name parameter value and one that corresponds to a configurable variable that has no configuration-defined value by checking if errno is modified. This mirrors the behavior of sysconf().

The original need for this function was to provide a way of finding the configuration-defined default value for the environment variable PATH . Since PATH can be modified by the user to include directories that could contain utilities replacing the standard utilities in the Shell and Utilities volume of IEEE Std 1003.1-2001, applications need a way to determine the system-supplied PATH environment variable value that contains the correct search path for the standard utilities.

An application could use:

confstr(name, (char *)NULL, (size_t)0)

to find out how big a buffer is needed for the string value; use malloc() to allocate a buffer to hold the string; and call confstr() again to get the string. Alternately, it could allocate a fixed, static buffer that is big enough to hold most answers (perhaps 512 or 1024 bytes), but then use malloc() to allocate a larger buffer if it finds that this is too small.

RATIONALE

Application developers can normally determine any configuration variable by means of reading from the stream opened by a call to:

popen("command -p getconf variable", "r");

The confstr() function with a name argument of _CS_PATH returns a string that can be used as a PATH environment variable setting that will reference the standard shell and utilities as described in the Shell and Utilities volume of IEEE Std 1003.1-2001.

The confstr() function copies the returned string into a buffer supplied by the application instead of returning a pointer to a string. This allows a cleaner function in some implementations (such as those with lightweight threads) and resolves questions about when the application must copy the string returned.

FUTURE DIRECTIONS

None.

SEE ALSO

pathconf() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, c99

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sleep(3p)

SLEEP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sleep - suspend execution for an interval of time

SYNOPSIS

#include <unistd.h>

unsigned sleep(unsigned seconds);

DESCRIPTION

The sleep() function shall cause the calling thread to be suspended from execution until either the number of realtime seconds specified by the argument seconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested due to the scheduling of other activity by the system.

If a SIGALRM signal is generated for the calling process during execution of sleep() and if the SIGALRM signal is being ignored or blocked from delivery, it is unspecified whether sleep() returns when the SIGALRM signal is scheduled. If the signal is being blocked, it is also unspecified whether it remains pending after sleep() returns or it is discarded.

If a SIGALRM signal is generated for the calling process during execution of sleep(), except as a result of a prior call to alarm(), and if the SIGALRM signal is not being ignored or blocked from delivery, it is unspecified whether that signal has any effect other than causing sleep() to return.

If a signal-catching function interrupts sleep() and examines or changes either the time a SIGALRM is scheduled to be generated, the action associated with the SIGALRM signal, or whether the SIGALRM signal is blocked from delivery, the results are unspecified.

If a signal-catching function interrupts sleep() and calls siglongjmp() or longjmp() to restore an environment saved prior to the sleep() call, the action associated with the SIGALRM signal and the time at which a SIGALRM signal is scheduled to be generated are unspecified. It is also unspecified whether the SIGALRM signal is blocked, unless the process' signal mask is restored as part of the environment.

Interactions between sleep() and any of setitimer(), ualarm(), or usleep() are unspecified.

RETURN VALUE

If sleep() returns because the requested time has elapsed, the value returned shall be 0. If sleep() returns due to delivery of a signal, the return value shall be the "unslept" amount (the requested time minus the time actually slept) in seconds.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

There are two general approaches to the implementation of the sleep() function. One is to use the alarm() function to schedule a SIGALRM signal and then suspend the process waiting for that signal. The other is to implement an independent facility. This volume of IEEE Std 1003.1-2001 permits either approach.

In order to comply with the requirement that no primitive shall change a process attribute unless explicitly described by this volume of IEEE Std 1003.1-2001, an implementation using SIGALRM must carefully take into account any SIGALRM signal scheduled by previous alarm() calls, the action previously established for SIGALRM, and whether SIGALRM was blocked. If a SIGALRM has been scheduled before the sleep() would ordinarily complete, the sleep() must be shortened to that time and a SIGALRM generated (possibly simulated by direct invocation of the signal-catching function) before sleep() returns. If a SIGALRM has been scheduled after the sleep() would ordinarily complete, it must be rescheduled for the same time before sleep() returns. The action and blocking for SIGALRM must be saved and restored.

Historical implementations often implement the SIGALRM-based version using alarm() and pause(). One such implementation is prone to infinite hangups, as described in pause() . Another such implementation uses the C-language setjmp() and longjmp() functions to avoid that window. That implementation introduces a different problem: when the SIGALRM signal interrupts a signal-catching function installed by the user to catch a different signal, the longjmp() aborts that signal-catching function. An implementation based on sigprocmask(), alarm(), and sigsuspend() can avoid these problems.

Despite all reasonable care, there are several very subtle, but detectable and unavoidable, differences between the two types of implementations. These are the cases mentioned in this volume of IEEE Std 1003.1-2001 where some other activity relating to SIGALRM takes place, and the results are stated to be unspecified. All of these cases are sufficiently unusual as not to be of concern to most applications.

See also the discussion of the term realtime in alarm() .

Since sleep() can be implemented using alarm(), the discussion about alarms occurring early under alarm() applies to sleep() as well.

Application writers should note that the type of the argument seconds and the return value of sleep() is unsigned. That means that a Strictly Conforming POSIX System Interfaces Application cannot pass a value greater than the minimum guaranteed value for {UINT_MAX}, which the ISO C standard sets as 65535, and any application passing a larger value is restricting its portability. A different type was considered, but historical implementations, including those with a 16-bit int type, consistently use either unsigned or int.

Scheduling delays may cause the process to return from the sleep() function significantly after the requested time. In such cases, the return value should be set to zero, since the formula (requested time minus the time actually spent) yields a negative number and sleep() returns an unsigned.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , getitimer() , nanosleep() , pause() , sigaction() , sigsetjmp() , ualarm() , usleep() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lround(3p)

LROUND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lround, lroundf, lroundl - round to nearest integer value

SYNOPSIS

#include <math.h>

long lround(double x);
long lroundf(float x);
long lroundl(long double x);

DESCRIPTION

These functions shall round their argument to the nearest integer value, rounding halfway cases away from zero, regardless of the current rounding direction.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the rounded integer value.

If x is NaN, a domain error shall occur and an unspecified value is returned.

If x is +Inf, a domain error shall occur and an unspecified value is returned.

If x is -Inf, a domain error shall occur and an unspecified value is returned.

If the correct value is positive and too large to represent as a long, a domain error shall occur and an unspecified value is returned.

If the correct value is negative and too large to represent as a long, a domain error shall occur and an unspecified value is returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is NaN or ±Inf, or the correct value is not representable as an integer.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

These functions differ from the lrint() functions in the default rounding direction, with the lround() functions rounding halfway cases away from zero and needing not to raise the inexact floating-point exception for non-integer arguments that round to within the range of the return type.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , llround() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getsid(3p)

GETSID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getsid - get the process group ID of a session leader

SYNOPSIS

#include <unistd.h>

pid_t getsid(pid_t pid);

DESCRIPTION

The getsid() function shall obtain the process group ID of the process that is the session leader of the process specified by pid. If pid is (pid_t)0, it specifies the calling process.

RETURN VALUE

Upon successful completion, getsid() shall return the process group ID of the session leader of the specified process. Otherwise, it shall return (pid_t)-1 and set errno to indicate the error.

ERRORS

The getsid() function shall fail if:

EPERM
The process specified by pid is not in the same session as the calling process, and the implementation does not allow access to the process group ID of the session leader of that process from the calling process.
ESRCH
There is no process with a process ID equal to pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fork() , getpid() , getpgid() , setpgid() , setsid() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_barrier_init(3p)

PTHREAD_BARRIER_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_barrier_destroy, pthread_barrier_init - destroy and initialize a barrier object (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_barrier_destroy(pthread_barrier_t *barrier);
int pthread_barrier_init(pthread_barrier_t *restrict barrier,
const pthread_barrierattr_t *restrict attr, unsigned count);

DESCRIPTION

The pthread_barrier_destroy() function shall destroy the barrier referenced by barrier and release any resources used by the barrier. The effect of subsequent use of the barrier is undefined until the barrier is reinitialized by another call to pthread_barrier_init(). An implementation may use this function to set barrier to an invalid value. The results are undefined if pthread_barrier_destroy() is called when any thread is blocked on the barrier, or if this function is called with an uninitialized barrier.

The pthread_barrier_init() function shall allocate any resources required to use the barrier referenced by barrier and shall initialize the barrier with attributes referenced by attr. If attr is NULL, the default barrier attributes shall be used; the effect is the same as passing the address of a default barrier attributes object. The results are undefined if pthread_barrier_init() is called when any thread is blocked on the barrier (that is, has not returned from the pthread_barrier_wait() call). The results are undefined if a barrier is used without first being initialized. The results are undefined if pthread_barrier_init() is called specifying an already initialized barrier.

The count argument specifies the number of threads that must call pthread_barrier_wait() before any of them successfully return from the call. The value specified by count must be greater than zero.

If the pthread_barrier_init() function fails, the barrier shall not be initialized and the contents of barrier are undefined.

Only the object referenced by barrier may be used for performing synchronization. The result of referring to copies of that object in calls to pthread_barrier_destroy() or pthread_barrier_wait() is undefined.

RETURN VALUE

Upon successful completion, these functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_barrier_destroy() function may fail if:

EBUSY
The implementation has detected an attempt to destroy a barrier while it is in use (for example, while being used in a pthread_barrier_wait() call) by another thread.
EINVAL
The value specified by barrier is invalid.

The pthread_barrier_init() function shall fail if:

EAGAIN
The system lacks the necessary resources to initialize another barrier.
EINVAL
The value specified by count is equal to zero.
ENOMEM
Insufficient memory exists to initialize the barrier.

The pthread_barrier_init() function may fail if:

EBUSY
The implementation has detected an attempt to reinitialize a barrier while it is in use (for example, while being used in a pthread_barrier_wait() call) by another thread.
EINVAL
The value specified by attr is invalid.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_barrier_destroy() and pthread_barrier_init() functions are part of the Barriers option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_barrier_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


scalblnf (3p)

 Continue to this page.


log(3p)

LOG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

log, logf, logl - natural logarithm function

SYNOPSIS

#include <math.h>

double log(double x);
float logf(float x);
long double logl(long double x);

DESCRIPTION

These functions shall compute the natural logarithm of their argument x, log_e(x).

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the natural logarithm of x.

If x is ±0, a pole error shall occur and log(), logf(), and logl() shall return -HUGE_VAL, -HUGE_VALF, and -HUGE_VALL, respectively.

For finite values of x that are less than 0, or if x is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is 1, +0 shall be returned.

If x is +Inf, x shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The finite value of x is negative, or x is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Pole Error
The value of x is zero.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exp() , feclearexcept() , fetestexcept() , isnan() , log10() , log1p() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_mem_offset(3p)

POSIX_MEM_OFFSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_mem_offset - find offset and length of a mapped typed memory block (ADVANCED REALTIME)

SYNOPSIS

#include <sys/mman.h>

int posix_mem_offset(const void *restrict addr, size_t len,
off_t *restrict off, size_t *restrict contig_len,
int *restrict fildes);

DESCRIPTION

The posix_mem_offset() function shall return in the variable pointed to by off a value that identifies the offset (or location), within a memory object, of the memory block currently mapped at addr. The function shall return in the variable pointed to by fildes, the descriptor used (via mmap()) to establish the mapping which contains addr. If that descriptor was closed since the mapping was established, the returned value of fildes shall be -1. The len argument specifies the length of the block of the memory object the user wishes the offset for; upon return, the value pointed to by contig_len shall equal either len, or the length of the largest contiguous block of the memory object that is currently mapped to the calling process starting at addr, whichever is smaller.

If the memory object mapped at addr is a typed memory object, then if the off and contig_len values obtained by calling posix_mem_offset() are used in a call to mmap() with a file descriptor that refers to the same memory pool as fildes (either through the same port or through a different port), and that was opened with neither the POSIX_TYPED_MEM_ALLOCATE nor the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, the typed memory area that is mapped shall be exactly the same area that was mapped at addr in the address space of the process that called posix_mem_offset().

If the memory object specified by fildes is not a typed memory object, then the behavior of this function is implementation-defined.

RETURN VALUE

Upon successful completion, the posix_mem_offset() function shall return zero; otherwise, the corresponding error status value shall be returned.

ERRORS

The posix_mem_offset() function shall fail if:

EACCES
The process has not mapped a memory object supported by this function at the given address addr.

This function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mmap() , posix_typed_mem_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


scalblnl (3p)

 Continue to this page.


posix_trace_attr_setlogsize (3p)

 Continue to this page.


imaxdiv(3p)

IMAXDIV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

imaxdiv - return quotient and remainder

SYNOPSIS

#include <inttypes.h>

imaxdiv_t imaxdiv(intmax_t numer, intmax_t denom);

DESCRIPTION

The imaxdiv() function shall compute numer / denom and numer % denom in a single operation.

RETURN VALUE

The imaxdiv() function shall return a structure of type imaxdiv_t, comprising both the quotient and the remainder. The structure shall contain (in either order) the members quot (the quotient) and rem (the remainder), each of which has type intmax_t.

If either part of the result cannot be represented, the behavior is undefined.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

imaxabs() , the Base Definitions volume of IEEE Std 1003.1-2001, <inttypes.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sendmsg(3p)

SENDMSG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sendmsg - send a message on a socket using a message structure

SYNOPSIS

#include <sys/socket.h>

ssize_t sendmsg(int socket, const struct msghdr *message, int flags);

DESCRIPTION

The sendmsg() function shall send a message through a connection-mode or connectionless-mode socket. If the socket is connectionless-mode, the message shall be sent to the address specified by msghdr. If the socket is connection-mode, the destination address in msghdr shall be ignored.

The sendmsg() function takes the following arguments:

socket
Specifies the socket file descriptor.
message
Points to a msghdr structure, containing both the destination address and the buffers for the outgoing message. The length and format of the address depend on the address family of the socket. The msg_flags member is ignored.
flags
Specifies the type of message transmission. The application may specify 0 or the following flag:
MSG_EOR
Terminates a record (if supported by the protocol).
MSG_OOB
Sends out-of-band data on sockets that support out-of-bound data. The significance and semantics of out-of-band data are protocol-specific.

The msg_iov and msg_iovlen fields of message specify zero or more buffers containing the data to be sent. msg_iov points to an array of iovec structures; msg_iovlen shall be set to the dimension of this array. In each iovec structure, the iov_base field specifies a storage area and the iov_len field gives its size in bytes. Some of these sizes can be zero. The data from each storage area indicated by msg_iov is sent in turn.

Successful completion of a call to sendmsg() does not guarantee delivery of the message. A return value of -1 indicates only locally-detected errors.

If space is not available at the sending socket to hold the message to be transmitted and the socket file descriptor does not have O_NONBLOCK set, the sendmsg() function shall block until space is available. If space is not available at the sending socket to hold the message to be transmitted and the socket file descriptor does have O_NONBLOCK set, the sendmsg() function shall fail.

If the socket protocol supports broadcast and the specified address is a broadcast address for the socket protocol, sendmsg() shall fail if the SO_BROADCAST option is not set for the socket.

The socket in use may require the process to have appropriate privileges to use the sendmsg() function.

RETURN VALUE

Upon successful completion, sendmsg() shall return the number of bytes sent. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The sendmsg() function shall fail if:

EAGAIN or EWOULDBLOCK
The socket's file descriptor is marked O_NONBLOCK and the requested operation would block.
EAFNOSUPPORT
Addresses in the specified address family cannot be used with this socket.
EBADF
The socket argument is not a valid file descriptor.
ECONNRESET
A connection was forcibly closed by a peer.
EINTR
A signal interrupted sendmsg() before any data was transmitted.
EINVAL
The sum of the iov_len values overflows an ssize_t.
EMSGSIZE
The message is too large to be sent all at once (as the socket requires), or the msg_iovlen member of the msghdr structure pointed to by message is less than or equal to 0 or is greater than {IOV_MAX}.
ENOTCONN
The socket is connection-mode but is not connected.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The socket argument is associated with a socket that does not support one or more of the values set in flags.
EPIPE
The socket is shut down for writing, or the socket is connection-mode and is no longer connected. In the latter case, and if the socket is of type SOCK_STREAM, the SIGPIPE signal is generated to the calling thread.

If the address family of the socket is AF_UNIX, then sendmsg() shall fail if:

EIO
An I/O error occurred while reading from or writing to the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the pathname in the socket address.
ENAMETOOLONG
A component of a pathname exceeded {NAME_MAX} characters, or an entire pathname exceeded {PATH_MAX} characters.
ENOENT
A component of the pathname does not name an existing file or the path name is an empty string.
ENOTDIR
A component of the path prefix of the pathname in the socket address is not a directory.

The sendmsg() function may fail if:

EACCES
Search permission is denied for a component of the path prefix; or write access to the named socket is denied.
EDESTADDRREQ
The socket is not connection-mode and does not have its peer address set, and no destination address was specified.
EHOSTUNREACH
The destination host cannot be reached (probably because the host is down or a remote router cannot reach it).
EIO
An I/O error occurred while reading from or writing to the file system.
EISCONN
A destination address was specified and the socket is already connected.
ENETDOWN
The local network interface used to reach the destination is down.
ENETUNREACH
No route to the network is present.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.

If the address family of the socket is AF_UNIX, then sendmsg() may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the pathname in the socket address.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

Done.

APPLICATION USAGE

The select() and poll() functions can be used to determine when it is possible to send more data.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getsockopt() , poll() , recv() , recvfrom() , recvmsg() , select() , send() , sendto() , setsockopt() , shutdown() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_getinheritsched(3p)

PTHREAD_ATTR_GETINHERITSCHED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getinheritsched, pthread_attr_setinheritsched - get and set the inheritsched attribute (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_attr_getinheritsched(const pthread_attr_t *restrict attr,
int *restrict inheritsched);
int pthread_attr_setinheritsched(pthread_attr_t *attr,
int inheritsched);

DESCRIPTION

The pthread_attr_getinheritsched(), and pthread_attr_setinheritsched() functions, respectively, shall get and set the inheritsched attribute in the attr argument.

When the attributes objects are used by pthread_create(), the inheritsched attribute determines how the other scheduling attributes of the created thread shall be set.

PTHREAD_INHERIT_SCHED

Specifies that the thread scheduling attributes shall be inherited from the creating thread, and the scheduling attributes in this attr argument shall be ignored.

PTHREAD_EXPLICIT_SCHED

Specifies that the thread scheduling attributes shall be set to the corresponding values from this attributes object.

The symbols PTHREAD_INHERIT_SCHED and PTHREAD_EXPLICIT_SCHED are defined in the <pthread.h> header.

The following thread scheduling attributes defined by IEEE Std 1003.1-2001 are affected by the inheritsched attribute: scheduling policy ( schedpolicy), scheduling parameters ( schedparam), and scheduling contention scope ( contentionscope).

RETURN VALUE

If successful, the pthread_attr_getinheritsched() and pthread_attr_setinheritsched() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_attr_setinheritsched() function may fail if:

EINVAL
The value of inheritsched is not valid.
ENOTSUP
An attempt was made to set the attribute to an unsupported value.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

After these attributes have been set, a thread can be created with the specified attributes using pthread_create(). Using these routines does not affect the current running thread.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_attr_getscope() , pthread_attr_getschedpolicy() , pthread_attr_getschedparam() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ftrylockfile (3p)

 Continue to this page.


dbm_close (3p)

 Continue to this page.


mq_timedreceive (3p)

 Continue to this page.


tzname (3p)

 Continue to this page.


islower(3p)

ISLOWER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

islower - test for a lowercase letter

SYNOPSIS

#include <ctype.h>

int islower(int c);

DESCRIPTION

The islower() function shall test whether c is a character of class lower in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The islower() function shall return non-zero if c is a lowercase letter; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Testing for a Lowercase Letter

The following example tests whether the value is a lowercase letter, based on the locale of the user, then uses it as part of a key value.

#include <ctype.h>
#include <stdlib.h>
#include <locale.h>
...
char *keystr;
int elementlen, len;
char c;
...
setlocale(LC_ALL, "");
...
len = 0;
while (len < elementlen) {
    c = (char) (rand() % 256);
...
    if (islower(c))
        keystr[len++] = c;
    }
...

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , isgraph() , isprint() , ispunct() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strrchr(3p)

STRRCHR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strrchr - string scanning operation

SYNOPSIS

#include <string.h>

char *strrchr(const char *s, int c);

DESCRIPTION

The strrchr() function shall locate the last occurrence of c (converted to a char) in the string pointed to by s. The terminating null byte is considered to be part of the string.

RETURN VALUE

Upon successful completion, strrchr() shall return a pointer to the byte or a null pointer if c does not occur in the string.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Finding the Base Name of a File

The following example uses strrchr() to get a pointer to the base name of a file. The strrchr() function searches backwards through the name of the file to find the last '/' character in name. This pointer (plus one) will point to the base name of the file.

#include <string.h>
...
const char *name;
char *basename;
...
basename = strrchr(name, '/') + 1;
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cimag(3p)

CIMAG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cimag, cimagf, cimagl - complex imaginary functions

SYNOPSIS

#include <complex.h>

double cimag(double complex z);
float cimagf(float complex z);
long double cimagl(long double complex z);

DESCRIPTION

These functions shall compute the imaginary part of z.

RETURN VALUE

These functions shall return the imaginary part value (as a real).

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

For a variable z of complex type:

z == creal(z) + cimag(z)*I

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

carg() , conj() , cproj() , creal() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lio_listio(3p)

LIO_LISTIO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lio_listio - list directed I/O (REALTIME)

SYNOPSIS

#include <aio.h>

int lio_listio(int mode, struct aiocb *restrict const list[restrict],
int nent, struct sigevent *restrict sig);

DESCRIPTION

The lio_listio() function shall initiate a list of I/O requests with a single function call.

The mode argument takes one of the values LIO_WAIT or LIO_NOWAIT declared in <aio.h> and determines whether the function returns when the I/O operations have been completed, or as soon as the operations have been queued. If the mode argument is LIO_WAIT, the function shall wait until all I/O is complete and the sig argument shall be ignored.

If the mode argument is LIO_NOWAIT, the function shall return immediately, and asynchronous notification shall occur, according to the sig argument, when all the I/O operations complete. If sig is NULL, then no asynchronous notification shall occur. If sig is not NULL, asynchronous notification occurs as specified in Signal Generation and Delivery when all the requests in list have completed.

The I/O requests enumerated by list are submitted in an unspecified order.

The list argument is an array of pointers to aiocb structures. The array contains nent elements. The array may contain NULL elements, which shall be ignored.

The aio_lio_opcode field of each aiocb structure specifies the operation to be performed. The supported operations are LIO_READ, LIO_WRITE, and LIO_NOP; these symbols are defined in <aio.h>. The LIO_NOP operation causes the list entry to be ignored. If the aio_lio_opcode element is equal to LIO_READ, then an I/O operation is submitted as if by a call to aio_read() with the aiocbp equal to the address of the aiocb structure. If the aio_lio_opcode element is equal to LIO_WRITE, then an I/O operation is submitted as if by a call to aio_write() with the aiocbp equal to the address of the aiocb structure.

The aio_fildes member specifies the file descriptor on which the operation is to be performed.

The aio_buf member specifies the address of the buffer to or from which the data is transferred.

The aio_nbytes member specifies the number of bytes of data to be transferred.

The members of the aiocb structure further describe the I/O operation to be performed, in a manner identical to that of the corresponding aiocb structure when used by the aio_read() and aio_write() functions.

The nent argument specifies how many elements are members of the list; that is, the length of the array.

The behavior of this function is altered according to the definitions of synchronized I/O data integrity completion and synchronized I/O file integrity completion if synchronized I/O is enabled on the file associated with aio_fildes.

For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with aiocbp->aio_fildes.

RETURN VALUE

If the mode argument has the value LIO_NOWAIT, the lio_listio() function shall return the value zero if the I/O operations are successfully queued; otherwise, the function shall return the value -1 and set errno to indicate the error.

If the mode argument has the value LIO_WAIT, the lio_listio() function shall return the value zero when all the indicated I/O has completed successfully. Otherwise, lio_listio() shall return a value of -1 and set errno to indicate the error.

In either case, the return value only indicates the success or failure of the lio_listio() call itself, not the status of the individual I/O requests. In some cases one or more of the I/O requests contained in the list may fail. Failure of an individual request does not prevent completion of any other individual request. To determine the outcome of each I/O request, the application shall examine the error status associated with each aiocb control block. The error statuses so returned are identical to those returned as the result of an aio_read() or aio_write() function.

ERRORS

The lio_listio() function shall fail if:

EAGAIN
The resources necessary to queue all the I/O requests were not available. The application may check the error status for each aiocb to determine the individual request(s) that failed.
EAGAIN
The number of entries indicated by nent would cause the system-wide limit {AIO_MAX} to be exceeded.
EINVAL
The mode argument is not a proper value, or the value of nent was greater than {AIO_LISTIO_MAX}.
EINTR
A signal was delivered while waiting for all I/O requests to complete during an LIO_WAIT operation. Note that, since each I/O operation invoked by lio_listio() may possibly provoke a signal when it completes, this error return may be caused by the completion of one (or more) of the very I/O operations being awaited. Outstanding I/O requests are not canceled, and the application shall examine each list element to determine whether the request was initiated, canceled, or completed.
EIO
One or more of the individual I/O operations failed. The application may check the error status for each aiocb structure to determine the individual request(s) that failed.

In addition to the errors returned by the lio_listio() function, if the lio_listio() function succeeds or fails with errors of [EAGAIN], [EINTR], or [EIO], then some of the I/O specified by the list may have been initiated. If the lio_listio() function fails with an error code other than [EAGAIN], [EINTR], or [EIO], no operations from the list shall have been initiated. The I/O operation indicated by each list element can encounter errors specific to the individual read or write function being performed. In this event, the error status for each aiocb control block contains the associated error code. The error codes that can be set are the same as would be set by a read() or write() function, with the following additional error codes possible:

EAGAIN
The requested I/O operation was not queued due to resource limitations.
ECANCELED
The requested I/O was canceled before the I/O completed due to an explicit aio_cancel() request.
EFBIG
The aiocbp->aio_lio_opcode is LIO_WRITE, the file is a regular file, aiocbp->aio_nbytes is greater than 0, and the aiocbp->aio_offset is greater than or equal to the offset maximum in the open file description associated with aiocbp->aio_fildes.
EINPROGRESS
The requested I/O is in progress.
EOVERFLOW
The aiocbp->aio_lio_opcode is LIO_READ, the file is a regular file, aiocbp->aio_nbytes is greater than 0, and the aiocbp->aio_offset is before the end-of-file and is greater than or equal to the offset maximum in the open file description associated with aiocbp->aio_fildes.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Although it may appear that there are inconsistencies in the specified circumstances for error codes, the [EIO] error condition applies when any circumstance relating to an individual operation makes that operation fail. This might be due to a badly formulated request (for example, the aio_lio_opcode field is invalid, and aio_error() returns [EINVAL]) or might arise from application behavior (for example, the file descriptor is closed before the operation is initiated, and aio_error() returns [EBADF]).

The limitation on the set of error codes returned when operations from the list shall have been initiated enables applications to know when operations have been started and whether aio_error() is valid for a specific operation.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_read() , aio_write() , aio_error() , aio_return() , aio_cancel() , close() , exec() , exit() , fork() , lseek() , read() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


glob(3p)

GLOB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

glob, globfree - generate pathnames matching a pattern

SYNOPSIS

#include <glob.h>

int glob(const char *restrict pattern, int flags,
int(*errfunc)(const char *epath, int eerrno),
glob_t *restrict pglob);
void globfree(glob_t *pglob);

DESCRIPTION

The glob() function is a pathname generator that shall implement the rules defined in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13, Pattern Matching Notation, with optional support for rule 3 in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13.3, Patterns Used for Filename Expansion.

The structure type glob_t is defined in <glob.h> and includes at least the following members:
Member Type | Member Name | Description
size_t | gl_pathc | Count of paths matched by pattern.
char ** | gl_pathv | Pointer to a list of matched pathnames.
size_t | gl_offs | Slots to reserve at the beginning of gl_pathv.

The argument pattern is a pointer to a pathname pattern to be expanded. The glob() function shall match all accessible pathnames against this pattern and develop a list of all pathnames that match. In order to have access to a pathname, glob() requires search permission on every component of a path except the last, and read permission on each directory of any filename component of pattern that contains any of the following special characters: '*' , '?' , and '[' .

The glob() function shall store the number of matched pathnames into pglob->gl_pathc and a pointer to a list of pointers to pathnames into pglob->gl_pathv. The pathnames shall be in sort order as defined by the current setting of the LC_COLLATE category; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.2, LC_COLLATE. The first pointer after the last pathname shall be a null pointer. If the pattern does not match any pathnames, the returned number of matched paths is set to 0, and the contents of pglob->gl_pathv are implementation-defined.

It is the caller's responsibility to create the structure pointed to by pglob. The glob() function shall allocate other space as needed, including the memory pointed to by gl_pathv. The globfree() function shall free any space associated with pglob from a previous call to glob().

The flags argument is used to control the behavior of glob(). The value of flags is a bitwise-inclusive OR of zero or more of the following constants, which are defined in <glob.h>:

GLOB_APPEND
Append pathnames generated to the ones from a previous call to glob().
GLOB_DOOFFS
Make use of pglob->gl_offs. If this flag is set, pglob->gl_offs is used to specify how many null pointers to add to the beginning of pglob->gl_pathv. In other words, pglob->gl_pathv shall point to pglob->gl_offs null pointers, followed by pglob->gl_pathc pathname pointers, followed by a null pointer.
GLOB_ERR
Cause glob() to return when it encounters a directory that it cannot open or read. Ordinarily, glob() continues to find matches.
GLOB_MARK
Each pathname that is a directory that matches pattern shall have a slash appended.
GLOB_NOCHECK
Supports rule 3 in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13.3, Patterns Used for Filename Expansion. If pattern does not match any pathname, then glob() shall return a list consisting of only pattern, and the number of matched pathnames is 1.
GLOB_NOESCAPE
Disable backslash escaping.
GLOB_NOSORT
Ordinarily, glob() sorts the matching pathnames according to the current setting of the LC_COLLATE category; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.2, LC_COLLATE. When this flag is used, the order of pathnames returned is unspecified.

The GLOB_APPEND flag can be used to append a new set of pathnames to those found in a previous call to glob(). The following rules apply to applications when two or more calls to glob() are made with the same value of pglob and without intervening calls to globfree():

1.
The first such call shall not set GLOB_APPEND. All subsequent calls shall set it.

2.
All the calls shall set GLOB_DOOFFS, or all shall not set it.

3.
After the second call, pglob->gl_pathv points to a list containing the following:
a.
Zero or more null pointers, as specified by GLOB_DOOFFS and pglob->gl_offs.

b.
Pointers to the pathnames that were in the pglob->gl_pathv list before the call, in the same order as before.

c.
Pointers to the new pathnames generated by the second call, in the specified order.

4.
The count returned in pglob->gl_pathc shall be the total number of pathnames from the two calls.

5.
The application can change any of the fields after a call to glob(). If it does, the application shall reset them to the original value before a subsequent call, using the same pglob value, to globfree() or glob() with the GLOB_APPEND flag.

If, during the search, a directory is encountered that cannot be opened or read and errfunc is not a null pointer, glob() calls (*errfunc()) with two arguments:

1.
The epath argument is a pointer to the path that failed.

2.
The eerrno argument is the value of errno from the failure, as set by opendir(), readdir(), or stat(). (Other values may be used to report other errors not explicitly documented for those functions.)

If (*errfunc()) is called and returns non-zero, or if the GLOB_ERR flag is set in flags, glob() shall stop the scan and return GLOB_ABORTED after setting gl_pathc and gl_pathv in pglob to reflect the paths already scanned. If GLOB_ERR is not set and either errfunc is a null pointer or (*errfunc()) returns 0, the error shall be ignored.

The glob() function shall not fail because of large files.

RETURN VALUE

Upon successful completion, glob() shall return 0. The argument pglob->gl_pathc shall return the number of matched pathnames and the argument pglob->gl_pathv shall contain a pointer to a null-terminated list of matched and sorted pathnames. However, if pglob->gl_pathc is 0, the content of pglob->gl_pathv is undefined.

The globfree() function shall not return a value.

If glob() terminates due to an error, it shall return one of the non-zero constants defined in <glob.h>. The arguments pglob->gl_pathc and pglob->gl_pathv are still set as defined above.

ERRORS

The glob() function shall fail and return the corresponding value if:

GLOB_ABORTED
The scan was stopped because GLOB_ERR was set or (*errfunc()) returned non-zero.
GLOB_NOMATCH
The pattern does not match any existing pathname, and GLOB_NOCHECK was not set in flags.
GLOB_NOSPACE
An attempt to allocate memory failed.

The following sections are informative.

EXAMPLES

One use of the GLOB_DOOFFS flag is by applications that build an argument list for use with execv(), execve(), or execvp(). Suppose, for example, that an application wants to do the equivalent of:

ls -l *.c

but for some reason:

system("ls -l *.c")

is not acceptable. The application could obtain approximately the same result using the sequence:

globbuf.gl_offs = 2;
glob("*.c", GLOB_DOOFFS, NULL, &globbuf);
globbuf.gl_pathv[0] = "ls";
globbuf.gl_pathv[1] = "-l";
execvp("ls", &globbuf.gl_pathv[0]);

Using the same example:

ls -l *.c *.h

could be approximately simulated using GLOB_APPEND as follows:

globbuf.gl_offs = 2;
glob("*.c", GLOB_DOOFFS, NULL, &globbuf);
glob("*.h", GLOB_DOOFFS|GLOB_APPEND, NULL, &globbuf);
...

APPLICATION USAGE

This function is not provided for the purpose of enabling utilities to perform pathname expansion on their arguments, as this operation is performed by the shell, and utilities are explicitly not expected to redo this. Instead, it is provided for applications that need to do pathname expansion on strings obtained from other sources, such as a pattern typed by a user or read from a file.

If a utility needs to see if a pathname matches a given pattern, it can use fnmatch().

Note that gl_pathc and gl_pathv have meaning even if glob() fails. This allows glob() to report partial results in the event of an error. However, if gl_pathc is 0, gl_pathv is unspecified even if glob() did not return an error.

The GLOB_NOCHECK option could be used when an application wants to expand a pathname if wildcards are specified, but wants to treat the pattern as just a string otherwise. The sh utility might use this for option-arguments, for example.

The new pathnames generated by a subsequent call with GLOB_APPEND are not sorted together with the previous pathnames. This mirrors the way that the shell handles pathname expansion when multiple expansions are done on a command line.

Applications that need tilde and parameter expansion should use wordexp().

RATIONALE

It was claimed that the GLOB_DOOFFS flag is unnecessary because it could be simulated using:

new = (char **)malloc((n + pglob->gl_pathc + 1)
       * sizeof(char *));
(void) memcpy(new+n, pglob->gl_pathv,
       pglob->gl_pathc * sizeof(char *));
(void) memset(new, 0, n * sizeof(char *));
free(pglob->gl_pathv);
pglob->gl_pathv = new;

However, this assumes that the memory pointed to by gl_pathv is a block that was separately created using malloc(). This is not necessarily the case. An application should make no assumptions about how the memory referenced by fields in pglob was allocated. It might have been obtained from malloc() in a large chunk and then carved up within glob(), or it might have been created using a different memory allocator. It is not the intent of the standard developers to specify or imply how the memory used by glob() is managed.

The GLOB_APPEND flag would be used when an application wants to expand several different patterns into a single list.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fnmatch() , opendir() , readdir() , stat() , wordexp() , the Base Definitions volume of IEEE Std 1003.1-2001, <glob.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fread(3p)

FREAD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fread - binary input

SYNOPSIS

#include <stdio.h>

size_t fread(void *restrict ptr, size_t size, size_t nitems,
FILE *restrict stream);

DESCRIPTION

The fread() function shall read into the array pointed to by ptr up to nitems elements whose size is specified by size in bytes, from the stream pointed to by stream. For each object, size calls shall be made to the fgetc() function and the results stored, in the order read, in an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) shall be advanced by the number of bytes successfully read. If an error occurs, the resulting value of the file position indicator for the stream is unspecified. If a partial element is read, its value is unspecified.

The fread() function may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fgetwc(), fgetws(), fread(), fscanf(), getc(), getchar(), gets(), or scanf() using stream that returns data not supplied by a prior call to ungetc() or ungetwc().

RETURN VALUE

Upon successful completion, fread() shall return the number of elements successfully read which is less than nitems only if a read error or end-of-file is encountered. If size or nitems is 0, fread() shall return 0 and the contents of the array and the state of the stream remain unchanged. Otherwise, if a read error occurs, the error indicator for the stream shall be set, and errno shall be set to indicate the error.

ERRORS

Refer to fgetc() .

The following sections are informative.

EXAMPLES

Reading from a Stream

The following example reads a single element from the fp stream into the array pointed to by buf.

#include <stdio.h>
...
size_t bytes_read;
char buf[100];
FILE *fp;
...
bytes_read = fread(buf, sizeof(buf), 1, fp);
...

APPLICATION USAGE

The ferror() or feof() functions must be used to distinguish between an error condition and an end-of-file condition.

Because of possible differences in element length and byte ordering, files written using fwrite() are application-dependent, and possibly cannot be read using fread() by a different application or by the same application on a different processor.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feof() , ferror() , fgetc() , fopen() , getc() , gets() , scanf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fegetexceptflag(3p)

FEGETEXCEPTFLAG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fegetexceptflag, fesetexceptflag - get and set floating-point status flags

SYNOPSIS

#include <fenv.h>

int fegetexceptflag(fexcept_t *flagp, int excepts);
int fesetexceptflag(const fexcept_t *flagp, int excepts);

DESCRIPTION

The fegetexceptflag() function shall attempt to store an implementation-defined representation of the states of the floating-point status flags indicated by the argument excepts in the object pointed to by the argument flagp.

The fesetexceptflag() function shall attempt to set the floating-point status flags indicated by the argument excepts to the states stored in the object pointed to by flagp. The value pointed to by flagp shall have been set by a previous call to fegetexceptflag() whose second argument represented at least those floating-point exceptions represented by the argument excepts. This function does not raise floating-point exceptions, but only sets the state of the flags.

RETURN VALUE

If the representation was successfully stored, fegetexceptflag() shall return zero. Otherwise, it shall return a non-zero value. If the excepts argument is zero or if all the specified exceptions were successfully set, fesetexceptflag() shall return zero. Otherwise, it shall return a non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , feraiseexcept() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nan(3p)

NAN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nan, nanf, nanl - return quiet NaN

SYNOPSIS

#include <math.h>

double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

DESCRIPTION

The function call nan("n-char-sequence") shall be equivalent to:

strtod("NAN(n-char-sequence)", (char **) NULL);

The function call nan("") shall be equivalent to:

strtod("NAN()", (char **) NULL)

If tagp does not point to an n- char sequence or an empty string, the function call shall be equivalent to:

strtod("NAN", (char **) NULL)

Function calls to nanf() and nanl() are equivalent to the corresponding function calls to strtof() and strtold().

RETURN VALUE

These functions shall return a quiet NaN, if available, with content indicated through tagp.

If the implementation does not support quiet NaNs, these functions shall return zero.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strtod() , strtold() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_detach(3p)

PTHREAD_DETACH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_detach - detach a thread

SYNOPSIS

#include <pthread.h>

int pthread_detach(pthread_t thread);

DESCRIPTION

The pthread_detach() function shall indicate to the implementation that storage for the thread thread can be reclaimed when that thread terminates. If thread has not terminated, pthread_detach() shall not cause it to terminate. The effect of multiple pthread_detach() calls on the same target thread is unspecified.

RETURN VALUE

If the call succeeds, pthread_detach() shall return 0; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_detach() function shall fail if:

EINVAL
The implementation has detected that the value specified by thread does not refer to a joinable thread.
ESRCH
No thread could be found corresponding to that specified by the given thread ID.

The pthread_detach() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The pthread_join() or pthread_detach() functions should eventually be called for every thread that is created so that storage associated with the thread may be reclaimed.

It has been suggested that a "detach" function is not necessary; the detachstate thread creation attribute is sufficient, since a thread need never be dynamically detached. However, need arises in at least two cases:

1.
In a cancellation handler for a pthread_join() it is nearly essential to have a pthread_detach() function in order to detach the thread on which pthread_join() was waiting. Without it, it would be necessary to have the handler do another pthread_join() to attempt to detach the thread, which would both delay the cancellation processing for an unbounded period and introduce a new call to pthread_join(), which might itself need a cancellation handler. A dynamic detach is nearly essential in this case.

2.
In order to detach the "initial thread" (as may be desirable in processes that set up server threads).

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_join() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isinf(3p)

ISINF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isinf - test for infinity

SYNOPSIS

#include <math.h>

int isinf(real-floating x);

DESCRIPTION

The isinf() macro shall determine whether its argument value is an infinity (positive or negative). First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.

RETURN VALUE

The isinf() macro shall return a non-zero value if and only if its argument has an infinite value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fpclassify() , isfinite() , isnan() , isnormal() , signbit() , the Base Definitions volume of IEEE Std 1003.1-2001 <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


clock_settime (3p)

 Continue to this page.


tcdrain(3p)

TCDRAIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcdrain - wait for transmission of output

SYNOPSIS

#include <termios.h>

int tcdrain(int fildes);

DESCRIPTION

The tcdrain() function shall block until all output written to the object referred to by fildes is transmitted. The fildes argument is an open file descriptor associated with a terminal.

Any attempts to use tcdrain() from a process which is a member of a background process group on a fildes associated with its controlling terminal, shall cause the process group to be sent a SIGTTOU signal. If the calling process is blocking or ignoring SIGTTOU signals, the process shall be allowed to perform the operation, and no signal is sent.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcdrain() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINTR
A signal interrupted tcdrain().
ENOTTY
The file associated with fildes is not a terminal.

The tcdrain() function may fail if:

EIO
The process group of the writing process is orphaned, and the writing process is not ignoring or blocking SIGTTOU.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

tcflush() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getutxline (3p)

 Continue to this page.


acos(3p)

ACOS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

acos, acosf, acosl - arc cosine functions

SYNOPSIS

#include <math.h>

double acos(double x);
float acosf(float x);
long double acosl(long double x);

DESCRIPTION

These functions shall compute the principal value of the arc cosine of their argument x. The value of x should be in the range [-1,1].

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the arc cosine of x, in the range [0,pi] radians.

For finite values of x not in the range [-1,1], a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is +1, +0 shall be returned.

If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is finite and is not in the range [-1,1], or is ±Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cos() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fclose(3p)

FCLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fclose - close a stream

SYNOPSIS

#include <stdio.h>

int fclose(FILE *stream);

DESCRIPTION

The fclose() function shall cause the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream shall be written to the file; any unread buffered data shall be discarded. Whether or not the call succeeds, the stream shall be disassociated from the file and any buffer set by the setbuf() or setvbuf() function shall be disassociated from the stream. If the associated buffer was automatically allocated, it shall be deallocated.

The fclose() function shall mark for update the st_ctime and st_mtime fields of the underlying file, if the stream was writable, and if buffered data remains that has not yet been written to the file. The fclose() function shall perform the equivalent of a close() on the file descriptor that is associated with the stream pointed to by stream.

After the call to fclose(), any use of stream results in undefined behavior.

RETURN VALUE

Upon successful completion, fclose() shall return 0; otherwise, it shall return EOF and set errno to indicate the error.

ERRORS

The fclose() function shall fail if:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying stream and the process would be delayed in the write operation.
EBADF
The file descriptor underlying stream is not valid.
EFBIG
An attempt was made to write a file that exceeds the maximum file size.
EFBIG
An attempt was made to write a file that exceeds the process' file size limit.
EFBIG
The file is a regular file and an attempt was made to write at or beyond the offset maximum associated with the corresponding stream.
EINTR
The fclose() function was interrupted by a signal.
EIO
The process is a member of a background process group attempting to write to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the process group of the process is orphaned. This error may also be returned under implementation-defined conditions.
ENOSPC
There was no free space remaining on the device containing the file.
EPIPE
An attempt is made to write to a pipe or FIFO that is not open for reading by any process. A SIGPIPE signal shall also be sent to the thread.

The fclose() function may fail if:

ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

close() , fopen() , getrlimit() , ulimit() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getuid(3p)

GETUID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getuid - get a real user ID

SYNOPSIS

#include <unistd.h>

uid_t getuid(void);

DESCRIPTION

The getuid() function shall return the real user ID of the calling process.

RETURN VALUE

The getuid() function shall always be successful and no return value is reserved to indicate the error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Setting the Effective User ID to the Real User ID

The following example sets the effective user ID and the real user ID of the current process to the real user ID of the caller.

#include <unistd.h>
#include <sys/types.h>
...
setreuid(getuid(), getuid());
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getegid() , geteuid() , getgid() , setegid() , seteuid() , setgid() , setregid() , setreuid() , setuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigrelse (3p)

 Continue to this page.


if_freenameindex(3p)

IF_FREENAMEINDEX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

if_freenameindex - free memory allocated by if_nameindex

SYNOPSIS

#include <net/if.h>

void if_freenameindex(struct if_nameindex *ptr);

DESCRIPTION

The if_freenameindex() function shall free the memory allocated by if_nameindex(). The ptr argument shall be a pointer that was returned by if_nameindex(). After if_freenameindex() has been called, the application shall not use the array of which ptr is the address.

RETURN VALUE

None.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getsockopt() , if_indextoname() , if_nameindex() , if_nametoindex() , setsockopt() , the Base Definitions volume of IEEE Std 1003.1-2001, <net/if.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setnetent (3p)

 Continue to this page.


fdimf (3p)

 Continue to this page.


fdiml (3p)

 Continue to this page.


opterr (3p)

 Continue to this page.


getgrnam(3p)

GETGRNAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getgrnam, getgrnam_r - search group database for a name

SYNOPSIS

#include <grp.h>

struct group *getgrnam(const char *name);

int getgrnam_r(const char *name, struct group *grp, char *buffer,
size_t bufsize, struct group **result);

DESCRIPTION

The getgrnam() function shall search the group database for an entry with a matching name.

The getgrnam() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The getgrnam_r() function shall update the group structure pointed to by grp and store a pointer to that structure at the location pointed to by result. The structure shall contain an entry from the group database with a matching gid or name. Storage referenced by the group structure is allocated from the memory provided with the buffer parameter, which is bufsize bytes in size. The maximum size needed for this buffer can be determined with the {_SC_GETGR_R_SIZE_MAX} sysconf() parameter. A NULL pointer is returned at the location pointed to by result on error or if the requested entry is not found.

RETURN VALUE

The getgrnam() function shall return a pointer to a struct group with the structure defined in <grp.h> with a matching entry if one is found. The getgrnam() function shall return a null pointer if either the requested entry was not found, or an error occurred. On error, errno shall be set to indicate the error.

The return value may point to a static area which is overwritten by a subsequent call to getgrent(), getgrgid(), or getgrnam().

If successful, the getgrnam_r() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The getgrnam() and getgrnam_r() functions may fail if:

EIO
An I/O error has occurred.
EINTR
A signal was caught during getgrnam().
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.

The getgrnam_r() function may fail if:

ERANGE
Insufficient storage was supplied via buffer and bufsize to contain the data to be referenced by the resulting group structure.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications wishing to check for error situations should set errno to 0 before calling getgrnam(). If errno is set on return, an error occurred.

The getgrnam_r() function is thread-safe and shall return values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

endgrent() , getgrgid() , the Base Definitions volume of IEEE Std 1003.1-2001, <grp.h>, <limits.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


frexp(3p)

FREXP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

frexp, frexpf, frexpl - extract mantissa and exponent from a double precision number

SYNOPSIS

#include <math.h>

double frexp(double num, int *exp);
float frexpf(float num, int *exp);
long double frexpl(long double num, int *exp);

DESCRIPTION

These functions shall break a floating-point number num into a normalized fraction and an integral power of 2. The integer exponent shall be stored in the int object pointed to by exp.

RETURN VALUE

For finite arguments, these functions shall return the value x, such that x has a magnitude in the interval [0.5,1) or 0, and num equals x times 2 raised to the power *exp.

If num is NaN, a NaN shall be returned, and the value of *exp is unspecified.

If num is ±0, ±0 shall be returned, and the value of *exp shall be 0.

If num is ±Inf, num shall be returned, and the value of *exp is unspecified.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isnan() , ldexp() , modf() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstombs(3p)

WCSTOMBS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcstombs - convert a wide-character string to a character string

SYNOPSIS

#include <stdlib.h>

size_t wcstombs(char *restrict s, const wchar_t *restrict pwcs,
size_t n);

DESCRIPTION

The wcstombs() function shall convert the sequence of wide-character codes that are in the array pointed to by pwcs into a sequence of characters that begins in the initial shift state and store these characters into the array pointed to by s, stopping if a character would exceed the limit of n total bytes or if a null byte is stored. Each wide-character code shall be converted as if by a call to wctomb(), except that the shift state of wctomb() shall not be affected.

The behavior of this function shall be affected by the LC_CTYPE category of the current locale.

No more than n bytes shall be modified in the array pointed to by s. If copying takes place between objects that overlap, the behavior is undefined. If s is a null pointer, wcstombs() shall return the length required to convert the entire array regardless of the value of n, but no values are stored.

The wcstombs() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

If a wide-character code is encountered that does not correspond to a valid character (of one or more bytes each), wcstombs() shall return (size_t)-1. Otherwise, wcstombs() shall return the number of bytes stored in the character array, not including any terminating null byte. The array shall not be null-terminated if the value returned is n.

ERRORS

The wcstombs() function may fail if:

EILSEQ
A wide-character code does not correspond to a valid character.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mblen() , mbtowc() , mbstowcs() , wctomb() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


funlockfile (3p)

 Continue to this page.


pow(3p)

POW

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pow, powf, powl - power function

SYNOPSIS

#include <math.h>

double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);

DESCRIPTION

These functions shall compute the value of x raised to the power y, x**y. If x is negative, the application shall ensure that y is an integer value.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the value of x raised to the power y.

For finite values of x < 0, and finite non-integer values of y, a domain error shall occur and either a NaN (if representable), or an implementation-defined value shall be returned.

If the correct value would cause overflow, a range error shall occur and pow(), powf(), and powl() shall return ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL, respectively, with the same sign as the correct value of the function.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x or y is a NaN, a NaN shall be returned (unless specified elsewhere in this description).

For any value of y (including NaN), if x is +1, 1.0 shall be returned.

For any value of x (including NaN), if y is ±0, 1.0 shall be returned.

For any odd integer value of y > 0, if x is ±0, ±0 shall be returned.

For y > 0 and not an odd integer, if x is ±0, +0 shall be returned.

If x is -1, and y is ±Inf, 1.0 shall be returned.

For |x| < 1, if y is -Inf, +Inf shall be returned.

For |x| > 1, if y is -Inf, +0 shall be returned.

For |x| < 1, if y is +Inf, +0 shall be returned.

For |x| > 1, if y is +Inf, +Inf shall be returned.

For y an odd integer < 0, if x is -Inf, -0 shall be returned.

For y < 0 and not an odd integer, if x is -Inf, +0 shall be returned.

For y an odd integer > 0, if x is -Inf, -Inf shall be returned.

For y > 0 and not an odd integer, if x is -Inf, +Inf shall be returned.

For y < 0, if x is +Inf, +0 shall be returned.

For y > 0, if x is +Inf, +Inf shall be returned.

For y an odd integer < 0, if x is ±0, a pole error shall occur and ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL shall be returned for pow(), powf(), and powl(), respectively.

For y < 0 and not an odd integer, if x is ±0, a pole error shall occur and HUGE_VAL, HUGE_VALF, and HUGE_VALL shall be returned for pow(), powf(), and powl(), respectively.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The value of x is negative and y is a finite non-integer.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Pole Error
The value of x is zero and y is negative.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exp() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cfsetispeed(3p)

CFSETISPEED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cfsetispeed - set input baud rate

SYNOPSIS

#include <termios.h>

int cfsetispeed(struct termios *termios_p, speed_t speed);

DESCRIPTION

The cfsetispeed() function shall set the input baud rate stored in the structure pointed to by termios_p to speed.

There shall be no effect on the baud rates set in the hardware until a subsequent successful call to tcsetattr() with the same termios structure. Similarly, errors resulting from attempts to set baud rates not supported by the terminal device need not be detected until the tcsetattr() function is called.

RETURN VALUE

Upon successful completion, cfsetispeed() shall return 0; otherwise, -1 shall be returned, and errno may be set to indicate the error.

ERRORS

The cfsetispeed() function may fail if:

EINVAL
The speed value is not a valid baud rate.
EINVAL
The value of speed is outside the range of possible speed values as specified in <termios.h>.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Refer to cfgetispeed() .

FUTURE DIRECTIONS

None.

SEE ALSO

cfgetispeed() , cfgetospeed() , cfsetospeed() , tcsetattr() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lrintf (3p)

 Continue to this page.


lrintl (3p)

 Continue to this page.


getrusage(3p)

GETRUSAGE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getrusage - get information about resource utilization

SYNOPSIS

#include <sys/resource.h>

int getrusage(int who, struct rusage *r_usage);

DESCRIPTION

The getrusage() function shall provide measures of the resources used by the current process or its terminated and waited-for child processes. If the value of the who argument is RUSAGE_SELF, information shall be returned about resources used by the current process. If the value of the who argument is RUSAGE_CHILDREN, information shall be returned about resources used by the terminated and waited-for children of the current process. If the child is never waited for (for example, if the parent has SA_NOCLDWAIT set or sets SIGCHLD to SIG_IGN), the resource information for the child process is discarded and not included in the resource information provided by getrusage().

The r_usage argument is a pointer to an object of type struct rusage in which the returned information is stored.

RETURN VALUE

Upon successful completion, getrusage() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The getrusage() function shall fail if:

EINVAL
The value of the who argument is not valid.

The following sections are informative.

EXAMPLES

Using getrusage()

The following example returns information about the resources used by the current process.

#include <sys/resource.h>
...
int who = RUSAGE_SELF;
struct rusage usage;
int ret;

ret = getrusage(who, &usage);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exit() , sigaction() , time() , times() , wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/resource.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strcspn(3p)

STRCSPN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strcspn - get the length of a complementary substring

SYNOPSIS

#include <string.h>

size_t strcspn(const char *s1, const char *s2);

DESCRIPTION

The strcspn() function shall compute the length (in bytes) of the maximum initial segment of the string pointed to by s1 which consists entirely of bytes not from the string pointed to by s2.

RETURN VALUE

The strcspn() function shall return the length of the computed segment of the string pointed to by s1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strspn() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strcasecmp(3p)

STRCASECMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strcasecmp, strncasecmp - case-insensitive string comparisons

SYNOPSIS

#include <strings.h>

int strcasecmp(const char *s1, const char *s2);
int strncasecmp(const char *s1, const char *s2, size_t n);

DESCRIPTION

The strcasecmp() function shall compare, while ignoring differences in case, the string pointed to by s1 to the string pointed to by s2. The strncasecmp() function shall compare, while ignoring differences in case, not more than n bytes from the string pointed to by s1 to the string pointed to by s2.

In the POSIX locale, strcasecmp() and strncasecmp() shall behave as if the strings had been converted to lowercase and then a byte comparison performed. The results are unspecified in other locales.

RETURN VALUE

Upon completion, strcasecmp() shall return an integer greater than, equal to, or less than 0, if the string pointed to by s1 is, ignoring case, greater than, equal to, or less than the string pointed to by s2, respectively.

Upon successful completion, strncasecmp() shall return an integer greater than, equal to, or less than 0, if the possibly null-terminated array pointed to by s1 is, ignoring case, greater than, equal to, or less than the possibly null-terminated array pointed to by s2, respectively.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dbm_clearerr (3p)

 Continue to this page.


log1pf (3p)

 Continue to this page.


log1pl (3p)

 Continue to this page.


posix_spawnattr_setsigmask (3p)

 Continue to this page.


posix_trace_get_status(3p)

POSIX_TRACE_GET_ATTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_get_attr, posix_trace_get_status - retrieve the trace attributes or trace status (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_get_attr(trace_id_t trid, trace_attr_t *attr);
int posix_trace_get_status(trace_id_t trid,
struct posix_trace_status_info *statusinfo);

DESCRIPTION

The posix_trace_get_attr() function shall copy the attributes of the active trace stream identified by trid into the object pointed to by the attr argument. If the Trace Log option is supported, trid may represent a pre-recorded trace log.

The posix_trace_get_status() function shall return, in the structure pointed to by the statusinfo argument, the current trace status for the trace stream identified by the trid argument. These status values returned in the structure pointed to by statusinfo shall have been appropriately read to ensure that the returned values are consistent. If the Trace Log option is supported and the trid argument refers to a pre-recorded trace stream, the status shall be the status of the completed trace stream.

Each time the posix_trace_get_status() function is used, the overrun status of the trace stream shall be reset to POSIX_TRACE_NO_OVERRUN immediately after the call completes. If the Trace Log option is supported, the posix_trace_get_status() function shall behave the same as when the option is not supported except for the following differences:

*
If the trid argument refers to a trace stream with log, each time the posix_trace_get_status() function is used, the log overrun status of the trace stream shall be reset to POSIX_TRACE_NO_OVERRUN and the flush_error status shall be reset to zero immediately after the call completes.

*
If the trid argument refers to a pre-recorded trace stream, the status returned shall be the status of the completed trace stream and the status values of the trace stream shall not be reset.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

The posix_trace_get_attr() function stores the trace attributes in the object pointed to by attr, if successful.

The posix_trace_get_status() function stores the trace status in the object pointed to by statusinfo, if successful.

ERRORS

These functions shall fail if:

EINVAL
The trace stream argument trid does not correspond to a valid active trace stream or a valid trace log.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_attr_destroy() , posix_trace_attr_init() , posix_trace_create() , posix_trace_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cprojf (3p)

 Continue to this page.


cprojl (3p)

 Continue to this page.


pthread_setschedprio(3p)

PTHREAD_SETSCHEDPRIO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_setschedprio - dynamic thread scheduling parameters access (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_setschedprio(pthread_t thread, int prio);

DESCRIPTION

The pthread_setschedprio() function shall set the scheduling priority for the thread whose thread ID is given by thread to the value given by prio. See Scheduling Policies for a description on how this function call affects the ordering of the thread in the thread list for its new priority.

If the pthread_setschedprio() function fails, the scheduling priority of the target thread shall not be changed.

RETURN VALUE

If successful, the pthread_setschedprio() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_setschedprio() function may fail if:

EINVAL
The value of prio is invalid for the scheduling policy of the specified thread.
ENOTSUP
An attempt was made to set the priority to an unsupported value.
EPERM
The caller does not have the appropriate permission to set the scheduling policy of the specified thread.
EPERM
The implementation does not allow the application to modify the priority to the value specified.
ESRCH
The value specified by thread does not refer to an existing thread.

The pthread_setschedprio() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The pthread_setschedprio() function provides a way for an application to temporarily raise its priority and then lower it again, without having the undesired side effect of yielding to other threads of the same priority. This is necessary if the application is to implement its own strategies for bounding priority inversion, such as priority inheritance or priority ceilings. This capability is especially important if the implementation does not support the Thread Priority Protection or Thread Priority Inheritance options, but even if those options are supported it is needed if the application is to bound priority inheritance for other resources, such as semaphores.

The standard developers considered that while it might be preferable conceptually to solve this problem by modifying the specification of pthread_setschedparam(), it was too late to make such a change, as there may be implementations that would need to be changed. Therefore, this new function was introduced.

FUTURE DIRECTIONS

None.

SEE ALSO

Scheduling Policies , pthread_getschedparam() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


srandom (3p)

 Continue to this page.


fdopen(3p)

FDOPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fdopen - associate a stream with a file descriptor

SYNOPSIS

#include <stdio.h>

FILE *fdopen(int fildes, const char *mode);

DESCRIPTION

The fdopen() function shall associate a stream with a file descriptor.

The mode argument is a character string having one of the following values:

r or rb
Open a file for reading.
w or wb
Open a file for writing.
a or ab
Open a file for writing at end-of-file.
r+ or rb+ or r+b
Open a file for update (reading and writing).
w+ or wb+ or w+b
Open a file for update (reading and writing).
a+ or ab+ or a+b
Open a file for update (reading and writing) at end-of-file.

The meaning of these flags is exactly as specified in fopen(), except that modes beginning with w shall not cause truncation of the file.

Additional values for the mode argument may be supported by an implementation.

The application shall ensure that the mode of the stream as expressed by the mode argument is allowed by the file access mode of the open file description to which fildes refers. The file position indicator associated with the new stream is set to the position indicated by the file offset associated with the file descriptor.

The error and end-of-file indicators for the stream shall be cleared. The fdopen() function may cause the st_atime field of the underlying file to be marked for update.

If fildes refers to a shared memory object, the result of the fdopen() function is unspecified.

If fildes refers to a typed memory object, the result of the fdopen() function is unspecified.

The fdopen() function shall preserve the offset maximum previously set for the open file description corresponding to fildes.

RETURN VALUE

Upon successful completion, fdopen() shall return a pointer to a stream; otherwise, a null pointer shall be returned and errno set to indicate the error.

ERRORS

The fdopen() function may fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINVAL
The mode argument is not a valid mode.
EMFILE
{FOPEN_MAX} streams are currently open in the calling process.
EMFILE
{STREAM_MAX} streams are currently open in the calling process.
ENOMEM
Insufficient space to allocate a buffer.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

File descriptors are obtained from calls like open(), dup(), creat(), or pipe(), which open files but do not return streams.

RATIONALE

The file descriptor may have been obtained from open(), creat(), pipe(), dup(), or fcntl(); inherited through fork() or exec; or perhaps obtained by implementation-defined means, such as the 4.3 BSD socket() call.

The meanings of the mode arguments of fdopen() and fopen() differ. With fdopen(), open for write (w or w+) does not truncate, and append (a or a+) cannot create for writing. The mode argument formats that include a b are allowed for consistency with the ISO C standard function fopen(). The b has no effect on the resulting stream. Although not explicitly required by this volume of IEEE Std 1003.1-2001, a good implementation of append (a) mode would cause the O_APPEND flag to be set.

FUTURE DIRECTIONS

None.

SEE ALSO

Interaction of File Descriptors and Standard I/O Streams , fclose() , fopen() , open() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nearbyintf (3p)

 Continue to this page.


nearbyintl (3p)

 Continue to this page.


round(3p)

ROUND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

round, roundf, roundl - round to the nearest integer value in a floating-point format

SYNOPSIS

#include <math.h>

double round(double x);
float roundf(float x);
long double roundl(long double x);

DESCRIPTION

These functions shall round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the rounded integer value.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

If the correct value would cause overflow, a range error shall occur and round(), roundf(), and roundl() shall return the value of the macro ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (with the same sign as x), respectively.

ERRORS

These functions may fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ilogb(3p)

ILOGB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ilogb, ilogbf, ilogbl - return an unbiased exponent

SYNOPSIS

#include <math.h>

int ilogb(double x);
int ilogbf(float x);
int ilogbl(long double x);

DESCRIPTION

These functions shall return the exponent part of their argument x. Formally, the return value is the integral part of log_r|x| as a signed integral value, for non-zero x, where r is the radix of the machine's floating-point arithmetic, which is the value of FLT_RADIX defined in <float.h>.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the exponent part of x as a signed integer value. They are equivalent to calling the corresponding logb() function and casting the returned value to type int.

If x is 0, a domain error shall occur, and the value FP_ILOGB0 shall be returned.

If x is ±Inf, a domain error shall occur, and the value {INT_MAX} shall be returned.

If x is a NaN, a domain error shall occur, and the value FP_ILOGBNAN shall be returned.

If the correct value is greater than {INT_MAX}, {INT_MAX} shall be returned and a domain error shall occur.

If the correct value is less than {INT_MIN}, {INT_MIN} shall be returned and a domain error shall occur.

ERRORS

These functions shall fail if:

Domain Error
The x argument is zero, NaN, or ±Inf, or the correct value is not representable as an integer.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

The errors come from taking the expected floating-point value and converting it to int, which is an invalid operation in IEEE Std 754-1985 (since overflow, infinity, and NaN are not representable in a type int), so should be a domain error.

There are no known implementations that overflow. For overflow to happen, {INT_MAX} must be less than LDBL_MAX_EXP*log2(FLT_RADIX) or {INT_MIN} must be greater than LDBL_MIN_EXP*log2(FLT_RADIX) if subnormals are not supported, or {INT_MIN} must be greater than (LDBL_MIN_EXP-LDBL_MANT_DIG)*log2(FLT_RADIX) if subnormals are supported.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , logb() , scalb() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <float.h>, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_getschedpolicy(3p)

PTHREAD_ATTR_GETSCHEDPOLICY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getschedpolicy, pthread_attr_setschedpolicy - get and set the schedpolicy attribute (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_attr_getschedpolicy(const pthread_attr_t *restrict attr,
int *restrict policy);
int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);

DESCRIPTION

The pthread_attr_getschedpolicy() and pthread_attr_setschedpolicy() functions, respectively, shall get and set the schedpolicy attribute in the attr argument.

The supported values of policy shall include SCHED_FIFO, SCHED_RR, and SCHED_OTHER, which are defined in the <sched.h> header. When threads executing with the scheduling policy SCHED_FIFO, SCHED_RR, or SCHED_SPORADIC are waiting on a mutex, they shall acquire the mutex in priority order when the mutex is unlocked.

RETURN VALUE

If successful, the pthread_attr_getschedpolicy() and pthread_attr_setschedpolicy() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_attr_setschedpolicy() function may fail if:

EINVAL
The value of policy is not valid.
ENOTSUP
An attempt was made to set the attribute to an unsupported value.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

After these attributes have been set, a thread can be created with the specified attributes using pthread_create(). Using these routines does not affect the current running thread.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_attr_getscope() , pthread_attr_getinheritsched() , pthread_attr_getschedparam() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strftime(3p)

STRFTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strftime - convert date and time to a string

SYNOPSIS

#include <time.h>

size_t strftime(char *restrict s, size_t maxsize,
const char *restrict format, const struct tm *restrict timeptr);

DESCRIPTION

The strftime() function shall place bytes into the array pointed to by s as controlled by the string pointed to by format. The format is a character string, beginning and ending in its initial shift state, if any. The format string consists of zero or more conversion specifications and ordinary characters. A conversion specification consists of a '%' character, possibly followed by an E or O modifier, and a terminating conversion specifier character that determines the conversion specification's behavior. All ordinary characters (including the terminating null byte) are copied unchanged into the array. If copying takes place between objects that overlap, the behavior is undefined. No more than maxsize bytes are placed into the array. Each conversion specifier is replaced by appropriate characters as described in the following list. The appropriate characters are determined using the LC_TIME category of the current locale and by the values of zero or more members of the broken-down time structure pointed to by timeptr, as specified in brackets in the description. If any of the specified values are outside the normal range, the characters stored are unspecified.

Local timezone information is used as though strftime() called tzset().

The following conversion specifications are supported:

%a
Replaced by the locale's abbreviated weekday name. [ tm_wday]
%A
Replaced by the locale's full weekday name. [ tm_wday]
%b
Replaced by the locale's abbreviated month name. [ tm_mon]
%B
Replaced by the locale's full month name. [ tm_mon]
%c
Replaced by the locale's appropriate date and time representation. (See the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>.)
%C
Replaced by the year divided by 100 and truncated to an integer, as a decimal number [00,99]. [ tm_year]
%d
Replaced by the day of the month as a decimal number [01,31]. [ tm_mday]
%D
Equivalent to %m / %d / %y . [ tm_mon, tm_mday, tm_year]
%e
Replaced by the day of the month as a decimal number [1,31]; a single digit is preceded by a space. [ tm_mday]
%F
Equivalent to %Y - %m - %d (the ISO 8601:2000 standard date format). [ tm_year, tm_mon, tm_mday]
%g
Replaced by the last 2 digits of the week-based year (see below) as a decimal number [00,99]. [ tm_year, tm_wday, tm_yday]
%G
Replaced by the week-based year (see below) as a decimal number (for example, 1977). [ tm_year, tm_wday, tm_yday]
%h
Equivalent to %b . [ tm_mon]
%H
Replaced by the hour (24-hour clock) as a decimal number [00,23]. [ tm_hour]
%I
Replaced by the hour (12-hour clock) as a decimal number [01,12]. [ tm_hour]
%j
Replaced by the day of the year as a decimal number [001,366]. [ tm_yday]
%m
Replaced by the month as a decimal number [01,12]. [ tm_mon]
%M
Replaced by the minute as a decimal number [00,59]. [ tm_min]
%n
Replaced by a <newline>.
%p
Replaced by the locale's equivalent of either a.m. or p.m. [ tm_hour]
%r
Replaced by the time in a.m. and p.m. notation; in the POSIX locale this shall be equivalent to %I : %M : %S %p . [ tm_hour, tm_min, tm_sec]
%R
Replaced by the time in 24-hour notation ( %H : %M ). [ tm_hour, tm_min]
%S
Replaced by the second as a decimal number [00,60]. [ tm_sec]
%t
Replaced by a <tab>.
%T
Replaced by the time ( %H : %M : %S ). [ tm_hour, tm_min, tm_sec]
%u
Replaced by the weekday as a decimal number [1,7], with 1 representing Monday. [ tm_wday]
%U
Replaced by the week number of the year as a decimal number [00,53]. The first Sunday of January is the first day of week 1; days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
%V
Replaced by the week number of the year (Monday as the first day of the week) as a decimal number [01,53]. If the week containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. Both January 4th and the first Thursday of January are always in week 1. [ tm_year, tm_wday, tm_yday]
%w
Replaced by the weekday as a decimal number [0,6], with 0 representing Sunday. [ tm_wday]
%W
Replaced by the week number of the year as a decimal number [00,53]. The first Monday of January is the first day of week 1; days in the new year before this are in week 0. [ tm_year, tm_wday, tm_yday]
%x
Replaced by the locale's appropriate date representation. (See the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>.)
%X
Replaced by the locale's appropriate time representation. (See the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>.)
%y
Replaced by the last two digits of the year as a decimal number [00,99]. [ tm_year]
%Y
Replaced by the year as a decimal number (for example, 1997). [ tm_year]
%z
Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ), or by no characters if no timezone is determinable. For example, "-0430" means 4 hours 30 minutes behind UTC (west of Greenwich). If tm_isdst is zero, the standard time offset is used. If tm_isdst is greater than zero, the daylight savings time offset is used. If tm_isdst is negative, no characters are returned. [ tm_isdst]
%Z
Replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists. [ tm_isdst]
%%
Replaced by % .

If a conversion specification does not correspond to any of the above, the behavior is undefined.

If a struct tm broken-down time structure is created by localtime() or localtime_r(), or modified by mktime(), and the value of TZ is subsequently modified, the results of the %Z and %z strftime() conversion specifiers are undefined, when strftime() is called with such a broken-down time structure.

If a struct tm broken-down time structure is created or modified by gmtime() or gmtime_r(), it is unspecified whether the result of the %Z and %z conversion specifiers shall refer to UTC or the current local timezone, when strftime() is called with such a broken-down time structure.

Modified Conversion Specifiers

Some conversion specifiers can be modified by the E or O modifier characters to indicate that an alternative format or specification should be used rather than the one normally used by the unmodified conversion specifier. If the alternative format or specification does not exist for the current locale (see ERA in the Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.5, LC_TIME), the behavior shall be as if the unmodified conversion specification were used.

%Ec
Replaced by the locale's alternative appropriate date and time representation.
%EC
Replaced by the name of the base year (period) in the locale's alternative representation.
%Ex
Replaced by the locale's alternative date representation.
%EX
Replaced by the locale's alternative time representation.
%Ey
Replaced by the offset from %EC (year only) in the locale's alternative representation.
%EY
Replaced by the full alternative year representation.
%Od
Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading zeros if there is any alternative symbol for zero; otherwise, with leading spaces.
%Oe
Replaced by the day of the month, using the locale's alternative numeric symbols, filled as needed with leading spaces.
%OH
Replaced by the hour (24-hour clock) using the locale's alternative numeric symbols.
%OI
Replaced by the hour (12-hour clock) using the locale's alternative numeric symbols.
%Om
Replaced by the month using the locale's alternative numeric symbols.
%OM
Replaced by the minutes using the locale's alternative numeric symbols.
%OS
Replaced by the seconds using the locale's alternative numeric symbols.
%Ou
Replaced by the weekday as a number in the locale's alternative representation (Monday=1).
%OU
Replaced by the week number of the year (Sunday as the first day of the week, rules corresponding to %U ) using the locale's alternative numeric symbols.
%OV
Replaced by the week number of the year (Monday as the first day of the week, rules corresponding to %V ) using the locale's alternative numeric symbols.
%Ow
Replaced by the number of the weekday (Sunday=0) using the locale's alternative numeric symbols.
%OW
Replaced by the week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols.
%Oy
Replaced by the year (offset from %C ) using the locale's alternative numeric symbols.

%g , %G , and %V give values according to the ISO 8601:2000 standard week-based year. In this system, weeks begin on a Monday and week 1 of the year is the week that includes January 4th, which is also the week that includes the first Thursday of the year, and is also the first week that contains at least four days in the year. If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of the last week of the preceding year; thus, for Saturday 2nd January 1999, %G is replaced by 1998 and %V is replaced by 53. If December 29th, 30th, or 31st is a Monday, it and any following days are part of week 1 of the following year. Thus, for Tuesday 30th December 1997, %G is replaced by 1998 and %V is replaced by 01.

If a conversion specifier is not one of the above, the behavior is undefined.

RETURN VALUE

If the total number of resulting bytes including the terminating null byte is not more than maxsize, strftime() shall return the number of bytes placed into the array pointed to by s, not including the terminating null byte. Otherwise, 0 shall be returned and the contents of the array are unspecified.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Getting a Localized Date String

The following example first sets the locale to the user's default. The locale information will be used in the nl_langinfo() and strftime() functions. The nl_langinfo() function returns the localized date string which specifies how the date is laid out. The strftime() function takes this information and, using the tm structure for values, places the date and time information into datestring.

#include <time.h>
#include <locale.h>
#include <langinfo.h>
...
struct tm *tm;
char datestring[256];
...
setlocale (LC_ALL, "");
...
strftime (datestring, sizeof(datestring), nl_langinfo (D_T_FMT), tm);
...

APPLICATION USAGE

The range of values for %S is [00,60] rather than [00,59] to allow for the occasional leap second.

Some of the conversion specifications are duplicates of others. They are included for compatibility with nl_cxtime() and nl_ascxtime(), which were published in Issue 2.

Applications should use %Y (4-digit years) in preference to %y (2-digit years).

In the C locale, the E and O modifiers are ignored and the replacement strings for the following specifiers are:

%a
The first three characters of %A .
%A
One of Sunday, Monday, ..., Saturday.
%b
The first three characters of %B .
%B
One of January, February, ..., December.
%c
Equivalent to %a %b %e %T %Y .
%p
One of AM or PM.
%r
Equivalent to %I : %M : %S %p .
%x
Equivalent to %m / %d / %y .
%X
Equivalent to %T .
%Z
Implementation-defined.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asctime() , clock() , ctime() , difftime() , getdate() , gmtime() , localtime() , mktime() , strptime() , time() , tzset() , utime() , Base Definitions volume of IEEE Std 1003.1-2001, Section 7.3.5, LC_TIME, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vfork(3p)

VFORK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

vfork - create a new process; share virtual memory

SYNOPSIS

#include <unistd.h>

pid_t vfork(void);

DESCRIPTION

The vfork() function shall be equivalent to fork(), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.

RETURN VALUE

Upon successful completion, vfork() shall return 0 to the child process and return the process ID of the child process to the parent process. Otherwise, -1 shall be returned to the parent, no child process shall be created, and errno shall be set to indicate the error.

ERRORS

The vfork() function shall fail if:

EAGAIN
The system-wide limit on the total number of processes under execution would be exceeded, or the system-imposed limit on the total number of processes under execution by a single user would be exceeded.
ENOMEM
There is insufficient swap space for the new process.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Conforming applications are recommended not to depend on vfork(), but to use fork() instead. The vfork() function may be withdrawn in a future version.

On some implementations, vfork() is equivalent to fork().

The vfork() function differs from fork() only in that the child process can share code and data with the calling process (parent process). This speeds cloning activity significantly at a risk to the integrity of the parent process if vfork() is misused.

The use of vfork() for any purpose except as a prelude to an immediate call to a function from the exec family, or to _exit(), is not advised.

The vfork() function can be used to create new processes without fully copying the address space of the old process. If a forked process is simply going to call exec, the data space copied from the parent to the child by fork() is not used. This is particularly inefficient in a paged environment, making vfork() particularly useful. Depending upon the size of the parent's data space, vfork() can give a significant performance improvement over fork().

The vfork() function can normally be used just like fork(). It does not work, however, to return while running in the child's context from the caller of vfork() since the eventual return from vfork() would then return to a no longer existent stack frame. Care should be taken, also, to call _exit() rather than exit() if exec cannot be used, since exit() flushes and closes standard I/O channels, thereby damaging the parent process' standard I/O data structures. (Even with fork(), it is wrong to call exit(), since buffered data would then be flushed twice.)

If signal handlers are invoked in the child process after vfork(), they must follow the same rules as other code in the child process.

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

exec() , exit() , fork() , wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


casinf (3p)

 Continue to this page.


isnan(3p)

ISNAN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isnan - test for a NaN

SYNOPSIS

#include <math.h>

int isnan(real-floating x);

DESCRIPTION

The isnan() macro shall determine whether its argument value is a NaN. First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.

RETURN VALUE

The isnan() macro shall return a non-zero value if and only if its argument has a NaN value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fpclassify() , isfinite() , isinf() , isnormal() , signbit() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


casinh(3p)

CASINH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

casinh, casinhf, casinhl - complex arc hyperbolic sine functions

SYNOPSIS

#include <complex.h>

double complex casinh(double complex z);
float complex casinhf(float complex z);
long double complex casinhl(long double complex z);

DESCRIPTION

These functions shall compute the complex arc hyperbolic sine of z, with branch cuts outside the interval [-i, +i] along the imaginary axis.

RETURN VALUE

These functions shall return the complex arc hyperbolic sine value, in the range of a strip mathematically unbounded along the real axis and in the interval [-ipi/2, +ipi/2] along the imaginary axis.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

csinh() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


casinl (3p)

 Continue to this page.


wordexp(3p)

WORDEXP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wordexp, wordfree - perform word expansions

SYNOPSIS

#include <wordexp.h>

int wordexp(const char *restrict words, wordexp_t *restrict pwordexp,
int flags);
void wordfree(wordexp_t *pwordexp);

DESCRIPTION

The wordexp() function shall perform word expansions as described in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.6, Word Expansions, subject to quoting as in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.2, Quoting, and place the list of expanded words into the structure pointed to by pwordexp.

The words argument is a pointer to a string containing one or more words to be expanded. The expansions shall be the same as would be performed by the command line interpreter if words were the part of a command line representing the arguments to a utility. Therefore, the application shall ensure that words does not contain an unquoted <newline> or any of the unquoted shell special characters '|' , '&' , ';' , '<' , '>' except in the context of command substitution as specified in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.6.3, Command Substitution. It also shall not contain unquoted parentheses or braces, except in the context of command or variable substitution. The application shall ensure that every member of words which it expects to have expanded by wordexp() does not contain an unquoted initial comment character. The application shall also ensure that any words which it intends to be ignored (because they begin or continue a comment) are deleted from words. If the argument words contains an unquoted comment character (number sign) that is the beginning of a token, wordexp() shall either treat the comment character as a regular character, or interpret it as a comment indicator and ignore the remainder of words.

The structure type wordexp_t is defined in the <wordexp.h> header and includes at least the following members:
Member Type | Member Name | Description
size_t | we_wordc | Count of words matched by words.
char ** | we_wordv | Pointer to list of expanded words.
size_t | we_offs | Slots to reserve at the beginning of pwordexp->we_wordv.

The wordexp() function shall store the number of generated words into pwordexp->we_wordc and a pointer to a list of pointers to words in pwordexp->we_wordv. Each individual field created during field splitting (see the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.6.5, Field Splitting) or pathname expansion (see the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.6.6, Pathname Expansion) shall be a separate word in the pwordexp->we_wordv list. The words shall be in order as described in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.6, Word Expansions. The first pointer after the last word pointer shall be a null pointer. The expansion of special parameters described in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.5.2, Special Parameters is unspecified.

It is the caller's responsibility to allocate the storage pointed to by pwordexp. The wordexp() function shall allocate other space as needed, including memory pointed to by pwordexp->we_wordv. The wordfree() function frees any memory associated with pwordexp from a previous call to wordexp().

The flags argument is used to control the behavior of wordexp(). The value of flags is the bitwise-inclusive OR of zero or more of the following constants, which are defined in <wordexp.h>:

WRDE_APPEND
Append words generated to the ones from a previous call to wordexp().
WRDE_DOOFFS
Make use of pwordexp->we_offs. If this flag is set, pwordexp->we_offs is used to specify how many null pointers to add to the beginning of pwordexp->we_wordv. In other words, pwordexp->we_wordv shall point to pwordexp->we_offs null pointers, followed by pwordexp->we_wordc word pointers, followed by a null pointer.
WRDE_NOCMD
If the implementation supports the utilities defined in the Shell and Utilities volume of IEEE Std 1003.1-2001, fail if command substitution, as specified in the Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.6.3, Command Substitution, is requested.
WRDE_REUSE
The pwordexp argument was passed to a previous successful call to wordexp(), and has not been passed to wordfree(). The result shall be the same as if the application had called wordfree() and then called wordexp() without WRDE_REUSE.
WRDE_SHOWERR
Do not redirect stderr to /dev/null.
WRDE_UNDEF
Report error on an attempt to expand an undefined shell variable.

The WRDE_APPEND flag can be used to append a new set of words to those generated by a previous call to wordexp(). The following rules apply to applications when two or more calls to wordexp() are made with the same value of pwordexp and without intervening calls to wordfree():

1.
The first such call shall not set WRDE_APPEND. All subsequent calls shall set it.

2.
All of the calls shall set WRDE_DOOFFS, or all shall not set it.

3.
After the second and each subsequent call, pwordexp->we_wordv shall point to a list containing the following:
a.
Zero or more null pointers, as specified by WRDE_DOOFFS and pwordexp->we_offs

b.
Pointers to the words that were in the pwordexp->we_wordv list before the call, in the same order as before

c.
Pointers to the new words generated by the latest call, in the specified order

4.
The count returned in pwordexp->we_wordc shall be the total number of words from all of the calls.

5.
The application can change any of the fields after a call to wordexp(), but if it does it shall reset them to the original value before a subsequent call, using the same pwordexp value, to wordfree() or wordexp() with the WRDE_APPEND or WRDE_REUSE flag.

If the implementation supports the utilities defined in the Shell and Utilities volume of IEEE Std 1003.1-2001, and words contains an unquoted character- <newline>, '|' , '&' , ';' , '<' , '>' , '(' , ')' , '{' , '}' - in an inappropriate context, wordexp() shall fail, and the number of expanded words shall be 0.

Unless WRDE_SHOWERR is set in flags, wordexp() shall redirect stderr to /dev/null for any utilities executed as a result of command substitution while expanding words. If WRDE_SHOWERR is set, wordexp() may write messages to stderr if syntax errors are detected while expanding words.

The application shall ensure that if WRDE_DOOFFS is set, then pwordexp->we_offs has the same value for each wordexp() call and wordfree() call using a given pwordexp.

The following constants are defined as error return values:

WRDE_BADCHAR
One of the unquoted characters- <newline>, '|' , '&' , ';' , '<' , '>' , '(' , ')' , '{' , '}' - appears in words in an inappropriate context.
WRDE_BADVAL
Reference to undefined shell variable when WRDE_UNDEF is set in flags.
WRDE_CMDSUB
Command substitution requested when WRDE_NOCMD was set in flags.
WRDE_NOSPACE
Attempt to allocate memory failed.
WRDE_SYNTAX
Shell syntax error, such as unbalanced parentheses or unterminated string.

RETURN VALUE

Upon successful completion, wordexp() shall return 0. Otherwise, a non-zero value, as described in <wordexp.h>, shall be returned to indicate an error. If wordexp() returns the value WRDE_NOSPACE, then pwordexp->we_wordc and pwordexp->we_wordv shall be updated to reflect any words that were successfully expanded. In other cases, they shall not be modified.

The wordfree() function shall not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The wordexp() function is intended to be used by an application that wants to do all of the shell's expansions on a word or words obtained from a user. For example, if the application prompts for a filename (or list of filenames) and then uses wordexp() to process the input, the user could respond with anything that would be valid as input to the shell.

The WRDE_NOCMD flag is provided for applications that, for security or other reasons, want to prevent a user from executing shell commands. Disallowing unquoted shell special characters also prevents unwanted side effects, such as executing a command or writing a file.

RATIONALE

This function was included as an alternative to glob(). There had been continuing controversy over exactly what features should be included in glob(). It is hoped that by providing wordexp() (which provides all of the shell word expansions, but which may be slow to execute) and glob() (which is faster, but which only performs pathname expansion, without tilde or parameter expansion) this will satisfy the majority of applications.

While wordexp() could be implemented entirely as a library routine, it is expected that most implementations run a shell in a subprocess to do the expansion.

Two different approaches have been proposed for how the required information might be presented to the shell and the results returned. They are presented here as examples.

One proposal is to extend the echo utility by adding a -q option. This option would cause echo to add a backslash before each backslash and <blank> that occurs within an argument. The wordexp() function could then invoke the shell as follows:

(void) strcpy(buffer, "echo -q");
(void) strcat(buffer, words);
if ((flags & WRDE_SHOWERR) == 0)
    (void) strcat(buffer, "2>/dev/null");
f = popen(buffer, "r");

The wordexp() function would read the resulting output, remove unquoted backslashes, and break into words at unquoted <blank>s. If the WRDE_NOCMD flag was set, wordexp() would have to scan words before starting the subshell to make sure that there would be no command substitution. In any case, it would have to scan words for unquoted special characters.

Another proposal is to add the following options to sh:

-w wordlist

This option provides a wordlist expansion service to applications. The words in wordlist shall be expanded and the following written to standard output:

1.
The count of the number of words after expansion, in decimal, followed by a null byte

2.
The number of bytes needed to represent the expanded words (not including null separators), in decimal, followed by a null byte

3.
The expanded words, each terminated by a null byte

If an error is encountered during word expansion, sh exits with a non-zero status after writing the former to report any words successfully expanded

-P
Run in "protected" mode. If specified with the -w option, no command substitution shall be performed.

With these options, wordexp() could be implemented fairly simply by creating a subprocess using fork() and executing sh using the line:

execl(<shell path>, "sh", "-P", "-w", words, (char *)0);

after directing standard error to /dev/null.

It seemed objectionable for a library routine to write messages to standard error, unless explicitly requested, so wordexp() is required to redirect standard error to /dev/null to ensure that no messages are generated, even for commands executed for command substitution. The WRDE_SHOWERR flag can be specified to request that error messages be written.

The WRDE_REUSE flag allows the implementation to avoid the expense of freeing and reallocating memory, if that is possible. A minimal implementation can call wordfree() when WRDE_REUSE is set.

FUTURE DIRECTIONS

None.

SEE ALSO

fnmatch() , glob() , the Base Definitions volume of IEEE Std 1003.1-2001, <wordexp.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, Chapter 2, Shell Command Language

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


btowc(3p)

BTOWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

btowc - single byte to wide character conversion

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

wint_t btowc(int c);

DESCRIPTION

The btowc() function shall determine whether c constitutes a valid (one-byte) character in the initial shift state.

The behavior of this function shall be affected by the LC_CTYPE category of the current locale.

RETURN VALUE

The btowc() function shall return WEOF if c has the value EOF or if (unsigned char) c does not constitute a valid (one-byte) character in the initial shift state. Otherwise, it shall return the wide-character representation of that character.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wctob() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_destroy (3p)

 Continue to this page.


posix_trace_attr_setstreamsize (3p)

 Continue to this page.


setrlimit (3p)

 Continue to this page.


wctype(3p)

WCTYPE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wctype - define character class

SYNOPSIS

#include <wctype.h>

wctype_t wctype(const char *property);

DESCRIPTION

The wctype() function is defined for valid character class names as defined in the current locale. The property argument is a string identifying a generic character class for which codeset-specific type information is required. The following character class names shall be defined in all locales:

alnum
alpha
blank
cntrl

digit
graph
lower
print

punct
space
upper
xdigit

Additional character class names defined in the locale definition file (category LC_CTYPE ) can also be specified.

The function shall return a value of type wctype_t, which can be used as the second argument to subsequent calls of iswctype(). The wctype() function shall determine values of wctype_t according to the rules of the coded character set defined by character type information in the program's locale (category LC_CTYPE ). The values returned by wctype() shall be valid until a call to setlocale() that modifies the category LC_CTYPE .

RETURN VALUE

The wctype() function shall return 0 if the given character class name is not valid for the current locale (category LC_CTYPE ); otherwise, it shall return an object of type wctype_t that can be used in calls to iswctype().

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswctype() , the Base Definitions volume of IEEE Std 1003.1-2001, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pread (3p)

 Continue to this page.


calloc(3p)

CALLOC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

calloc - a memory allocator

SYNOPSIS

#include <stdlib.h>

void *calloc(size_t nelem, size_t elsize);

DESCRIPTION

The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0.

The order and contiguity of storage allocated by successive calls to calloc() is unspecified. The pointer returned if the allocation succeeds shall be suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly freed or reallocated). Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned shall point to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer shall be returned. If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer.

RETURN VALUE

Upon successful completion with both nelem and elsize non-zero, calloc() shall return a pointer to the allocated space. If either nelem or elsize is 0, then either a null pointer or a unique pointer value that can be successfully passed to free() shall be returned. Otherwise, it shall return a null pointer and set errno to indicate the error.

ERRORS

The calloc() function shall fail if:

ENOMEM
Insufficient memory is available.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

There is now no requirement for the implementation to support the inclusion of <malloc.h>.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

free() , malloc() , realloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cbrtf (3p)

 Continue to this page.


cbrtl (3p)

 Continue to this page.


optind (3p)

 Continue to this page.


isgreaterequal(3p)

ISGREATEREQUAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isgreaterequal - test if x is greater than or equal to y

SYNOPSIS

#include <math.h>

int isgreaterequal(real-floating x, real-floating y);

DESCRIPTION

The isgreaterequal() macro shall determine whether its first argument is greater than or equal to its second argument. The value of isgreaterequal( x, y) shall be equal to (x) >= (y); however, unlike (x) >= (y), isgreaterequal( x, y) shall not raise the invalid floating-point exception when x and y are unordered.

RETURN VALUE

Upon successful completion, the isgreaterequal() macro shall return the value of (x) >= (y).

If x or y is NaN, 0 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values, exactly one of the relationships (less, greater, and equal) is true. Relational operators may raise the invalid floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. This macro is a quiet (non-floating-point exception raising) version of a relational operator. It facilitates writing efficient code that accounts for NaNs without suffering the invalid floating-point exception. In the SYNOPSIS section, real-floating indicates that the argument shall be an expression of real-floating type.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isgreater() , isless() , islessequal() , islessgreater() , isunordered() , the Base Definitions volume of IEEE Std 1003.1-2001 <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_close (3p)

 Continue to this page.


posix_trace_open(3p)

POSIX_TRACE_CLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_close, posix_trace_open, posix_trace_rewind - trace log management (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_close(trace_id_t trid);
int posix_trace_open(int file_desc, trace_id_t *trid);
int posix_trace_rewind(trace_id_t trid);

DESCRIPTION

The posix_trace_close() function shall deallocate the trace log identifier indicated by trid, and all of its associated resources. If there is no valid trace log pointed to by the trid, this function shall fail.

The posix_trace_open() function shall allocate the necessary resources and establish the connection between a trace log identified by the file_desc argument and a trace stream identifier identified by the object pointed to by the trid argument. The file_desc argument should be a valid open file descriptor that corresponds to a trace log. The file_desc argument shall be open for reading. The current trace event timestamp, which specifies the timestamp of the trace event that will be read by the next call to posix_trace_getnext_event(), shall be set to the timestamp of the oldest trace event recorded in the trace log identified by trid.

The posix_trace_open() function shall return a trace stream identifier in the variable pointed to by the trid argument, that may only be used by the following functions:

posix_trace_close()
posix_trace_eventid_equal()
posix_trace_eventid_get_name()
posix_trace_eventtypelist_getnext_id()
posix_trace_eventtypelist_rewind()

posix_trace_get_attr()
posix_trace_get_status()
posix_trace_getnext_event()
posix_trace_rewind()

In particular, notice that the operations normally used by a trace controller process, such as posix_trace_start(), posix_trace_stop(), or posix_trace_shutdown(), cannot be invoked using the trace stream identifier returned by the posix_trace_open() function.

The posix_trace_rewind() function shall reset the current trace event timestamp, which specifies the timestamp of the trace event that will be read by the next call to posix_trace_getnext_event(), to the timestamp of the oldest trace event recorded in the trace log identified by trid.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

If successful, the posix_trace_open() function stores the trace stream identifier value in the object pointed to by trid.

ERRORS

The posix_trace_open() function shall fail if:

EINTR
The operation was interrupted by a signal and thus no trace log was opened.
EINVAL
The object pointed to by file_desc does not correspond to a valid trace log.

The posix_trace_close() and posix_trace_rewind() functions may fail if:

EINVAL
The object pointed to by trid does not correspond to a valid trace log.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_get_attr() , posix_trace_get_filter() , posix_trace_getnext_event() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


shm_unlink(3p)

SHM_UNLINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shm_unlink - remove a shared memory object (REALTIME)

SYNOPSIS

#include <sys/mman.h>

int shm_unlink(const char *name);

DESCRIPTION

The shm_unlink() function shall remove the name of the shared memory object named by the string pointed to by name.

If one or more references to the shared memory object exist when the object is unlinked, the name shall be removed before shm_unlink() returns, but the removal of the memory object contents shall be postponed until all open and map references to the shared memory object have been removed.

Even if the object continues to exist after the last shm_unlink(), reuse of the name shall subsequently cause shm_open() to behave as if no shared memory object of this name exists (that is, shm_open() will fail if O_CREAT is not set, or will create a new shared memory object if O_CREAT is set).

RETURN VALUE

Upon successful completion, a value of zero shall be returned. Otherwise, a value of -1 shall be returned and errno set to indicate the error. If -1 is returned, the named shared memory object shall not be changed by this function call.

ERRORS

The shm_unlink() function shall fail if:

EACCES
Permission is denied to unlink the named shared memory object.
ENAMETOOLONG
The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
The named shared memory object does not exist.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Names of memory objects that were allocated with open() are deleted with unlink() in the usual fashion. Names of memory objects that were allocated with shm_open() are deleted with shm_unlink(). Note that the actual memory object is not destroyed until the last close and unmap on it have occurred if it was already in use.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

close() , mmap() , munmap() , shmat() , shmctl() , shmdt() , shm_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cpowf (3p)

 Continue to this page.


cpowl (3p)

 Continue to this page.


sin(3p)

SIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sin, sinf, sinl - sine function

SYNOPSIS

#include <math.h>

double sin(double x);
float sinf(float x);
long double sinl(long double x);

DESCRIPTION

These functions shall compute the sine of their argument x, measured in radians.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the sine of x.

If x is NaN, a NaN shall be returned.

If x is ±0, x shall be returned.

If x is subnormal, a range error may occur and x should be returned.

If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is ±Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

These functions may fail if:

Range Error
The value of x is subnormal

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

Taking the Sine of a 45-Degree Angle

#include <math.h>
...
double radians = 45.0 * M_PI / 180;
double result;
...
result = sin(radians);

APPLICATION USAGE

These functions may lose accuracy when their argument is near a multiple of pi or is far from 0.0.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asin() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tan(3p)

TAN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tan, tanf, tanl - tangent function

SYNOPSIS

#include <math.h>

double tan(double x);
float tanf(float x);
long double tanl(long double x);

DESCRIPTION

These functions shall compute the tangent of their argument x, measured in radians.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the tangent of x.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0, x shall be returned.

If x is subnormal, a range error may occur and x should be returned.

If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

If the correct value would cause overflow, a range error shall occur and tan(), tanf(), and tanl() shall return ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL, respectively, with the same sign as the correct value of the function.

ERRORS

These functions shall fail if:

Domain Error
The value of x is ±Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Range Error
The result overflows

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows, or the value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

Taking the Tangent of a 45-Degree Angle

#include <math.h>
...
double radians = 45.0 * M_PI / 180;
double result;
...
result = tan (radians);

APPLICATION USAGE

There are no known floating-point representations such that for a normal argument, tan( x) is either overflow or underflow.

These functions may lose accuracy when their argument is near a multiple of pi/2 or is far from 0.0.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

atan() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_create_withlog (3p)

 Continue to this page.


posix_trace_shutdown (3p)

 Continue to this page.


telldir(3p)

TELLDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

telldir - current location of a named directory stream

SYNOPSIS

#include <dirent.h>

long telldir(DIR *dirp);

DESCRIPTION

The telldir() function shall obtain the current location associated with the directory stream specified by dirp.

If the most recent operation on the directory stream was a seekdir(), the directory position returned from the telldir() shall be the same as that supplied as a loc argument for seekdir().

RETURN VALUE

Upon successful completion, telldir() shall return the current location of the specified directory stream.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

opendir() , readdir() , seekdir() , the Base Definitions volume of IEEE Std 1003.1-2001, <dirent.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


snprintf (3p)

 Continue to this page.


listen(3p)

LISTEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

listen - listen for socket connections and limit the queue of incoming connections

SYNOPSIS

#include <sys/socket.h>

int listen(int socket, int backlog);

DESCRIPTION

The listen() function shall mark a connection-mode socket, specified by the socket argument, as accepting connections.

The backlog argument provides a hint to the implementation which the implementation shall use to limit the number of outstanding connections in the socket's listen queue. Implementations may impose a limit on backlog and silently reduce the specified value. Normally, a larger backlog argument value shall result in a larger or equal length of the listen queue. Implementations shall support values of backlog up to SOMAXCONN, defined in <sys/socket.h>.

The implementation may include incomplete connections in its listen queue. The limits on the number of incomplete connections and completed connections queued may be different.

The implementation may have an upper limit on the length of the listen queue-either global or per accepting socket. If backlog exceeds this limit, the length of the listen queue is set to the limit.

If listen() is called with a backlog argument value that is less than 0, the function behaves as if it had been called with a backlog argument value of 0.

A backlog argument of 0 may allow the socket to accept connections, in which case the length of the listen queue may be set to an implementation-defined minimum value.

The socket in use may require the process to have appropriate privileges to use the listen() function.

RETURN VALUE

Upon successful completions, listen() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The listen() function shall fail if:

EBADF
The socket argument is not a valid file descriptor.
EDESTADDRREQ

The socket is not bound to a local address, and the protocol does not support listening on an unbound socket.

EINVAL
The socket is already connected.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The socket protocol does not support listen().

The listen() function may fail if:

EACCES
The calling process does not have the appropriate privileges.
EINVAL
The socket has been shut down.
ENOBUFS
Insufficient resources are available in the system to complete the call.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

accept() , connect() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


munmap(3p)

MUNMAP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

munmap - unmap pages of memory

SYNOPSIS

#include <sys/mman.h>

int munmap(void *addr, size_t len);

DESCRIPTION

The munmap() function shall remove any mappings for those entire pages containing any part of the address space of the process starting at addr and continuing for len bytes. Further references to these pages shall result in the generation of a SIGSEGV signal to the process. If there are no mappings in the specified address range, then munmap() has no effect.

The implementation shall require that addr be a multiple of the page size {PAGESIZE}.

If a mapping to be removed was private, any modifications made in this address range shall be discarded.

Any memory locks (see mlock() and mlockall() ) associated with this address range shall be removed, as if by an appropriate call to munlock().

If a mapping removed from a typed memory object causes the corresponding address range of the memory pool to be inaccessible by any process in the system except through allocatable mappings (that is, mappings of typed memory objects opened with the POSIX_TYPED_MEM_MAP_ALLOCATABLE flag), then that range of the memory pool shall become deallocated and may become available to satisfy future typed memory allocation requests.

A mapping removed from a typed memory object opened with the POSIX_TYPED_MEM_MAP_ALLOCATABLE flag shall not affect in any way the availability of that typed memory for allocation.

The behavior of this function is unspecified if the mapping was not established by a call to mmap().

RETURN VALUE

Upon successful completion, munmap() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The munmap() function shall fail if:

EINVAL
Addresses in the range [addr,addr+len) are outside the valid range for the address space of a process.
EINVAL
The len argument is 0.
EINVAL
The addr argument is not a multiple of the page size as returned by sysconf().

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The munmap() function is only supported if the Memory Mapped Files option or the Shared Memory Objects option is supported.

RATIONALE

The munmap() function corresponds to SVR4, just as the mmap() function does.

It is possible that an application has applied process memory locking to a region that contains shared memory. If this has occurred, the munmap() call ignores those locks and, if necessary, causes those locks to be removed.

FUTURE DIRECTIONS

None.

SEE ALSO

mlock() , mlockall() , mmap() , posix_typed_mem_open() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vfscanf (3p)

 Continue to this page.


mprotect(3p)

MPROTECT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mprotect - set protection of memory mapping

SYNOPSIS

#include <sys/mman.h>

int mprotect(void *addr, size_t len, int prot);

DESCRIPTION

The mprotect() function shall change the access protections to be that specified by prot for those whole pages containing any part of the address space of the process starting at address addr and continuing for len bytes. The parameter prot determines whether read, write, execute, or some combination of accesses are permitted to the data being mapped. The prot argument should be either PROT_NONE or the bitwise-inclusive OR of one or more of PROT_READ, PROT_WRITE, and PROT_EXEC.

If an implementation cannot support the combination of access types specified by prot, the call to mprotect() shall fail.

An implementation may permit accesses other than those specified by prot; however, no implementation shall permit a write to succeed where PROT_WRITE has not been set or shall permit any access where PROT_NONE alone has been set. Implementations shall support at least the following values of prot: PROT_NONE, PROT_READ, PROT_WRITE, and the bitwise-inclusive OR of PROT_READ and PROT_WRITE. If PROT_WRITE is specified, the application shall ensure that it has opened the mapped objects in the specified address range with write permission, unless MAP_PRIVATE was specified in the original mapping, regardless of whether the file descriptors used to map the objects have since been closed.

The implementation shall require that addr be a multiple of the page size as returned by sysconf().

The behavior of this function is unspecified if the mapping was not established by a call to mmap().

When mprotect() fails for reasons other than [EINVAL], the protections on some of the pages in the range [addr,addr+len) may have been changed.

RETURN VALUE

Upon successful completion, mprotect() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The mprotect() function shall fail if:

EACCES
The prot argument specifies a protection that violates the access permission the process has to the underlying memory object.
EAGAIN
The prot argument specifies PROT_WRITE over a MAP_PRIVATE mapping and there are insufficient memory resources to reserve for locking the private page.
EINVAL
The addr argument is not a multiple of the page size as returned by sysconf().
ENOMEM
Addresses in the range [addr,addr+len) are invalid for the address space of a process, or specify one or more pages which are not mapped.
ENOMEM
The prot argument specifies PROT_WRITE on a MAP_PRIVATE mapping, and it would require more space than the system is able to supply for locking the private pages, if required.
ENOTSUP
The implementation does not support the combination of accesses requested in the prot argument.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The [EINVAL] error above is marked EX because it is defined as an optional error in the POSIX Realtime Extension.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mmap() , sysconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


semop(3p)

SEMOP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

semop - XSI semaphore operations

SYNOPSIS

#include <sys/sem.h>

int semop(int semid, struct sembuf *sops, size_t nsops);

DESCRIPTION

The semop() function operates on XSI semaphores (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.15, Semaphore). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime .

The semop() function shall perform atomically a user-defined array of semaphore operations on the set of semaphores associated with the semaphore identifier specified by the argument semid.

The argument sops is a pointer to a user-defined array of semaphore operation structures. The implementation shall not modify elements of this array unless the application uses implementation-defined extensions.

The argument nsops is the number of such structures in the array.

Each structure, sembuf, includes the following members:
Member Type | Member Name | Description
short | sem_num | Semaphore number.
short | sem_op | Semaphore operation.
short | sem_flg | Operation flags.

Each semaphore operation specified by sem_op is performed on the corresponding semaphore specified by semid and sem_num.

The variable sem_op specifies one of three semaphore operations:

1.
If sem_op is a negative integer and the calling process has alter permission, one of the following shall occur:
*
If semval(see <sys/sem.h>) is greater than or equal to the absolute value of sem_op, the absolute value of sem_op is subtracted from semval. Also, if (sem_flg &SEM_UNDO) is non-zero, the absolute value of sem_op shall be added to the calling process' semadj value for the specified semaphore.

*
If semval is less than the absolute value of sem_op and (sem_flg &IPC_NOWAIT) is non-zero, semop() shall return immediately.

*
If semval is less than the absolute value of sem_op and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semncnt associated with the specified semaphore and suspend execution of the calling thread until one of the following conditions occurs:
*
The value of semval becomes greater than or equal to the absolute value of sem_op. When this occurs, the value of semncnt associated with the specified semaphore shall be decremented, the absolute value of sem_op shall be subtracted from semval and, if (sem_flg &SEM_UNDO) is non-zero, the absolute value of sem_op shall be added to the calling process' semadj value for the specified semaphore.

*
The semid for which the calling thread is awaiting action is removed from the system. When this occurs, errno shall be set equal to [EIDRM] and -1 shall be returned.

*
The calling thread receives a signal that is to be caught. When this occurs, the value of semncnt associated with the specified semaphore shall be decremented, and the calling thread shall resume execution in the manner prescribed in sigaction() .

2.
If sem_op is a positive integer and the calling process has alter permission, the value of sem_op shall be added to semval and, if (sem_flg &SEM_UNDO) is non-zero, the value of sem_op shall be subtracted from the calling process' semadj value for the specified semaphore.

3.
If sem_op is 0 and the calling process has read permission, one of the following shall occur:
*
If semval is 0, semop() shall return immediately.

*
If semval is non-zero and (sem_flg &IPC_NOWAIT) is non-zero, semop() shall return immediately.

*
If semval is non-zero and (sem_flg &IPC_NOWAIT) is 0, semop() shall increment the semzcnt associated with the specified semaphore and suspend execution of the calling thread until one of the following occurs:
*
The value of semval becomes 0, at which time the value of semzcnt associated with the specified semaphore shall be decremented.

*
The semid for which the calling thread is awaiting action is removed from the system. When this occurs, errno shall be set equal to [EIDRM] and -1 shall be returned.

*
The calling thread receives a signal that is to be caught. When this occurs, the value of semzcnt associated with the specified semaphore shall be decremented, and the calling thread shall resume execution in the manner prescribed in sigaction() .

Upon successful completion, the value of sempid for each semaphore specified in the array pointed to by sops shall be set equal to the process ID of the calling process.

RETURN VALUE

Upon successful completion, semop() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The semop() function shall fail if:

E2BIG
The value of nsops is greater than the system-imposed maximum.
EACCES
Operation permission is denied to the calling process; see XSI Interprocess Communication .
EAGAIN
The operation would result in suspension of the calling process but (sem_flg &IPC_NOWAIT) is non-zero.
EFBIG
The value of sem_num is less than 0 or greater than or equal to the number of semaphores in the set associated with semid.
EIDRM
The semaphore identifier semid is removed from the system.
EINTR
The semop() function was interrupted by a signal.
EINVAL
The value of semid is not a valid semaphore identifier, or the number of individual semaphores for which the calling process requests a SEM_UNDO would exceed the system-imposed limit.
ENOSPC
The limit on the number of individual processes requesting a SEM_UNDO would be exceeded.
ERANGE
An operation would cause a semval to overflow the system-imposed limit, or an operation would cause a semadj value to overflow the system-imposed limit.

The following sections are informative.

EXAMPLES

Setting Values in Semaphores

The following example sets the values of the two semaphores associated with the semid identifier to the values contained in the sb array.

#include <sys/sem.h>
...
int semid;
struct sembuf sb[2];
int nsops = 2;
int result;

/* Adjust value of semaphore in the semaphore array semid. */
sb[0].sem_num = 0;
sb[0].sem_op = -1;
sb[0].sem_flg = SEM_UNDO | IPC_NOWAIT;
sb[1].sem_num = 1;
sb[1].sem_op =  1;
sb[1].sem_flg = 0;

result = semop(semid, sb, nsops);

Creating a Semaphore Identifier

The following example gets a unique semaphore key using the ftok() function, then gets a semaphore ID associated with that key using the semget() function (the first call also tests to make sure the semaphore exists). If the semaphore does not exist, the program creates it, as shown by the second call to semget(). In creating the semaphore for the queuing process, the program attempts to create one semaphore with read/write permission for all. It also uses the IPC_EXCL flag, which forces semget() to fail if the semaphore already exists.

After creating the semaphore, the program uses a call to semop() to initialize it to the values in the sbuf array. The number of processes that can execute concurrently without queuing is initially set to 2. The final call to semget() creates a semaphore identifier that can be used later in the program.

The final call to semop() acquires the semaphore and waits until it is free; the SEM_UNDO option releases the semaphore when the process exits, waiting until there are less than two processes running concurrently.

#include <sys/types.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <fcntl.h>
#include <limits.h>
...
key_t semkey;
int semid, pfd, fv;
struct sembuf sbuf;
char *lgn;
char filename[PATH_MAX+1];
struct stat outstat;
struct passwd *pw;
...
/* Get unique key for semaphore. */
if ((semkey = ftok("/tmp", 'a')) == (key_t) -1) {
    perror("IPC error: ftok"); exit(1);
}

/* Get semaphore ID associated with this key. */
if ((semid = semget(semkey, 0, 0)) == -1) {

    /* Semaphore does not exist - Create. */
    if ((semid = semget(semkey, 1, IPC_CREAT | IPC_EXCL | S_IRUSR |
        S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) != -1)
    {
        /* Initialize the semaphore. */
        sbuf.sem_num = 0;
        sbuf.sem_op = 2;  /* This is the number of runs without queuing. */
        sbuf.sem_flg = 0;
        if (semop(semid, &sbuf, 1) == -1) {
            perror("IPC error: semop"); exit(1);
        }
    }
    else if (errno == EEXIST) {
        if ((semid = semget(semkey, 0, 0)) == -1) {
            perror("IPC error 1: semget"); exit(1);
        }
    }
    else {
        perror("IPC error 2: semget"); exit(1);
    }
}
...
sbuf.sem_num = 0;
sbuf.sem_op = -1;
sbuf.sem_flg = SEM_UNDO;
if (semop(semid, &sbuf, 1) == -1) {
    perror("IPC Error: semop"); exit(1);
}

APPLICATION USAGE

The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

XSI Interprocess Communication , Realtime , exec() , exit() , fork() , semctl() , semget() , sem_close() , sem_destroy() , sem_getvalue() , sem_init() , sem_open() , sem_post() , sem_unlink() , sem_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/ipc.h>, <sys/sem.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventset_fill (3p)

 Continue to this page.


posix_spawnattr_setflags (3p)

 Continue to this page.


rintf (3p)

 Continue to this page.


waitpid (3p)

 Continue to this page.


rintl (3p)

 Continue to this page.


posix_fallocate(3p)

POSIX_FALLOCATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_fallocate - file space control (ADVANCED REALTIME)

SYNOPSIS

#include <fcntl.h>

int posix_fallocate(int fd, off_t offset, size_t len);

DESCRIPTION

The posix_fallocate() function shall ensure that any required storage for regular file data starting at offset and continuing for len bytes is allocated on the file system storage media. If posix_fallocate() returns successfully, subsequent writes to the specified file data shall not fail due to the lack of free space on the file system storage media.

If the offset+ len is beyond the current file size, then posix_fallocate() shall adjust the file size to offset+ len. Otherwise, the file size shall not be changed.

It is implementation-defined whether a previous posix_fadvise() call influences allocation strategy.

Space allocated via posix_fallocate() shall be freed by a successful call to creat() or open() that truncates the size of the file. Space allocated via posix_fallocate() may be freed by a successful call to ftruncate() that reduces the file size to a size smaller than offset+ len.

RETURN VALUE

Upon successful completion, posix_fallocate() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The posix_fallocate() function shall fail if:

EBADF
The fd argument is not a valid file descriptor.
EBADF
The fd argument references a file that was opened without write permission.
EFBIG
The value of offset+ len is greater than the maximum file size.
EINTR
A signal was caught during execution.
EINVAL
The len argument was zero or the offset argument was less than zero.
EIO
An I/O error occurred while reading from or writing to a file system.
ENODEV
The fd argument does not refer to a regular file.
ENOSPC
There is insufficient free space remaining on the file system storage media.
ESPIPE
The fd argument is associated with a pipe or FIFO.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The posix_fallocate() function is part of the Advisory Information option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

creat() , ftruncate() , open() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


swscanf (3p)

 Continue to this page.


pthread_spin_trylock (3p)

 Continue to this page.


mq_getattr(3p)

MQ_GETATTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_getattr - get message queue attributes (REALTIME)

SYNOPSIS

#include <mqueue.h>

int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat);

DESCRIPTION

The mq_getattr() function shall obtain status information and attributes of the message queue and the open message queue description associated with the message queue descriptor.

The mqdes argument specifies a message queue descriptor.

The results shall be returned in the mq_attr structure referenced by the mqstat argument.

Upon return, the following members shall have the values associated with the open message queue description as set when the message queue was opened and as modified by subsequent mq_setattr() calls: mq_flags.

The following attributes of the message queue shall be returned as set at message queue creation: mq_maxmsg, mq_msgsize.

Upon return, the following members within the mq_attr structure referenced by the mqstat argument shall be set to the current state of the message queue:

mq_curmsgs
The number of messages currently on the queue.

RETURN VALUE

Upon successful completion, the mq_getattr() function shall return zero. Otherwise, the function shall return -1 and set errno to indicate the error.

ERRORS

The mq_getattr() function shall fail if:

EBADF
The mqdes argument is not a valid message queue descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_open() , mq_send() , mq_setattr() , mq_timedsend() , msgctl() , msgget() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mq_receive(3p)

MQ_RECEIVE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_receive, mq_timedreceive - receive a message from a message queue (REALTIME)

SYNOPSIS

#include <mqueue.h>

ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len,
unsigned *msg_prio);

#include <mqueue.h>
#include <time.h>
ssize_t mq_timedreceive(mqd_t mqdes, char *restrict msg_ptr,
size_t msg_len, unsigned *restrict msg_prio,
const struct timespec *restrict abs_timeout);

DESCRIPTION

The mq_receive() function shall receive the oldest of the highest priority message(s) from the message queue specified by mqdes. If the size of the buffer in bytes, specified by the msg_len argument, is less than the mq_msgsize attribute of the message queue, the function shall fail and return an error. Otherwise, the selected message shall be removed from the queue and copied to the buffer pointed to by the msg_ptr argument.

If the value of msg_len is greater than {SSIZE_MAX}, the result is implementation-defined.

If the argument msg_prio is not NULL, the priority of the selected message shall be stored in the location referenced by msg_prio.

If the specified message queue is empty and O_NONBLOCK is not set in the message queue description associated with mqdes, mq_receive() shall block until a message is enqueued on the message queue or until mq_receive() is interrupted by a signal. If more than one thread is waiting to receive a message when a message arrives at an empty queue and the Priority Scheduling option is supported, then the thread of highest priority that has been waiting the longest shall be selected to receive the message. Otherwise, it is unspecified which waiting thread receives the message. If the specified message queue is empty and O_NONBLOCK is set in the message queue description associated with mqdes, no message shall be removed from the queue, and mq_receive() shall return an error.

The mq_timedreceive() function shall receive the oldest of the highest priority messages from the message queue specified by mqdes as described for the mq_receive() function. However, if O_NONBLOCK was not specified when the message queue was opened via the mq_open() function, and no message exists on the queue to satisfy the receive, the wait for such a message shall be terminated when the specified timeout expires. If O_NONBLOCK is set, this function is equivalent to mq_receive().

The timeout expires when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call.

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock; if the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function.

The resolution of the timeout shall be the resolution of the clock on which it is based. The timespec argument is defined in the <time.h> header.

Under no circumstance shall the operation fail with a timeout if a message can be removed from the message queue immediately. The validity of the abs_timeout parameter need not be checked if a message can be removed from the message queue immediately.

RETURN VALUE

Upon successful completion, the mq_receive() and mq_timedreceive() functions shall return the length of the selected message in bytes and the message shall be removed from the queue. Otherwise, no message shall be removed from the queue, the functions shall return a value of -1, and set errno to indicate the error.

ERRORS

The mq_receive() and mq_timedreceive() functions shall fail if:

EAGAIN
O_NONBLOCK was set in the message description associated with mqdes, and the specified message queue is empty.
EBADF
The mqdes argument is not a valid message queue descriptor open for reading.
EMSGSIZE
The specified message buffer size, msg_len, is less than the message size attribute of the message queue.
EINTR
The mq_receive() or mq_timedreceive() operation was interrupted by a signal.
EINVAL
The process or thread would have blocked, and the abs_timeout parameter specified a nanoseconds field value less than zero or greater than or equal to 1000 million.
ETIMEDOUT
The O_NONBLOCK flag was not set when the message queue was opened, but no message arrived on the queue before the specified timeout expired.

The mq_receive() and mq_timedreceive() functions may fail if:

EBADMSG
The implementation has detected a data corruption problem with the message.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_open() , mq_send() , mq_timedsend() , msgctl() , msgget() , msgrcv() , msgsnd() , time() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


catanf (3p)

 Continue to this page.


catanh(3p)

CATANH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

catanh, catanhf, catanhl - complex arc hyperbolic tangent functions

SYNOPSIS

#include <complex.h>

double complex catanh(double complex z);
float complex catanhf(float complex z);
long double complex catanhl(long double complex z);

DESCRIPTION

These functions shall compute the complex arc hyperbolic tangent of z, with branch cuts outside the interval [-1, +1] along the real axis.

RETURN VALUE

These functions shall return the complex arc hyperbolic tangent value, in the range of a strip mathematically unbounded along the real axis and in the interval [-ipi/2, +ipi/2] along the imaginary axis.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ctanh() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


catanl (3p)

 Continue to this page.


getsockname(3p)

GETSOCKNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getsockname - get the socket name

SYNOPSIS

#include <sys/socket.h>

int getsockname(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);

DESCRIPTION

The getsockname() function shall retrieve the locally-bound name of the specified socket, store this address in the sockaddr structure pointed to by the address argument, and store the length of this address in the object pointed to by the address_len argument.

If the actual length of the address is greater than the length of the supplied sockaddr structure, the stored address shall be truncated.

If the socket has not been bound to a local name, the value stored in the object pointed to by address is unspecified.

RETURN VALUE

Upon successful completion, 0 shall be returned, the address argument shall point to the address of the socket, and the address_len argument shall point to the length of the address. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The getsockname() function shall fail if:

EBADF
The socket argument is not a valid file descriptor.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The operation is not supported for this socket's protocol.

The getsockname() function may fail if:

EINVAL
The socket has been shut down.
ENOBUFS
Insufficient resources were available in the system to complete the function.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

accept() , bind() , getpeername() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iconv_close(3p)

ICONV_CLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iconv_close - codeset conversion deallocation function

SYNOPSIS

#include <iconv.h>

int iconv_close(iconv_t cd);

DESCRIPTION

The iconv_close() function shall deallocate the conversion descriptor cd and all other associated resources allocated by iconv_open().

If a file descriptor is used to implement the type iconv_t, that file descriptor shall be closed.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The iconv_close() function may fail if:

EBADF
The conversion descriptor is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iconv() , iconv_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <iconv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


log10(3p)

LOG10

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

log10, log10f, log10l - base 10 logarithm function

SYNOPSIS

#include <math.h>

double log10(double x);
float log10f(float x);
long double log10l(long double x);

DESCRIPTION

These functions shall compute the base 10 logarithm of their argument x, log_10(x).

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the base 10 logarithm of x.

If x is ±0, a pole error shall occur and log10(), log10f(), and log10l() shall return -HUGE_VAL, -HUGE_VALF, and -HUGE_VALL, respectively.

For finite values of x that are less than 0, or if x is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is 1, +0 shall be returned.

If x is +Inf, +Inf shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The finite value of x is negative, or x is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Pole Error
The value of x is zero.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , log() , pow() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_getconcurrency(3p)

PTHREAD_GETCONCURRENCY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_getconcurrency, pthread_setconcurrency - get and set the level of concurrency

SYNOPSIS

#include <pthread.h>

int pthread_getconcurrency(void);
int pthread_setconcurrency(int new_level);

DESCRIPTION

Unbound threads in a process may or may not be required to be simultaneously active. By default, the threads implementation ensures that a sufficient number of threads are active so that the process can continue to make progress. While this conserves system resources, it may not produce the most effective level of concurrency.

The pthread_setconcurrency() function allows an application to inform the threads implementation of its desired concurrency level, new_level. The actual level of concurrency provided by the implementation as a result of this function call is unspecified.

If new_level is zero, it causes the implementation to maintain the concurrency level at its discretion as if pthread_setconcurrency() had never been called.

The pthread_getconcurrency() function shall return the value set by a previous call to the pthread_setconcurrency() function. If the pthread_setconcurrency() function was not previously called, this function shall return zero to indicate that the implementation is maintaining the concurrency level.

A call to pthread_setconcurrency() shall inform the implementation of its desired concurrency level. The implementation shall use this as a hint, not a requirement.

If an implementation does not support multiplexing of user threads on top of several kernel-scheduled entities, the pthread_setconcurrency() and pthread_getconcurrency() functions are provided for source code compatibility but they shall have no effect when called. To maintain the function semantics, the new_level parameter is saved when pthread_setconcurrency() is called so that a subsequent call to pthread_getconcurrency() shall return the same value.

RETURN VALUE

If successful, the pthread_setconcurrency() function shall return zero; otherwise, an error number shall be returned to indicate the error.

The pthread_getconcurrency() function shall always return the concurrency level set by a previous call to pthread_setconcurrency(). If the pthread_setconcurrency() function has never been called, pthread_getconcurrency() shall return zero.

ERRORS

The pthread_setconcurrency() function shall fail if:

EINVAL
The value specified by new_level is negative.
EAGAIN
The value specific by new_level would cause a system resource to be exceeded.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Use of these functions changes the state of the underlying concurrency upon which the application depends. Library developers are advised to not use the pthread_getconcurrency() and pthread_setconcurrency() functions since their use may conflict with an applications use of these functions.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


alarm(3p)

ALARM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

alarm - schedule an alarm signal

SYNOPSIS

#include <unistd.h>

unsigned alarm(unsigned seconds);

DESCRIPTION

The alarm() function shall cause the system to generate a SIGALRM signal for the process after the number of realtime seconds specified by seconds have elapsed. Processor scheduling delays may prevent the process from handling the signal as soon as it is generated.

If seconds is 0, a pending alarm request, if any, is canceled.

Alarm requests are not stacked; only one SIGALRM generation can be scheduled in this manner. If the SIGALRM signal has not yet been generated, the call shall result in rescheduling the time at which the SIGALRM signal is generated.

Interactions between alarm() and any of setitimer(), ualarm(), or usleep() are unspecified.

RETURN VALUE

If there is a previous alarm() request with time remaining, alarm() shall return a non-zero value that is the number of seconds until the previous request would have generated a SIGALRM signal. Otherwise, alarm() shall return 0.

ERRORS

The alarm() function is always successful, and no return value is reserved to indicate an error.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The fork() function clears pending alarms in the child process. A new process image created by one of the exec functions inherits the time left to an alarm signal in the old process' image.

Application writers should note that the type of the argument seconds and the return value of alarm() is unsigned. That means that a Strictly Conforming POSIX System Interfaces Application cannot pass a value greater than the minimum guaranteed value for {UINT_MAX}, which the ISO C standard sets as 65535, and any application passing a larger value is restricting its portability. A different type was considered, but historical implementations, including those with a 16-bit int type, consistently use either unsigned or int.

Application writers should be aware of possible interactions when the same process uses both the alarm() and sleep() functions.

RATIONALE

Many historical implementations (including Version 7 and System V) allow an alarm to occur up to a second early. Other implementations allow alarms up to half a second or one clock tick early or do not allow them to occur early at all. The latter is considered most appropriate, since it gives the most predictable behavior, especially since the signal can always be delayed for an indefinite amount of time due to scheduling. Applications can thus choose the seconds argument as the minimum amount of time they wish to have elapse before the signal.

The term "realtime" here and elsewhere ( sleep(), times()) is intended to mean "wall clock" time as common English usage, and has nothing to do with "realtime operating systems". It is in contrast to virtual time, which could be misinterpreted if just time were used.

In some implementations, including 4.3 BSD, very large values of the seconds argument are silently rounded down to an implementation-defined maximum value. This maximum is large enough (to the order of several months) that the effect is not noticeable.

There were two possible choices for alarm generation in multi-threaded applications: generation for the calling thread or generation for the process. The first option would not have been particularly useful since the alarm state is maintained on a per-process basis and the alarm that is established by the last invocation of alarm() is the only one that would be active.

Furthermore, allowing generation of an asynchronous signal for a thread would have introduced an exception to the overall signal model. This requires a compelling reason in order to be justified.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm , exec() , fork() , getitimer() , pause() , sigaction() , sleep() , ualarm() , usleep() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


scalbln (3p)

 Continue to this page.


posix_trace_timedgetnext_event (3p)

 Continue to this page.


scalbnf (3p)

 Continue to this page.


scalbnl (3p)

 Continue to this page.


isgreater(3p)

ISGREATER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isgreater - test if x greater than y

SYNOPSIS

#include <math.h>

int isgreater(real-floating x, real-floating y);

DESCRIPTION

The isgreater() macro shall determine whether its first argument is greater than its second argument. The value of isgreater( x, y) shall be equal to (x) > (y); however, unlike (x) > (y), isgreater( x, y) shall not raise the invalid floating-point exception when x and y are unordered.

RETURN VALUE

Upon successful completion, the isgreater() macro shall return the value of (x) > (y).

If x or y is NaN, 0 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values, exactly one of the relationships (less, greater, and equal) is true. Relational operators may raise the invalid floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. This macro is a quiet (non-floating-point exception raising) version of a relational operator. It facilitates writing efficient code that accounts for NaNs without suffering the invalid floating-point exception. In the SYNOPSIS section, real-floating indicates that the argument shall be an expression of real-floating type.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isgreaterequal() , isless() , islessequal() , islessgreater() , isunordered() , the Base Definitions volume of IEEE Std 1003.1-2001 <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dbm_error (3p)

 Continue to this page.


log1p(3p)

LOG1P

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

log1p, log1pf, log1pl - compute a natural logarithm

SYNOPSIS

#include <math.h>

double log1p(double x);
float log1pf(float x);
long double log1pl(long double x);

DESCRIPTION

These functions shall compute log_e(1.0 + x).

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the natural logarithm of 1.0 + x.

If x is -1, a pole error shall occur and log1p(), log1pf(), and log1pl() shall return -HUGE_VAL, -HUGE_VALF, and -HUGE_VALL, respectively.

For finite values of x that are less than -1, or if x is -Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0, or +Inf, x shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions shall fail if:

Domain Error
The finite value of x is less than -1, or x is -Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Pole Error
The value of x is -1.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

These functions may fail if:

Range Error
The value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , log() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


log2f (3p)

 Continue to this page.


cproj(3p)

CPROJ

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cproj, cprojf, cprojl - complex projection functions

SYNOPSIS

#include <complex.h>

double complex cproj(double complex z);
float complex cprojf(float complex z);
long double complex cprojl(long double complex z);

DESCRIPTION

These functions shall compute a projection of z onto the Riemann sphere: z projects to z, except that all complex infinities (even those with one infinite part and one NaN part) project to positive infinity on the real axis. If z has an infinite part, then cproj( z) shall be equivalent to:

INFINITY + I * copysign(0.0, cimag(z))

RETURN VALUE

These functions shall return the value of the projection onto the Riemann sphere.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Two topologies are commonly used in complex mathematics: the complex plane with its continuum of infinities, and the Riemann sphere with its single infinity. The complex plane is better suited for transcendental functions, the Riemann sphere for algebraic functions. The complex types with their multiplicity of infinities provide a useful (though imperfect) model for the complex plane. The cproj() function helps model the Riemann sphere by mapping all infinities to one, and should be used just before any operation, especially comparisons, that might give spurious results for any of the other infinities. Note that a complex value with one infinite part and one NaN part is regarded as an infinity, not a NaN, because if one part is infinite, the complex value is infinite independent of the value of the other part. For the same reason, cabs() returns an infinity if its argument has an infinite part and a NaN part.

FUTURE DIRECTIONS

None.

SEE ALSO

carg() , cimag() , conj() , creal() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


log2l (3p)

 Continue to this page.


tanhf (3p)

 Continue to this page.


siginterrupt(3p)

SIGINTERRUPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

siginterrupt - allow signals to interrupt functions

SYNOPSIS

#include <signal.h>

int siginterrupt(int sig, int flag);

DESCRIPTION

The siginterrupt() function shall change the restart behavior when a function is interrupted by the specified signal. The function siginterrupt(sig, flag) has an effect as if implemented as:

int siginterrupt(int sig, int flag) {
    int ret;
    struct sigaction act;

    (void) sigaction(sig, NULL, &act);
    if (flag)
        act.sa_flags &= ~SA_RESTART;
    else
        act.sa_flags |= SA_RESTART;
    ret = sigaction(sig, &act, NULL);
    return ret;
}

RETURN VALUE

Upon successful completion, siginterrupt() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The siginterrupt() function shall fail if:

EINVAL
The sig argument is not a valid signal number.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The siginterrupt() function supports programs written to historical system interfaces. A conforming application, when being written or rewritten, should use sigaction() with the SA_RESTART flag instead of siginterrupt().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , sigaction() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tanhl (3p)

 Continue to this page.


posix_trace_attr_getlogsize(3p)

POSIX_TRACE_ATTR_GETLOGSIZE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_attr_getlogsize, posix_trace_attr_getmaxdatasize, posix_trace_attr_getmaxsystemeventsize, posix_trace_attr_getmaxusereventsize, posix_trace_attr_getstreamsize, posix_trace_attr_setlogsize, posix_trace_attr_setmaxdatasize, posix_trace_attr_setstreamsize - retrieve and set trace stream size attributes (TRACING)

SYNOPSIS

#include <sys/types.h>
#include <trace.h>

int posix_trace_attr_getlogsize(const trace_attr_t *restrict attr,
size_t *restrict logsize);

int posix_trace_attr_getmaxdatasize(const trace_attr_t *restrict attr,
size_t *restrict maxdatasize);
int posix_trace_attr_getmaxsystemeventsize(
const trace_attr_t *restrict attr,
size_t *restrict eventsize);
int posix_trace_attr_getmaxusereventsize(
const trace_attr_t *restrict attr,
size_t data_len, size_t *restrict eventsize);
int posix_trace_attr_getstreamsize(const trace_attr_t *restrict attr,
size_t *restrict streamsize);

int posix_trace_attr_setlogsize(trace_attr_t *attr,
size_t logsize);

int posix_trace_attr_setmaxdatasize(trace_attr_t *attr,
size_t maxdatasize);
int posix_trace_attr_setstreamsize(trace_attr_t *attr,
size_t streamsize);

DESCRIPTION

The posix_trace_attr_getlogsize() function shall copy the log size, in bytes, from the log-max-size attribute of the attributes object pointed to by the attr argument into the variable pointed to by the logsize argument. This log size is the maximum total of bytes that shall be allocated for system and user trace events in the trace log. The default value for the log-max-size attribute is implementation-defined.

The posix_trace_attr_setlogsize() function shall set the maximum allowed size, in bytes, in the log-max-size attribute of the attributes object pointed to by the attr argument, using the size value supplied by the logsize argument.

The trace log size shall be used if the log-full-policy attribute is set to POSIX_TRACE_LOOP or POSIX_TRACE_UNTIL_FULL. If the log-full-policy attribute is set to POSIX_TRACE_APPEND, the implementation shall ignore the log-max-size attribute.

The posix_trace_attr_getmaxdatasize() function shall copy the maximum user trace event data size, in bytes, from the max-data-size attribute of the attributes object pointed to by the attr argument into the variable pointed to by the maxdatasize argument. The default value for the max-data-size attribute is implementation-defined.

The posix_trace_attr_getmaxsystemeventsize() function shall calculate the maximum memory size, in bytes, required to store a single system trace event. This value is calculated for the trace stream attributes object pointed to by the attr argument and is returned in the variable pointed to by the eventsize argument.

The values returned as the maximum memory sizes of the user and system trace events shall be such that if the sum of the maximum memory sizes of a set of the trace events that may be recorded in a trace stream is less than or equal to the stream-min-size attribute of that trace stream, the system provides the necessary resources for recording all those trace events, without loss.

The posix_trace_attr_getmaxusereventsize() function shall calculate the maximum memory size, in bytes, required to store a single user trace event generated by a call to posix_trace_event() with a data_len parameter equal to the data_len value specified in this call. This value is calculated for the trace stream attributes object pointed to by the attr argument and is returned in the variable pointed to by the eventsize argument.

The posix_trace_attr_getstreamsize() function shall copy the stream size, in bytes, from the stream-min-size attribute of the attributes object pointed to by the attr argument into the variable pointed to by the streamsize argument.

This stream size is the current total memory size reserved for system and user trace events in the trace stream. The default value for the stream-min-size attribute is implementation-defined. The stream size refers to memory used to store trace event records. Other stream data (for example, trace attribute values) shall not be included in this size.

The posix_trace_attr_setmaxdatasize() function shall set the maximum allowed size, in bytes, in the max-data-size attribute of the attributes object pointed to by the attr argument, using the size value supplied by the maxdatasize argument. This maximum size is the maximum allowed size for the user data argument which may be passed to posix_trace_event(). The implementation shall be allowed to truncate data passed to trace_user_event which is longer than maxdatasize.

The posix_trace_attr_setstreamsize() function shall set the minimum allowed size, in bytes, in the stream-min-size attribute of the attributes object pointed to by the attr argument, using the size value supplied by the streamsize argument.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

The posix_trace_attr_getlogsize() function stores the maximum trace log allowed size in the object pointed to by logsize, if successful.

The posix_trace_attr_getmaxdatasize() function stores the maximum trace event record memory size in the object pointed to by maxdatasize, if successful.

The posix_trace_attr_getmaxsystemeventsize() function stores the maximum memory size to store a single system trace event in the object pointed to by eventsize, if successful.

The posix_trace_attr_getmaxusereventsize() function stores the maximum memory size to store a single user trace event in the object pointed to by eventsize, if successful.

The posix_trace_attr_getstreamsize() function stores the maximum trace stream allowed size in the object pointed to by streamsize, if successful.

ERRORS

These functions may fail if:

EINVAL
The value specified by one of the arguments is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_attr_init() , posix_trace_create() , posix_trace_event() , posix_trace_get_attr() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getlogin_r (3p)

 Continue to this page.


pthread_mutex_trylock (3p)

 Continue to this page.


unlink(3p)

UNLINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unlink - remove a directory entry

SYNOPSIS

#include <unistd.h>

int unlink(const char *path);

DESCRIPTION

The unlink() function shall remove a link to a file. If path names a symbolic link, unlink() shall remove the symbolic link named by path and shall not affect any file or directory named by the contents of the symbolic link. Otherwise, unlink() shall remove the link named by the pathname pointed to by path and shall decrement the link count of the file referenced by the link.

When the file's link count becomes 0 and no process has the file open, the space occupied by the file shall be freed and the file shall no longer be accessible. If one or more processes have the file open when the last link is removed, the link shall be removed before unlink() returns, but the removal of the file contents shall be postponed until all references to the file are closed.

The path argument shall not name a directory unless the process has appropriate privileges and the implementation supports using unlink() on directories.

Upon successful completion, unlink() shall mark for update the st_ctime and st_mtime fields of the parent directory. Also, if the file's link count is not 0, the st_ctime field of the file shall be marked for update.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error. If -1 is returned, the named file shall not be changed.

ERRORS

The unlink() function shall fail and shall not unlink the file if:

EACCES
Search permission is denied for a component of the path prefix, or write permission is denied on the directory containing the directory entry to be removed.
EBUSY
The file named by the path argument cannot be unlinked because it is being used by the system or another process and the implementation considers this an error.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The file named by path is a directory, and either the calling process does not have appropriate privileges, or the implementation prohibits using unlink() on directories.
EPERM or EACCES

The S_ISVTX flag is set on the directory containing the file referred to by the path argument and the caller is not the file owner, nor is the caller the directory owner, nor does the caller have appropriate privileges.

EROFS
The directory entry to be unlinked is part of a read-only file system.

The unlink() function may fail and not unlink the file if:

EBUSY
The file named by path is a named STREAM.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ETXTBSY
The entry to be unlinked is the last directory entry to a pure procedure (shared text) file that is being executed.

The following sections are informative.

EXAMPLES

Removing a Link to a File

The following example shows how to remove a link to a file named /home/cnd/mod1 by removing the entry named /modules/pass1.

#include <unistd.h>

char *path = "/modules/pass1";
int   status;
...
status = unlink(path);

Checking for an Error

The following example fragment creates a temporary password lock file named LOCKFILE, which is defined as /etc/ptmp, and gets a file descriptor for it. If the file cannot be opened for writing, unlink() is used to remove the link between the file descriptor and LOCKFILE.

#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>

#define LOCKFILE "/etc/ptmp"

int pfd;  /* Integer for file descriptor returned by open call. */
FILE *fpfd;  /* File pointer for use in putpwent(). */
...
/* Open password Lock file. If it exists, this is an error. */
if ((pfd = open(LOCKFILE, O_WRONLY| O_CREAT | O_EXCL, S_IRUSR
    | S_IWUSR | S_IRGRP | S_IROTH)) == -1)  {
    fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
    exit(1);
}

/* Lock file created; proceed with fdopen of lock file so that
   putpwent() can be used.
 */
if ((fpfd = fdopen(pfd, "w")) == NULL) {
    close(pfd);
    unlink(LOCKFILE);
    exit(1);
}

Replacing Files

The following example fragment uses unlink() to discard links to files, so that they can be replaced with new versions of the files. The first call removes the link to LOCKFILE if an error occurs. Successive calls remove the links to SAVEFILE and PASSWDFILE so that new links can be created, then removes the link to LOCKFILE when it is no longer needed.

#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>

#define LOCKFILE "/etc/ptmp"
#define PASSWDFILE "/etc/passwd"
#define SAVEFILE "/etc/opasswd"
...
/* If no change was made, assume error and leave passwd unchanged. */
if (!valid_change) {
    fprintf(stderr, "Could not change password for user %s\n", user);
    unlink(LOCKFILE);
    exit(1);
}

/* Change permissions on new password file. */
chmod(LOCKFILE, S_IRUSR | S_IRGRP | S_IROTH);

/* Remove saved password file. */
unlink(SAVEFILE);

/* Save current password file. */
link(PASSWDFILE, SAVEFILE);

/* Remove current password file. */
unlink(PASSWDFILE);

/* Save new password file as current password file. */
link(LOCKFILE,PASSWDFILE);

/* Remove lock file. */
unlink(LOCKFILE);

exit(0);

APPLICATION USAGE

Applications should use rmdir() to remove a directory.

RATIONALE

Unlinking a directory is restricted to the superuser in many historical implementations for reasons given in link() (see also rename()).

The meaning of [EBUSY] in historical implementations is "mount point busy". Since this volume of IEEE Std 1003.1-2001 does not cover the system administration concepts of mounting and unmounting, the description of the error was changed to "resource busy". (This meaning is used by some device drivers when a second process tries to open an exclusive use device.) The wording is also intended to allow implementations to refuse to remove a directory if it is the root or current working directory of any process.

FUTURE DIRECTIONS

None.

SEE ALSO

close() , link() , remove() , rmdir() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_setschedparam (3p)

 Continue to this page.


sched_setscheduler(3p)

SCHED_SETSCHEDULER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched_setscheduler - set scheduling policy and parameters (REALTIME)

SYNOPSIS

#include <sched.h>

int sched_setscheduler(pid_t pid, int policy,
const struct sched_param *param);

DESCRIPTION

The sched_setscheduler() function shall set the scheduling policy and scheduling parameters of the process specified by pid to policy and the parameters specified in the sched_param structure pointed to by param, respectively. The value of the sched_priority member in the sched_param structure shall be any integer within the inclusive priority range for the scheduling policy specified by policy. If the value of pid is negative, the behavior of the sched_setscheduler() function is unspecified.

The possible values for the policy parameter are defined in the <sched.h> header.

If a process specified by pid exists, and if the calling process has permission, the scheduling policy and scheduling parameters shall be set for the process whose process ID is equal to pid.

If pid is zero, the scheduling policy and scheduling parameters shall be set for the calling process.

The conditions under which one process has the appropriate privilege to change the scheduling parameters of another process are implementation-defined.

Implementations may require that the requesting process have permission to set its own scheduling parameters or those of another process. Additionally, implementation-defined restrictions may apply as to the appropriate privileges required to set a process' own scheduling policy, or another process' scheduling policy, to a particular value.

The sched_setscheduler() function shall be considered successful if it succeeds in setting the scheduling policy and scheduling parameters of the process specified by pid to the values specified by policy and the structure pointed to by param, respectively.

If the scheduling policy specified by policy is SCHED_SPORADIC, the value specified by the sched_ss_low_priority member of the param argument shall be any integer within the inclusive priority range for the sporadic server policy. The sched_ss_repl_period and sched_ss_init_budget members of the param argument shall represent the time parameters used by the sporadic server scheduling policy for the target process. The sched_ss_max_repl member of the param argument shall represent the maximum number of replenishments that are allowed to be pending simultaneously for the process scheduled under this scheduling policy.

The specified sched_ss_repl_period shall be greater than or equal to the specified sched_ss_init_budget for the function to succeed; if it is not, then the function shall fail.

The value of sched_ss_max_repl shall be within the inclusive range [1, {SS_REPL_MAX}] for the function to succeed; if not, the function shall fail.

If the scheduling policy specified by policy is either SCHED_FIFO or SCHED_RR, the sched_ss_low_priority, sched_ss_repl_period, and sched_ss_init_budget members of the param argument shall have no effect on the scheduling behavior.

The effect of this function on individual threads is dependent on the scheduling contention scope of the threads:

*
For threads with system scheduling contention scope, these functions shall have no effect on their scheduling.

*
For threads with process scheduling contention scope, the threads' scheduling policy and associated parameters shall not be affected. However, the scheduling of these threads with respect to threads in other processes may be dependent on the scheduling parameters of their process, which are governed using these functions.

If an implementation supports a two-level scheduling model in which library threads are multiplexed on top of several kernel-scheduled entities, then the underlying kernel-scheduled entities for the system contention scope threads shall not be affected by these functions.

The underlying kernel-scheduled entities for the process contention scope threads shall have their scheduling policy and associated scheduling parameters changed to the values specified in policy and param, respectively. Kernel-scheduled entities for use by process contention scope threads that are created after this call completes shall inherit their scheduling policy and associated scheduling parameters from the process.

This function is not atomic with respect to other threads in the process. Threads may continue to execute while this function call is in the process of changing the scheduling policy and associated scheduling parameters for the underlying kernel-scheduled entities used by the process contention scope threads.

RETURN VALUE

Upon successful completion, the function shall return the former scheduling policy of the specified process. If the sched_setscheduler() function fails to complete successfully, the policy and scheduling parameters shall remain unchanged, and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sched_setscheduler() function shall fail if:

EINVAL
The value of the policy parameter is invalid, or one or more of the parameters contained in param is outside the valid range for the specified scheduling policy.
EPERM
The requesting process does not have permission to set either or both of the scheduling parameters or the scheduling policy of the specified process.
ESRCH
No process can be found corresponding to that specified by pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sched_getparam() , sched_getscheduler() , sched_setparam() , the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ldexpf (3p)

 Continue to this page.


ldexpl (3p)

 Continue to this page.


shm_open(3p)

SHM_OPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

shm_open - open a shared memory object (REALTIME)

SYNOPSIS

#include <sys/mman.h>

int shm_open(const char *name, int oflag, mode_t mode);

DESCRIPTION

The shm_open() function shall establish a connection between a shared memory object and a file descriptor. It shall create an open file description that refers to the shared memory object and a file descriptor that refers to that open file description. The file descriptor is used by other functions to refer to that shared memory object. The name argument points to a string naming a shared memory object. It is unspecified whether the name appears in the file system and is visible to other functions that take pathnames as arguments. The name argument conforms to the construction rules for a pathname. If name begins with the slash character, then processes calling shm_open() with the same value of name refer to the same shared memory object, as long as that name has not been removed. If name does not begin with the slash character, the effect is implementation-defined. The interpretation of slash characters other than the leading slash character in name is implementation-defined.

If successful, shm_open() shall return a file descriptor for the shared memory object that is the lowest numbered file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor does not share it with any other processes. It is unspecified whether the file offset is set. The FD_CLOEXEC file descriptor flag associated with the new file descriptor is set.

The file status flags and file access modes of the open file description are according to the value of oflag. The oflag argument is the bitwise-inclusive OR of the following flags defined in the <fcntl.h> header. Applications specify exactly one of the first two values (access modes) below in the value of oflag:

O_RDONLY
Open for read access only.
O_RDWR
Open for read or write access.

Any combination of the remaining flags may be specified in the value of oflag:

O_CREAT
If the shared memory object exists, this flag has no effect, except as noted under O_EXCL below. Otherwise, the shared memory object is created; the user ID of the shared memory object shall be set to the effective user ID of the process; the group ID of the shared memory object is set to a system default group ID or to the effective group ID of the process. The permission bits of the shared memory object shall be set to the value of the mode argument except those set in the file mode creation mask of the process. When bits in mode other than the file permission bits are set, the effect is unspecified. The mode argument does not affect whether the shared memory object is opened for reading, for writing, or for both. The shared memory object has a size of zero.
O_EXCL
If O_EXCL and O_CREAT are set, shm_open() fails if the shared memory object exists. The check for the existence of the shared memory object and the creation of the object if it does not exist is atomic with respect to other processes executing shm_open() naming the same shared memory object with O_EXCL and O_CREAT set. If O_EXCL is set and O_CREAT is not set, the result is undefined.
O_TRUNC
If the shared memory object exists, and it is successfully opened O_RDWR, the object shall be truncated to zero length and the mode and owner shall be unchanged by this function call. The result of using O_TRUNC with O_RDONLY is undefined.

When a shared memory object is created, the state of the shared memory object, including all data associated with the shared memory object, persists until the shared memory object is unlinked and all other references are gone. It is unspecified whether the name and shared memory object state remain valid after a system reboot.

RETURN VALUE

Upon successful completion, the shm_open() function shall return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The shm_open() function shall fail if:

EACCES
The shared memory object exists and the permissions specified by oflag are denied, or the shared memory object does not exist and permission to create the shared memory object is denied, or O_TRUNC is specified and write permission is denied.
EEXIST
O_CREAT and O_EXCL are set and the named shared memory object already exists.
EINTR
The shm_open() operation was interrupted by a signal.
EINVAL
The shm_open() operation is not supported for the given name.
EMFILE
Too many file descriptors are currently in use by this process.
ENAMETOOLONG
The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
Too many shared memory objects are currently open in the system.
ENOENT
O_CREAT is not set and the named shared memory object does not exist.
ENOSPC
There is insufficient space for the creation of the new shared memory object.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

When the Memory Mapped Files option is supported, the normal open() call is used to obtain a descriptor to a file to be mapped according to existing practice with mmap(). When the Shared Memory Objects option is supported, the shm_open() function shall obtain a descriptor to the shared memory object to be mapped.

There is ample precedent for having a file descriptor represent several types of objects. In the POSIX.1-1990 standard, a file descriptor can represent a file, a pipe, a FIFO, a tty, or a directory. Many implementations simply have an operations vector, which is indexed by the file descriptor type and does very different operations. Note that in some cases the file descriptor passed to generic operations on file descriptors is returned by open() or creat() and in some cases returned by alternate functions, such as pipe(). The latter technique is used by shm_open().

Note that such shared memory objects can actually be implemented as mapped files. In both cases, the size can be set after the open using ftruncate(). The shm_open() function itself does not create a shared object of a specified size because this would duplicate an extant function that set the size of an object referenced by a file descriptor.

On implementations where memory objects are implemented using the existing file system, the shm_open() function may be implemented using a macro that invokes open(), and the shm_unlink() function may be implemented using a macro that invokes unlink().

For implementations without a permanent file system, the definition of the name of the memory objects is allowed not to survive a system reboot. Note that this allows systems with a permanent file system to implement memory objects as data structures internal to the implementation as well.

On implementations that choose to implement memory objects using memory directly, a shm_open() followed by an ftruncate() and close() can be used to preallocate a shared memory area and to set the size of that preallocation. This may be necessary for systems without virtual memory hardware support in order to ensure that the memory is contiguous.

The set of valid open flags to shm_open() was restricted to O_RDONLY, O_RDWR, O_CREAT, and O_TRUNC because these could be easily implemented on most memory mapping systems. This volume of IEEE Std 1003.1-2001 is silent on the results if the implementation cannot supply the requested file access because of implementation-defined reasons, including hardware ones.

The error conditions [EACCES] and [ENOTSUP] are provided to inform the application that the implementation cannot complete a request.

[EACCES] indicates for implementation-defined reasons, probably hardware-related, that the implementation cannot comply with a requested mode because it conflicts with another requested mode. An example might be that an application desires to open a memory object two times, mapping different areas with different access modes. If the implementation cannot map a single area into a process space in two places, which would be required if different access modes were required for the two areas, then the implementation may inform the application at the time of the second open.

[ENOTSUP] indicates for implementation-defined reasons, probably hardware-related, that the implementation cannot comply with a requested mode at all. An example would be that the hardware of the implementation cannot support write-only shared memory areas.

On all implementations, it may be desirable to restrict the location of the memory objects to specific file systems for performance (such as a RAM disk) or implementation-defined reasons (shared memory supported directly only on certain file systems). The shm_open() function may be used to enforce these restrictions. There are a number of methods available to the application to determine an appropriate name of the file or the location of an appropriate directory. One way is from the environment via getenv(). Another would be from a configuration file.

This volume of IEEE Std 1003.1-2001 specifies that memory objects have initial contents of zero when created. This is consistent with current behavior for both files and newly allocated memory. For those implementations that use physical memory, it would be possible that such implementations could simply use available memory and give it to the process uninitialized. This, however, is not consistent with standard behavior for the uninitialized data area, the stack, and of course, files. Finally, it is highly desirable to set the allocated memory to zero for security reasons. Thus, initializing memory objects to zero is required.

FUTURE DIRECTIONS

None.

SEE ALSO

close() , dup() , exec() , fcntl() , mmap() , shmat() , shmctl() , shmdt() , shm_unlink() , umask() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <sys/mman.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


lockf(3p)

LOCKF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lockf - record locking on files

SYNOPSIS

#include <unistd.h>

int lockf(int fildes, int function, off_t size);

DESCRIPTION

The lockf() function shall lock sections of a file with advisory-mode locks. Calls to lockf() from other threads which attempt to lock the locked file section shall either return an error value or block until the section becomes unlocked. All the locks for a process are removed when the process terminates. Record locking with lockf() shall be supported for regular files and may be supported for other files.

The fildes argument is an open file descriptor. To establish a lock with this function, the file descriptor shall be opened with write-only permission (O_WRONLY) or with read/write permission (O_RDWR).

The function argument is a control value which specifies the action to be taken. The permissible values for function are defined in <unistd.h> as follows:
Function | Description
F_ULOCK | Unlock locked sections.
F_LOCK | Lock a section for exclusive use.
F_TLOCK | Test and lock a section for exclusive use.
F_TEST | Test a section for locks by other processes.

F_TEST shall detect if a lock by another process is present on the specified section.

F_LOCK and F_TLOCK shall both lock a section of a file if the section is available.

F_ULOCK shall remove locks from a section of the file.

The size argument is the number of contiguous bytes to be locked or unlocked. The section to be locked or unlocked starts at the current offset in the file and extends forward for a positive size or backward for a negative size (the preceding bytes up to but not including the current offset). If size is 0, the section from the current offset through the largest possible file offset shall be locked (that is, from the current offset through the present or any future end-of-file). An area need not be allocated to the file to be locked because locks may exist past the end-of-file.

The sections locked with F_LOCK or F_TLOCK may, in whole or in part, contain or be contained by a previously locked section for the same process. When this occurs, or if adjacent locked sections would occur, the sections shall be combined into a single locked section. If the request would cause the number of locks to exceed a system-imposed limit, the request shall fail.

F_LOCK and F_TLOCK requests differ only by the action taken if the section is not available. F_LOCK shall block the calling thread until the section is available. F_TLOCK shall cause the function to fail if the section is already locked by another process.

File locks shall be released on first close by the locking process of any file descriptor for the file.

F_ULOCK requests may release (wholly or in part) one or more locked sections controlled by the process. Locked sections shall be unlocked starting at the current file offset through size bytes or to the end-of-file if size is (off_t)0. When all of a locked section is not released (that is, when the beginning or end of the area to be unlocked falls within a locked section), the remaining portions of that section shall remain locked by the process. Releasing the center portion of a locked section shall cause the remaining locked beginning and end portions to become two separate locked sections. If the request would cause the number of locks in the system to exceed a system-imposed limit, the request shall fail.

A potential for deadlock occurs if the threads of a process controlling a locked section are blocked by accessing another process' locked section. If the system detects that deadlock would occur, lockf() shall fail with an [EDEADLK] error.

The interaction between fcntl() and lockf() locks is unspecified.

Blocking on a section shall be interrupted by any signal.

An F_ULOCK request in which size is non-zero and the offset of the last byte of the requested section is the maximum value for an object of type off_t, when the process has an existing lock in which size is 0 and which includes the last byte of the requested section, shall be treated as a request to unlock from the start of the requested section with a size equal to 0. Otherwise, an F_ULOCK request shall attempt to unlock only the requested section.

Attempting to lock a section of a file that is associated with a buffered stream produces unspecified results.

RETURN VALUE

Upon successful completion, lockf() shall return 0. Otherwise, it shall return -1, set errno to indicate an error, and existing locks shall not be changed.

ERRORS

The lockf() function shall fail if:

EBADF
The fildes argument is not a valid open file descriptor; or function is F_LOCK or F_TLOCK and fildes is not a valid file descriptor open for writing.
EACCES or EAGAIN

The function argument is F_TLOCK or F_TEST and the section is already locked by another process.

EDEADLK
The function argument is F_LOCK and a deadlock is detected.
EINTR
A signal was caught during execution of the function.
EINVAL
The function argument is not one of F_LOCK, F_TLOCK, F_TEST, or F_ULOCK; or size plus the current file offset is less than 0.
EOVERFLOW
The offset of the first, or if size is not 0 then the last, byte in the requested section cannot be represented correctly in an object of type off_t.

The lockf() function may fail if:

EAGAIN
The function argument is F_LOCK or F_TLOCK and the file is mapped with mmap().
EDEADLK or ENOLCK

The function argument is F_LOCK, F_TLOCK, or F_ULOCK, and the request would cause the number of locks to exceed a system-imposed limit.

EOPNOTSUPP or EINVAL

The implementation does not support the locking of files of the type indicated by the fildes argument.

The following sections are informative.

EXAMPLES

Locking a Portion of a File

In the following example, a file named /home/cnd/mod1 is being modified. Other processes that use locking are prevented from changing it during this process. Only the first 10000 bytes are locked, and the lock call fails if another process has any part of this area locked already.

#include <fcntl.h>
#include <unistd.h>

int fildes;
int status;
...
fildes = open("/home/cnd/mod1", O_RDWR);
status = lockf(fildes, F_TLOCK, (off_t)10000);

APPLICATION USAGE

Record-locking should not be used in combination with the fopen(), fread(), fwrite(), and other stdio functions. Instead, the more primitive, non-buffered functions (such as open()) should be used. Unexpected results may occur in processes that do buffering in the user address space. The process may later read/write data which is/was locked. The stdio functions are the most common source of unexpected buffering.

The alarm() function may be used to provide a timeout facility in applications requiring it.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , chmod() , close() , creat() , fcntl() , fopen() , mmap() , open() , read() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strptime(3p)

STRPTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strptime - date and time conversion

SYNOPSIS

#include <time.h>

char *strptime(const char *restrict buf, const char *restrict format,
struct tm *restrict tm);

DESCRIPTION

The strptime() function shall convert the character string pointed to by buf to values which are stored in the tm structure pointed to by tm, using the format specified by format.

The format is composed of zero or more directives. Each directive is composed of one of the following: one or more white-space characters (as specified by isspace()); an ordinary character (neither '%' nor a white-space character); or a conversion specification. Each conversion specification is composed of a '%' character followed by a conversion character which specifies the replacement required. The application shall ensure that there is white-space or other non-alphanumeric characters between any two conversion specifications. The following conversion specifications are supported:

%a
The day of the week, using the locale's weekday names; either the abbreviated or full name may be specified.
%A
Equivalent to %a .
%b
The month, using the locale's month names; either the abbreviated or full name may be specified.
%B
Equivalent to %b .
%c
Replaced by the locale's appropriate date and time representation.
%C
The century number [00,99]; leading zeros are permitted but not required.
%d
The day of the month [01,31]; leading zeros are permitted but not required.
%D
The date as %m / %d / %y .
%e
Equivalent to %d .
%h
Equivalent to %b .
%H
The hour (24-hour clock) [00,23]; leading zeros are permitted but not required.
%I
The hour (12-hour clock) [01,12]; leading zeros are permitted but not required.
%j
The day number of the year [001,366]; leading zeros are permitted but not required.
%m
The month number [01,12]; leading zeros are permitted but not required.
%M
The minute [00,59]; leading zeros are permitted but not required.
%n
Any white space.
%p
The locale's equivalent of a.m or p.m.
%r
12-hour clock time using the AM/PM notation if t_fmt_ampm is not an empty string in the LC_TIME portion of the current locale; in the POSIX locale, this shall be equivalent to %I : %M : %S %p .
%R
The time as %H : %M .
%S
The seconds [00,60]; leading zeros are permitted but not required.
%t
Any white space.
%T
The time as %H : %M : %S .
%U
The week number of the year (Sunday as the first day of the week) as a decimal number [00,53]; leading zeros are permitted but not required.
%w
The weekday as a decimal number [0,6], with 0 representing Sunday; leading zeros are permitted but not required.
%W
The week number of the year (Monday as the first day of the week) as a decimal number [00,53]; leading zeros are permitted but not required.
%x
The date, using the locale's date format.
%X
The time, using the locale's time format.
%y
The year within century. When a century is not otherwise specified, values in the range [69,99] shall refer to years 1969 to 1999 inclusive, and values in the range [00,68] shall refer to years 2000 to 2068 inclusive; leading zeros shall be permitted but shall not be required.
Note:
It is expected that in a future version of IEEE Std 1003.1-2001 the default century inferred from a 2-digit year will change. (This would apply to all commands accepting a 2-digit year as input.)

%Y
The year, including the century (for example, 1988).
%%
Replaced by % .

Modified Conversion Specifiers

Some conversion specifiers can be modified by the E and O modifier characters to indicate that an alternative format or specification should be used rather than the one normally used by the unmodified conversion specifier. If the alternative format or specification does not exist in the current locale, the behavior shall be as if the unmodified conversion specification were used.

%Ec
The locale's alternative appropriate date and time representation.
%EC
The name of the base year (period) in the locale's alternative representation.
%Ex
The locale's alternative date representation.
%EX
The locale's alternative time representation.
%Ey
The offset from %EC (year only) in the locale's alternative representation.
%EY
The full alternative year representation.
%Od
The day of the month using the locale's alternative numeric symbols; leading zeros are permitted but not required.
%Oe
Equivalent to %Od .
%OH
The hour (24-hour clock) using the locale's alternative numeric symbols.
%OI
The hour (12-hour clock) using the locale's alternative numeric symbols.
%Om
The month using the locale's alternative numeric symbols.
%OM
The minutes using the locale's alternative numeric symbols.
%OS
The seconds using the locale's alternative numeric symbols.
%OU
The week number of the year (Sunday as the first day of the week) using the locale's alternative numeric symbols.
%Ow
The number of the weekday (Sunday=0) using the locale's alternative numeric symbols.
%OW
The week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols.
%Oy
The year (offset from %C ) using the locale's alternative numeric symbols.

A conversion specification composed of white-space characters is executed by scanning input up to the first character that is not white-space (which remains unscanned), or until no more characters can be scanned.

A conversion specification that is an ordinary character is executed by scanning the next character from the buffer. If the character scanned from the buffer differs from the one comprising the directive, the directive fails, and the differing and subsequent characters remain unscanned.

A series of conversion specifications composed of %n , %t , white-space characters, or any combination is executed by scanning up to the first character that is not white space (which remains unscanned), or until no more characters can be scanned.

Any other conversion specification is executed by scanning characters until a character matching the next directive is scanned, or until no more characters can be scanned. These characters, except the one matching the next directive, are then compared to the locale values associated with the conversion specifier. If a match is found, values for the appropriate tm structure members are set to values corresponding to the locale information. Case is ignored when matching items in buf such as month or weekday names. If no match is found, strptime() fails and no more characters are scanned.

RETURN VALUE

Upon successful completion, strptime() shall return a pointer to the character following the last character parsed. Otherwise, a null pointer shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Several "equivalent to" formats and the special processing of white-space characters are provided in order to ease the use of identical format strings for strftime() and strptime().

Applications should use %Y (4-digit years) in preference to %y (2-digit years).

It is unspecified whether multiple calls to strptime() using the same tm structure will update the current contents of the structure or overwrite all contents of the structure. Conforming applications should make a single call to strptime() with a format and all data needed to completely specify the date and time being converted.

RATIONALE

None.

FUTURE DIRECTIONS

The strptime() function is expected to be mandatory in the next version of this volume of IEEE Std 1003.1-2001.

SEE ALSO

scanf() , strftime() , time() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


realloc(3p)

REALLOC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

realloc - memory reallocator

SYNOPSIS

#include <stdlib.h>

void *realloc(void *ptr, size_t size);

DESCRIPTION

The realloc() function shall change the size of the memory object pointed to by ptr to the size specified by size. The contents of the object shall remain unchanged up to the lesser of the new and old sizes. If the new size of the memory object would require movement of the object, the space for the previous instantiation of the object is freed. If the new size is larger, the contents of the newly allocated portion of the object are unspecified. If size is 0 and ptr is not a null pointer, the object pointed to is freed. If the space cannot be allocated, the object shall remain unchanged.

If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.

If ptr does not match a pointer returned earlier by calloc(), malloc(), or realloc() or if the space has previously been deallocated by a call to free() or realloc(), the behavior is undefined.

The order and contiguity of storage allocated by successive calls to realloc() is unspecified. The pointer returned if the allocation succeeds shall be suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object in the space allocated (until the space is explicitly freed or reallocated). Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned shall point to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer shall be returned.

RETURN VALUE

Upon successful completion with a size not equal to 0, realloc() shall return a pointer to the (possibly moved) allocated space. If size is 0, either a null pointer or a unique pointer that can be successfully passed to free() shall be returned. If there is not enough available memory, realloc() shall return a null pointer and set errno to [ENOMEM].

ERRORS

The realloc() function shall fail if:

ENOMEM
Insufficient memory is available.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

calloc() , free() , malloc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ferror(3p)

FERROR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ferror - test error indicator on a stream

SYNOPSIS

#include <stdio.h>

int ferror(FILE *stream);

DESCRIPTION

The ferror() function shall test the error indicator for the stream pointed to by stream.

RETURN VALUE

The ferror() function shall return non-zero if and only if the error indicator is set for stream.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clearerr() , feof() , fopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getpwent(3p)

ENDPWENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

endpwent, getpwent, setpwent - user database functions

SYNOPSIS

#include <pwd.h>

void endpwent(void);
struct passwd *getpwent(void);
void setpwent(void);

DESCRIPTION

These functions shall retrieve information about users.

The getpwent() function shall return a pointer to a structure containing the broken-out fields of an entry in the user database. Each entry in the user database contains a passwd structure. When first called, getpwent() shall return a pointer to a passwd structure containing the first entry in the user database. Thereafter, it shall return a pointer to a passwd structure containing the next entry in the user database. Successive calls can be used to search the entire user database.

If an end-of-file or an error is encountered on reading, getpwent() shall return a null pointer.

An implementation that provides extended security controls may impose further implementation-defined restrictions on accessing the user database. In particular, the system may deny the existence of some or all of the user database entries associated with users other than the caller.

The setpwent() function effectively rewinds the user database to allow repeated searches.

The endpwent() function may be called to close the user database when processing is complete.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The getpwent() function shall return a null pointer on end-of-file or error.

ERRORS

The getpwent(), setpwent(), and endpwent() functions may fail if:

EIO
An I/O error has occurred.

In addition, getpwent() and setpwent() may fail if:

EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.

The return value may point to a static area which is overwritten by a subsequent call to getpwuid(), getpwnam(), or getpwent().

The following sections are informative.

EXAMPLES

Searching the User Database

The following example uses the getpwent() function to get successive entries in the user database, returning a pointer to a passwd structure that contains information about each user. The call to endpwent() closes the user database and cleans up.

#include <pwd.h>
...
struct passwd *p;
...
while ((p = getpwent ()) != NULL) {
...
}

endpwent();
...

APPLICATION USAGE

These functions are provided due to their historical usage. Applications should avoid dependencies on fields in the password database, whether the database is a single file, or where in the file system name space the database resides. Applications should use getpwuid() whenever possible because it avoids these dependencies.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

endgrent() , getlogin() , getpwnam() , getpwuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <pwd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strncasecmp (3p)

 Continue to this page.


posix_trace_attr_getstreamfullpolicy (3p)

 Continue to this page.


posix_trace_attr_setmaxdatasize (3p)

 Continue to this page.


pthread_rwlock_tryrdlock (3p)

 Continue to this page.


closedir(3p)

CLOSEDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

closedir - close a directory stream

SYNOPSIS

#include <dirent.h>

int closedir(DIR *dirp);

DESCRIPTION

The closedir() function shall close the directory stream referred to by the argument dirp. Upon return, the value of dirp may no longer point to an accessible object of the type DIR. If a file descriptor is used to implement type DIR, that file descriptor shall be closed.

RETURN VALUE

Upon successful completion, closedir() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The closedir() function may fail if:

EBADF
The dirp argument does not refer to an open directory stream.
EINTR
The closedir() function was interrupted by a signal.

The following sections are informative.

EXAMPLES

Closing a Directory Stream

The following program fragment demonstrates how the closedir() function is used.

...
    DIR *dir;
    struct dirent *dp;
...
    if ((dir = opendir (".")) == NULL) {
...
    }

    while ((dp = readdir (dir)) != NULL) {
...
    }

    closedir(dir);
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

opendir() , the Base Definitions volume of IEEE Std 1003.1-2001, <dirent.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmtmsg(3p)

FMTMSG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fmtmsg - display a message in the specified format on standard error and/or a system console

SYNOPSIS

#include <fmtmsg.h>

int fmtmsg(long classification, const char *label, int severity,
const char *text, const char *action, const char *tag);

DESCRIPTION

The fmtmsg() function shall display messages in a specified format instead of the traditional printf() function.

Based on a message's classification component, fmtmsg() shall write a formatted message either to standard error, to the console, or to both.

A formatted message consists of up to five components as defined below. The component classification is not part of a message displayed to the user, but defines the source of the message and directs the display of the formatted message.

classification
Contains the sum of identifying values constructed from the constants defined below. Any one identifier from a subclass may be used in combination with a single identifier from a different subclass. Two or more identifiers from the same subclass should not be used together, with the exception of identifiers from the display subclass. (Both display subclass identifiers may be used so that messages can be displayed to both standard error and the system console.)
Major Classifications

Identifies the source of the condition. Identifiers are: MM_HARD (hardware), MM_SOFT (software), and MM_FIRM (firmware).

Message Source Subclassifications

Identifies the type of software in which the problem is detected. Identifiers are: MM_APPL (application), MM_UTIL (utility), and MM_OPSYS (operating system).

Display Subclassifications

Indicates where the message is to be displayed. Identifiers are: MM_PRINT to display the message on the standard error stream, MM_CONSOLE to display the message on the system console. One or both identifiers may be used.

Status Subclassifications

Indicates whether the application can recover from the condition. Identifiers are: MM_RECOVER (recoverable) and MM_NRECOV (non-recoverable).

An additional identifier, MM_NULLMC, indicates that no classification component is supplied for the message.

label
Identifies the source of the message. The format is two fields separated by a colon. The first field is up to 10 bytes, the second is up to 14 bytes.
severity
Indicates the seriousness of the condition. Identifiers for the levels of severity are:
MM_HALT
Indicates that the application has encountered a severe fault and is halting. Produces the string "HALT" .
MM_ERROR
Indicates that the application has detected a fault. Produces the string "ERROR" .
MM_WARNING
Indicates a condition that is out of the ordinary, that might be a problem, and should be watched. Produces the string "WARNING" .
MM_INFO
Provides information about a condition that is not in error. Produces the string "INFO" .
MM_NOSEV
Indicates that no severity level is supplied for the message.

text
Describes the error condition that produced the message. The character string is not limited to a specific size. If the character string is empty, then the text produced is unspecified.
action
Describes the first step to be taken in the error-recovery process. The fmtmsg() function precedes the action string with the prefix: "TO FIX:" . The action string is not limited to a specific size.
tag
An identifier that references on-line documentation for the message. Suggested usage is that tag includes the label and a unique identifying number. A sample tag is "XSI:cat:146" .

The MSGVERB environment variable (for message verbosity) shall determine for fmtmsg() which message components it is to select when writing messages to standard error. The value of MSGVERB shall be a colon-separated list of optional keywords. Valid keywords are: label, severity, text, action, and tag. If MSGVERB contains a keyword for a component and the component's value is not the component's null value, fmtmsg() shall include that component in the message when writing the message to standard error. If MSGVERB does not include a keyword for a message component, that component shall not be included in the display of the message. The keywords may appear in any order. If MSGVERB is not defined, if its value is the null string, if its value is not of the correct format, or if it contains keywords other than the valid ones listed above, fmtmsg() shall select all components.

MSGVERB shall determine which components are selected for display to standard error. All message components shall be included in console messages.

RETURN VALUE

The fmtmsg() function shall return one of the following values:

MM_OK
The function succeeded.
MM_NOTOK
The function failed completely.
MM_NOMSG
The function was unable to generate a message on standard error, but otherwise succeeded.
MM_NOCON
The function was unable to generate a console message, but otherwise succeeded.

ERRORS

None.

The following sections are informative.

EXAMPLES

1.
The following example of fmtmsg():

fmtmsg(MM_PRINT, "XSI:cat", MM_ERROR, "illegal option",
"refer to cat in user's reference manual", "XSI:cat:001")

produces a complete message in the specified message format:

XSI:cat: ERROR: illegal option
TO FIX: refer to cat in user's reference manual XSI:cat:001

2.
When the environment variable MSGVERB is set as follows:

MSGVERB=severity:text:action

and Example 1 is used, fmtmsg() produces:

ERROR: illegal option
TO FIX: refer to cat in user's reference manual

APPLICATION USAGE

One or more message components may be systematically omitted from messages generated by an application by using the null value of the argument for that component.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

printf() , the Base Definitions volume of IEEE Std 1003.1-2001, <fmtmsg.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_eventset_add(3p)

POSIX_TRACE_EVENTSET_ADD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_eventset_add, posix_trace_eventset_del, posix_trace_eventset_empty, posix_trace_eventset_fill, posix_trace_eventset_ismember - manipulate trace event type sets (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_eventset_add(trace_event_id_t event_id,
trace_event_set_t *set);
int posix_trace_eventset_del(trace_event_id_t event_id,
trace_event_set_t *set);
int posix_trace_eventset_empty(trace_event_set_t *set);
int posix_trace_eventset_fill(trace_event_set_t *set, int what);
int posix_trace_eventset_ismember(trace_event_id_t event_id,
const trace_event_set_t *restrict set, int *restrict ismember);

DESCRIPTION

These primitives manipulate sets of trace event types. They operate on data objects addressable by the application, not on the current trace event filter of any trace stream.

The posix_trace_eventset_add() and posix_trace_eventset_del() functions, respectively, shall add or delete the individual trace event type specified by the value of the argument event_id to or from the trace event type set pointed to by the argument set. Adding a trace event type already in the set or deleting a trace event type not in the set shall not be considered an error.

The posix_trace_eventset_empty() function shall initialize the trace event type set pointed to by the set argument such that all trace event types defined, both system and user, shall be excluded from the set.

The posix_trace_eventset_fill() function shall initialize the trace event type set pointed to by the argument set, such that the set of trace event types defined by the argument what shall be included in the set. The value of the argument what shall consist of one of the following values, as defined in the <trace.h> header:

POSIX_TRACE_WOPID_EVENTS

All the process-independent implementation-defined system trace event types are included in the set.

POSIX_TRACE_SYSTEM_EVENTS

All the implementation-defined system trace event types are included in the set, as are those defined in IEEE Std 1003.1-2001.

POSIX_TRACE_ALL_EVENTS

All trace event types defined, both system and user, are included in the set.

Applications shall call either posix_trace_eventset_empty() or posix_trace_eventset_fill() at least once for each object of type trace_event_set_t prior to any other use of that object. If such an object is not initialized in this way, but is nonetheless supplied as an argument to any of the posix_trace_eventset_add(), posix_trace_eventset_del(), or posix_trace_eventset_ismember() functions, the results are undefined.

The posix_trace_eventset_ismember() function shall test whether the trace event type specified by the value of the argument event_id is a member of the set pointed to by the argument set. The value returned in the object pointed to by ismember argument is zero if the trace event type identifier is not a member of the set and a value different from zero if it is a member of the set.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

ERRORS

These functions may fail if:

EINVAL
The value of one of the arguments is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_set_filter() , posix_trace_trid_eventid_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


gethostbyname(3p)

GETHOSTBYADDR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

gethostbyaddr, gethostbyname - network host database functions

SYNOPSIS

#include <netdb.h>

struct hostent *gethostbyaddr(const void *addr, socklen_t len,
int type);
struct hostent *gethostbyname(const char *name);

DESCRIPTION

These functions shall retrieve information about hosts. This information is considered to be stored in a database that can be accessed sequentially or randomly. Implementation of this database is unspecified.

Note:
In many cases it is implemented by the Domain Name System, as documented in RFC 1034, RFC 1035, and RFC 1886.

Entries shall be returned in hostent structures.

The gethostbyaddr() function shall return an entry containing addresses of address family type for the host with address addr. The len argument contains the length of the address pointed to by addr. The gethostbyaddr() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The gethostbyname() function shall return an entry containing addresses of address family AF_INET for the host with name name. The gethostbyname() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The addr argument of gethostbyaddr() shall be an in_addr structure when type is AF_INET. It contains a binary format (that is, not null-terminated) address in network byte order. The gethostbyaddr() function is not guaranteed to return addresses of address families other than AF_INET, even when such addresses exist in the database.

If gethostbyaddr() returns successfully, then the h_addrtype field in the result shall be the same as the type argument that was passed to the function, and the h_addr_list field shall list a single address that is a copy of the addr argument that was passed to the function.

The name argument of gethostbyname() shall be a node name; the behavior of gethostbyname() when passed a numeric address string is unspecified. For IPv4, a numeric address string shall be in the dotted-decimal notation described in inet_addr() .

If name is not a numeric address string and is an alias for a valid host name, then gethostbyname() shall return information about the host name to which the alias refers, and name shall be included in the list of aliases returned.

RETURN VALUE

Upon successful completion, these functions shall return a pointer to a hostent structure if the requested entry was found, and a null pointer if the end of the database was reached or the requested entry was not found.

Upon unsuccessful completion, gethostbyaddr() and gethostbyname() shall set h_errno to indicate the error.

ERRORS

These functions shall fail in the following cases. The gethostbyaddr() and gethostbyname() functions shall set h_errno to the value shown in the list below. Any changes to errno are unspecified.

HOST_NOT_FOUND

No such host is known.

NO_DATA
The server recognized the request and the name, but no address is available. Another type of request to the name server for the domain might return an answer.
NO_RECOVERY

An unexpected server failure occurred which cannot be recovered.

TRY_AGAIN
A temporary and possibly transient error occurred, such as a failure of a server to respond.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The gethostbyaddr() and gethostbyname() functions may return pointers to static data, which may be overwritten by subsequent calls to any of these functions.

The getaddrinfo() and getnameinfo() functions are preferred over the gethostbyaddr() and gethostbyname() functions.

RATIONALE

None.

FUTURE DIRECTIONS

The gethostbyaddr() and gethostbyname() functions may be withdrawn in a future version.

SEE ALSO

endhostent() , endservent() , gai_strerror() , getaddrinfo() , h_errno() , inet_addr() , the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_create(3p)

PTHREAD_CREATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_create - thread creation

SYNOPSIS

#include <pthread.h>

int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void*), void *restrict arg);

DESCRIPTION

The pthread_create() function shall create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes shall be used. If the attributes specified by attr are modified later, the thread's attributes shall not be affected. Upon successful completion, pthread_create() shall store the ID of the created thread in the location referenced by thread.

The thread is created executing start_routine with arg as its sole argument. If the start_routine returns, the effect shall be as if there was an implicit call to pthread_exit() using the return value of start_routine as the exit status. Note that the thread in which main() was originally invoked differs from this. When it returns from main(), the effect shall be as if there was an implicit call to exit() using the return value of main() as the exit status.

The signal state of the new thread shall be initialized as follows:

*
The signal mask shall be inherited from the creating thread.

*
The set of signals pending for the new thread shall be empty.

The alternate stack shall not be inherited.

The floating-point environment shall be inherited from the creating thread.

If pthread_create() fails, no new thread is created and the contents of the location referenced by thread are undefined.

If _POSIX_THREAD_CPUTIME is defined, the new thread shall have a CPU-time clock accessible, and the initial value of this clock shall be set to zero.

RETURN VALUE

If successful, the pthread_create() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_create() function shall fail if:

EAGAIN
The system lacked the necessary resources to create another thread, or the system-imposed limit on the total number of threads in a process {PTHREAD_THREADS_MAX} would be exceeded.
EINVAL
The value specified by attr is invalid.
EPERM
The caller does not have appropriate permission to set the required scheduling parameters or scheduling policy.

The pthread_create() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

A suggested alternative to pthread_create() would be to define two separate operations: create and start. Some applications would find such behavior more natural. Ada, in particular, separates the "creation" of a task from its "activation".

Splitting the operation was rejected by the standard developers for many reasons:

*
The number of calls required to start a thread would increase from one to two and thus place an additional burden on applications that do not require the additional synchronization. The second call, however, could be avoided by the additional complication of a start-up state attribute.

*
An extra state would be introduced: "created but not started". This would require the standard to specify the behavior of the thread operations when the target has not yet started executing.

*
For those applications that require such behavior, it is possible to simulate the two separate steps with the facilities that are currently provided. The start_routine() can synchronize by waiting on a condition variable that is signaled by the start operation.

An Ada implementor can choose to create the thread at either of two points in the Ada program: when the task object is created, or when the task is activated (generally at a "begin"). If the first approach is adopted, the start_routine() needs to wait on a condition variable to receive the order to begin "activation". The second approach requires no such condition variable or extra synchronization. In either approach, a separate Ada task control block would need to be created when the task object is created to hold rendezvous queues, and so on.

An extension of the preceding model would be to allow the state of the thread to be modified between the create and start. This would allow the thread attributes object to be eliminated. This has been rejected because:

*
All state in the thread attributes object has to be able to be set for the thread. This would require the definition of functions to modify thread attributes. There would be no reduction in the number of function calls required to set up the thread. In fact, for an application that creates all threads using identical attributes, the number of function calls required to set up the threads would be dramatically increased. Use of a thread attributes object permits the application to make one set of attribute setting function calls. Otherwise, the set of attribute setting function calls needs to be made for each thread creation.

*
Depending on the implementation architecture, functions to set thread state would require kernel calls, or for other implementation reasons would not be able to be implemented as macros, thereby increasing the cost of thread creation.

*
The ability for applications to segregate threads by class would be lost.

Another suggested alternative uses a model similar to that for process creation, such as "thread fork". The fork semantics would provide more flexibility and the "create" function can be implemented simply by doing a thread fork followed immediately by a call to the desired "start routine" for the thread. This alternative has these problems:

*
For many implementations, the entire stack of the calling thread would need to be duplicated, since in many architectures there is no way to determine the size of the calling frame.

*
Efficiency is reduced since at least some part of the stack has to be copied, even though in most cases the thread never needs the copied context, since it merely calls the desired start routine.

FUTURE DIRECTIONS

None.

SEE ALSO

fork() , pthread_exit() , pthread_join() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutex_getprioceiling(3p)

PTHREAD_MUTEX_GETPRIOCEILING

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutex_getprioceiling, pthread_mutex_setprioceiling - get and set the priority ceiling of a mutex (REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_mutex_getprioceiling(const pthread_mutex_t *restrict mutex,
int *restrict prioceiling);
int pthread_mutex_setprioceiling(pthread_mutex_t *restrict mutex,
int prioceiling, int *restrict old_ceiling);

DESCRIPTION

The pthread_mutex_getprioceiling() function shall return the current priority ceiling of the mutex.

The pthread_mutex_setprioceiling() function shall either lock the mutex if it is unlocked, or block until it can successfully lock the mutex, then it shall change the mutex's priority ceiling and release the mutex. When the change is successful, the previous value of the priority ceiling shall be returned in old_ceiling. The process of locking the mutex need not adhere to the priority protect protocol.

If the pthread_mutex_setprioceiling() function fails, the mutex priority ceiling shall not be changed.

RETURN VALUE

If successful, the pthread_mutex_getprioceiling() and pthread_mutex_setprioceiling() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_mutex_getprioceiling() and pthread_mutex_setprioceiling() functions may fail if:

EINVAL
The priority requested by prioceiling is out of range.
EINVAL
The value specified by mutex does not refer to a currently existing mutex.
EPERM
The caller does not have the privilege to perform the operation.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_mutex_destroy() , pthread_mutex_lock() , pthread_mutex_timedlock() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


putc_unlocked (3p)

 Continue to this page.


sigaction(3p)

SIGACTION

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sigaction - examine and change a signal action

SYNOPSIS

#include <signal.h>

int sigaction(int sig, const struct sigaction *restrict act,
struct sigaction *restrict oact);

DESCRIPTION

The sigaction() function allows the calling process to examine and/or specify the action to be associated with a specific signal. The argument sig specifies the signal; acceptable values are defined in <signal.h>.

The structure sigaction, used to describe an action to be taken, is defined in the <signal.h> header to include at least the following members:
Member Type | Member Name | Description
void(*) (int) | sa_handler | Pointer to a signal-catching function or one of the macros SIG_IGN or SIG_DFL.
sigset_t | sa_mask | Additional set of signals to be blocked during execution of signal-catching function.
int | sa_flags | Special flags to affect behavior of signal.
void(*) (int, |  |
siginfo_t *, void *) | sa_sigaction | Pointer to a signal-catching function.

The storage occupied by sa_handler and sa_sigaction may overlap, and a conforming application shall not use both simultaneously.

If the argument act is not a null pointer, it points to a structure specifying the action to be associated with the specified signal. If the argument oact is not a null pointer, the action previously associated with the signal is stored in the location pointed to by the argument oact. If the argument act is a null pointer, signal handling is unchanged; thus, the call can be used to enquire about the current handling of a given signal. The SIGKILL and SIGSTOP signals shall not be added to the signal mask using this mechanism; this restriction shall be enforced by the system without causing an error to be indicated.

If the SA_SIGINFO flag (see below) is cleared in the sa_flags field of the sigaction structure, the sa_handler field identifies the action to be associated with the specified signal. If the SA_SIGINFO flag is set in the sa_flags field, and the implementation supports the Realtime Signals Extension option or the XSI Extension option, the sa_sigaction field specifies a signal-catching function. If the SA_SIGINFO bit is cleared and the sa_handler field specifies a signal-catching function, or if the SA_SIGINFO bit is set, the sa_mask field identifies a set of signals that shall be added to the signal mask of the thread before the signal-catching function is invoked. If the sa_handler field specifies a signal-catching function, the sa_mask field identifies a set of signals that shall be added to the process' signal mask before the signal-catching function is invoked.

The sa_flags field can be used to modify the behavior of the specified signal.

The following flags, defined in the <signal.h> header, can be set in sa_flags:

SA_NOCLDSTOP
Do not generate SIGCHLD when children stop or stopped children continue.

If sig is SIGCHLD and the SA_NOCLDSTOP flag is not set in sa_flags, and the implementation supports the SIGCHLD signal, then a SIGCHLD signal shall be generated for the calling process whenever any of its child processes stop and a SIGCHLD signal may be generated for the calling process whenever any of its stopped child processes are continued. If sig is SIGCHLD and the SA_NOCLDSTOP flag is set in sa_flags, then the implementation shall not generate a SIGCHLD signal in this way.

SA_ONSTACK
If set and an alternate signal stack has been declared with sigaltstack(), the signal shall be delivered to the calling process on that stack. Otherwise, the signal shall be delivered on the current stack.
SA_RESETHAND
If set, the disposition of the signal shall be reset to SIG_DFL and the SA_SIGINFO flag shall be cleared on entry to the signal handler.
Note:
SIGILL and SIGTRAP cannot be automatically reset when delivered; the system silently enforces this restriction.

Otherwise, the disposition of the signal shall not be modified on entry to the signal handler.

In addition, if this flag is set, sigaction() behaves as if the SA_NODEFER flag were also set.

SA_RESTART
This flag affects the behavior of interruptible functions; that is, those specified to fail with errno set to [EINTR]. If set, and a function specified as interruptible is interrupted by this signal, the function shall restart and shall not fail with [EINTR] unless otherwise specified. If the flag is not set, interruptible functions interrupted by this signal shall fail with errno set to [EINTR].
SA_SIGINFO
If cleared and the signal is caught, the signal-catching function shall be entered as:

void func(int signo);

where signo is the only argument to the signal-catching function. In this case, the application shall use the sa_handler member to describe the signal-catching function and the application shall not modify the sa_sigaction member.

If SA_SIGINFO is set and the signal is caught, the signal-catching function shall be entered as:

void func(int signo, siginfo_t *info, void *context);

where two additional arguments are passed to the signal-catching function. The second argument shall point to an object of type siginfo_t explaining the reason why the signal was generated; the third argument can be cast to a pointer to an object of type ucontext_t to refer to the receiving process' context that was interrupted when the signal was delivered. In this case, the application shall use the sa_sigaction member to describe the signal-catching function and the application shall not modify the sa_handler member.

The si_signo member contains the system-generated signal number.

The si_errno member may contain implementation-defined additional error information; if non-zero, it contains an error number identifying the condition that caused the signal to be generated.

The si_code member contains a code identifying the cause of the signal.

If the value of si_code is less than or equal to 0, then the signal was generated by a process and si_pid and si_uid, respectively, indicate the process ID and the real user ID of the sender. The <signal.h> header description contains information about the signal-specific contents of the elements of the siginfo_t type.

SA_NOCLDWAIT
If set, and sig equals SIGCHLD, child processes of the calling processes shall not be transformed into zombie processes when they terminate. If the calling process subsequently waits for its children, and the process has no unwaited-for children that were transformed into zombie processes, it shall block until all of its children terminate, and wait(), waitid(), and waitpid() shall fail and set errno to [ECHILD]. Otherwise, terminating child processes shall be transformed into zombie processes, unless SIGCHLD is set to SIG_IGN.
SA_NODEFER
If set and sig is caught, sig shall not be added to the process' signal mask on entry to the signal handler unless it is included in sa_mask. Otherwise, sig shall always be added to the process' signal mask on entry to the signal handler.

When a signal is caught by a signal-catching function installed by sigaction(), a new signal mask is calculated and installed for the duration of the signal-catching function (or until a call to either sigprocmask() or sigsuspend() is made). This mask is formed by taking the union of the current signal mask and the value of the sa_mask for the signal being delivered unless SA_NODEFER or SA_RESETHAND is set, and then including the signal being delivered. If and when the user's signal handler returns normally, the original signal mask is restored.

Once an action is installed for a specific signal, it shall remain installed until another action is explicitly requested (by another call to sigaction()), until the SA_RESETHAND flag causes resetting of the handler, or until one of the exec functions is called.

If the previous action for sig had been established by signal(), the values of the fields returned in the structure pointed to by oact are unspecified, and in particular oact-> sa_handler is not necessarily the same value passed to signal(). However, if a pointer to the same structure or a copy thereof is passed to a subsequent call to sigaction() via the act argument, handling of the signal shall be as if the original call to signal() were repeated.

If sigaction() fails, no new signal handler is installed.

It is unspecified whether an attempt to set the action for a signal that cannot be caught or ignored to SIG_DFL is ignored or causes an error to be returned with errno set to [EINVAL].

If SA_SIGINFO is not set in sa_flags, then the disposition of subsequent occurrences of sig when it is already pending is implementation-defined; the signal-catching function shall be invoked with a single argument. If the implementation supports the Realtime Signals Extension option, and if SA_SIGINFO is set in sa_flags, then subsequent occurrences of sig generated by sigqueue() or as a result of any signal-generating function that supports the specification of an application-defined value (when sig is already pending) shall be queued in FIFO order until delivered or accepted; the signal-catching function shall be invoked with three arguments. The application specified value is passed to the signal-catching function as the si_value member of the siginfo_t structure.

The result of the use of sigaction() and a sigwait() function concurrently within a process on the same signal is unspecified.

RETURN VALUE

Upon successful completion, sigaction() shall return 0; otherwise, -1 shall be returned, errno shall be set to indicate the error, and no new signal-catching function shall be installed.

ERRORS

The sigaction() function shall fail if:

EINVAL
The sig argument is not a valid signal number or an attempt is made to catch a signal that cannot be caught or ignore a signal that cannot be ignored.
ENOTSUP
The SA_SIGINFO bit flag is set in the sa_flags field of the sigaction structure, and the implementation does not support either the Realtime Signals Extension option, or the XSI Extension option.

The sigaction() function may fail if:

EINVAL
An attempt was made to set the action to SIG_DFL for a signal that cannot be caught or ignored (or both).

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sigaction() function supersedes the signal() function, and should be used in preference. In particular, sigaction() and signal() should not be used in the same process to control the same signal. The behavior of reentrant functions, as defined in the DESCRIPTION, is as specified by this volume of IEEE Std 1003.1-2001, regardless of invocation from a signal-catching function. This is the only intended meaning of the statement that reentrant functions may be used in signal-catching functions without restrictions. Applications must still consider all effects of such functions on such things as data structures, files, and process state. In particular, application writers need to consider the restrictions on interactions when interrupting sleep() and interactions among multiple handles for a file description. The fact that any specific function is listed as reentrant does not necessarily mean that invocation of that function from a signal-catching function is recommended.

In order to prevent errors arising from interrupting non-reentrant function calls, applications should protect calls to these functions either by blocking the appropriate signals or through the use of some programmatic semaphore (see semget() , sem_init() , sem_open() , and so on). Note in particular that even the "safe" functions may modify errno; the signal-catching function, if not executing as an independent thread, may want to save and restore its value. Naturally, the same principles apply to the reentrancy of application routines and asynchronous data access. Note that longjmp() and siglongjmp() are not in the list of reentrant functions. This is because the code executing after longjmp() and siglongjmp() can call any unsafe functions with the same danger as calling those unsafe functions directly from the signal handler. Applications that use longjmp() and siglongjmp() from within signal handlers require rigorous protection in order to be portable. Many of the other functions that are excluded from the list are traditionally implemented using either malloc() or free() functions or the standard I/O library, both of which traditionally use data structures in a non-reentrant manner. Since any combination of different functions using a common data structure can cause reentrancy problems, this volume of IEEE Std 1003.1-2001 does not define the behavior when any unsafe function is called in a signal handler that interrupts an unsafe function.

If the signal occurs other than as the result of calling abort(), kill(), or raise(), the behavior is undefined if the signal handler calls any function in the standard library other than one of the functions listed in the table above or refers to any object with static storage duration other than by assigning a value to a static storage duration variable of type volatile sig_atomic_t. Furthermore, if such a call fails, the value of errno is unspecified.

Usually, the signal is executed on the stack that was in effect before the signal was delivered. An alternate stack may be specified to receive a subset of the signals being caught.

When the signal handler returns, the receiving process resumes execution at the point it was interrupted unless the signal handler makes other arrangements. If longjmp() or _longjmp() is used to leave the signal handler, then the signal mask must be explicitly restored by the process.

This volume of IEEE Std 1003.1-2001 defines the third argument of a signal handling function when SA_SIGINFO is set as a void * instead of a ucontext_t *, but without requiring type checking. New applications should explicitly cast the third argument of the signal handling function to ucontext_t *.

The BSD optional four argument signal handling function is not supported by this volume of IEEE Std 1003.1-2001. The BSD declaration would be:

void handler(int sig, int code, struct sigcontext *scp,
    char *addr);

where sig is the signal number, code is additional information on certain signals, scp is a pointer to the sigcontext structure, and addr is additional address information. Much the same information is available in the objects pointed to by the second argument of the signal handler specified when SA_SIGINFO is set.

RATIONALE

Although this volume of IEEE Std 1003.1-2001 requires that signals that cannot be ignored shall not be added to the signal mask when a signal-catching function is entered, there is no explicit requirement that subsequent calls to sigaction() reflect this in the information returned in the oact argument. In other words, if SIGKILL is included in the sa_mask field of act, it is unspecified whether or not a subsequent call to sigaction() returns with SIGKILL included in the sa_mask field of oact.

The SA_NOCLDSTOP flag, when supplied in the act-> sa_flags parameter, allows overloading SIGCHLD with the System V semantics that each SIGCLD signal indicates a single terminated child. Most conforming applications that catch SIGCHLD are expected to install signal-catching functions that repeatedly call the waitpid() function with the WNOHANG flag set, acting on each child for which status is returned, until waitpid() returns zero. If stopped children are not of interest, the use of the SA_NOCLDSTOP flag can prevent the overhead from invoking the signal-catching routine when they stop.

Some historical implementations also define other mechanisms for stopping processes, such as the ptrace() function. These implementations usually do not generate a SIGCHLD signal when processes stop due to this mechanism; however, that is beyond the scope of this volume of IEEE Std 1003.1-2001.

This volume of IEEE Std 1003.1-2001 requires that calls to sigaction() that supply a NULL act argument succeed, even in the case of signals that cannot be caught or ignored (that is, SIGKILL or SIGSTOP). The System V signal() and BSD sigvec() functions return [EINVAL] in these cases and, in this respect, their behavior varies from sigaction().

This volume of IEEE Std 1003.1-2001 requires that sigaction() properly save and restore a signal action set up by the ISO C standard signal() function. However, there is no guarantee that the reverse is true, nor could there be given the greater amount of information conveyed by the sigaction structure. Because of this, applications should avoid using both functions for the same signal in the same process. Since this cannot always be avoided in case of general-purpose library routines, they should always be implemented with sigaction().

It was intended that the signal() function should be implementable as a library routine using sigaction().

The POSIX Realtime Extension extends the sigaction() function as specified by the POSIX.1-1990 standard to allow the application to request on a per-signal basis via an additional signal action flag that the extra parameters, including the application-defined signal value, if any, be passed to the signal-catching function.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , bsd_signal() , kill() , _longjmp() , longjmp() , raise() , semget() , sem_init() , sem_open() , sigaddset() , sigaltstack() , sigdelset() , sigemptyset() , sigfillset() , sigismember() , signal() , sigprocmask() , sigsuspend() , wait() , waitid() , waitpid() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <ucontext.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mkstemp(3p)

MKSTEMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mkstemp - make a unique filename

SYNOPSIS

#include <stdlib.h>

int mkstemp(char *template);

DESCRIPTION

The mkstemp() function shall replace the contents of the string pointed to by template by a unique filename, and return a file descriptor for the file open for reading and writing. The function thus prevents any possible race condition between testing whether the file exists and opening it for use. The string in template should look like a filename with six trailing 'X' s; mkstemp() replaces each 'X' with a character from the portable filename character set. The characters are chosen such that the resulting name does not duplicate the name of an existing file at the time of a call to mkstemp().

RETURN VALUE

Upon successful completion, mkstemp() shall return an open file descriptor. Otherwise, -1 shall be returned if no suitable file could be created.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Generating a Filename

The following example creates a file with a 10-character name beginning with the characters "file" and opens the file for reading and writing. The value returned as the value of fd is a file descriptor that identifies the file.

#include <stdlib.h>
...
char template[] = "/tmp/fileXXXXXX";
int fd;

fd = mkstemp(template);

APPLICATION USAGE

It is possible to run out of letters.

The mkstemp() function need not check to determine whether the filename part of template exceeds the maximum allowable filename length.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getpid() , open() , tmpfile() , tmpnam() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isspace(3p)

ISSPACE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isspace - test for a white-space character

SYNOPSIS

#include <ctype.h>

int isspace(int c);

DESCRIPTION

The isspace() function shall test whether c is a character of class space in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isspace() function shall return non-zero if c is a white-space character; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vswscanf (3p)

 Continue to this page.


usleep(3p)

USLEEP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

usleep - suspend execution for an interval

SYNOPSIS

#include <unistd.h>

int usleep(useconds_t useconds);

DESCRIPTION

The usleep() function shall cause the calling thread to be suspended from execution until either the number of realtime microseconds specified by the argument useconds has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested due to the scheduling of other activity by the system.

The useconds argument shall be less than one million. If the value of useconds is 0, then the call has no effect.

If a SIGALRM signal is generated for the calling process during execution of usleep() and if the SIGALRM signal is being ignored or blocked from delivery, it is unspecified whether usleep() returns when the SIGALRM signal is scheduled. If the signal is being blocked, it is also unspecified whether it remains pending after usleep() returns or it is discarded.

If a SIGALRM signal is generated for the calling process during execution of usleep(), except as a result of a prior call to alarm(), and if the SIGALRM signal is not being ignored or blocked from delivery, it is unspecified whether that signal has any effect other than causing usleep() to return.

If a signal-catching function interrupts usleep() and examines or changes either the time a SIGALRM is scheduled to be generated, the action associated with the SIGALRM signal, or whether the SIGALRM signal is blocked from delivery, the results are unspecified.

If a signal-catching function interrupts usleep() and calls siglongjmp() or longjmp() to restore an environment saved prior to the usleep() call, the action associated with the SIGALRM signal and the time at which a SIGALRM signal is scheduled to be generated are unspecified. It is also unspecified whether the SIGALRM signal is blocked, unless the process' signal mask is restored as part of the environment.

Implementations may place limitations on the granularity of timer values. For each interval timer, if the requested timer value requires a finer granularity than the implementation supports, the actual timer value shall be rounded up to the next supported value.

Interactions between usleep() and any of the following are unspecified:

nanosleep()
setitimer()
timer_create()
timer_delete()
timer_getoverrun()
timer_gettime()
timer_settime()
ualarm()
sleep()

RETURN VALUE

Upon successful completion, usleep() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The usleep() function may fail if:

EINVAL
The time interval specified one million or more microseconds.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications are recommended to use nanosleep() if the Timers option is supported, or setitimer(), timer_create(), timer_delete(), timer_getoverrun(), timer_gettime(), or timer_settime() instead of this function.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , getitimer() , nanosleep() , sigaction() , sleep() , timer_create() , timer_delete() , timer_getoverrun() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dlsym(3p)

DLSYM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dlsym - obtain the address of a symbol from a dlopen object

SYNOPSIS

#include <dlfcn.h>

void *dlsym(void *restrict handle, const char *restrict name);

DESCRIPTION

The dlsym() function shall obtain the address of a symbol defined within an object made accessible through a dlopen() call. The handle argument is the value returned from a call to dlopen() (and which has not since been released via a call to dlclose()), and name is the symbol's name as a character string.

The dlsym() function shall search for the named symbol in all objects loaded automatically as a result of loading the object referenced by handle (see dlopen() ). Load ordering is used in dlsym() operations upon the global symbol object. The symbol resolution algorithm used shall be dependency order as described in dlopen() .

The RTLD_DEFAULT and RTLD_NEXT flags are reserved for future use.

RETURN VALUE

If handle does not refer to a valid object opened by dlopen(), or if the named symbol cannot be found within any of the objects associated with handle, dlsym() shall return NULL. More detailed diagnostic information shall be available through dlerror() .

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following example shows how dlopen() and dlsym() can be used to access either function or data objects. For simplicity, error checking has been omitted.

void    *handle;
int     *iptr, (*fptr)(int);

/* open the needed object */
handle = dlopen("/usr/home/me/libfoo.so", RTLD_LOCAL | RTLD_LAZY);

/* find the address of function and data objects */
*(void **)(&fptr) = dlsym(handle, "my_function");
iptr = (int *)dlsym(handle, "my_object");

/* invoke function, passing value of integer as a parameter */
(*fptr)(*iptr);

APPLICATION USAGE

Special purpose values for handle are reserved for future use. These values and their meanings are:

RTLD_DEFAULT
The symbol lookup happens in the normal global scope; that is, a search for a symbol using this handle would find the same definition as a direct use of this symbol in the program code.
RTLD_NEXT
Specifies the next object after this one that defines name. This one refers to the object containing the invocation of dlsym(). The next object is the one found upon the application of a load order symbol resolution algorithm (see dlopen() ). The next object is either one of global scope (because it was introduced as part of the original process image or because it was added with a dlopen() operation including the RTLD_GLOBAL flag), or is an object that was included in the same dlopen() operation that loaded this one.

The RTLD_NEXT flag is useful to navigate an intentionally created hierarchy of multiply-defined symbols created through interposition. For example, if a program wished to create an implementation of malloc() that embedded some statistics gathering about memory allocations, such an implementation could use the real malloc() definition to perform the memory allocation-and itself only embed the necessary logic to implement the statistics gathering function.

RATIONALE

The ISO C standard does not require that pointers to functions can be cast back and forth to pointers to data. Indeed, the ISO C standard does not require that an object of type void * can hold a pointer to a function. Implementations supporting the XSI extension, however, do require that an object of type void * can hold a pointer to a function. The result of converting a pointer to a function into a pointer to another data type (except void *) is still undefined, however. Note that compilers conforming to the ISO C standard are required to generate a warning if a conversion from a void * pointer to a function pointer is attempted as in:

fptr = (int (*)(int))dlsym(handle, "my_function");

Due to the problem noted here, a future version may either add a new function to return function pointers, or the current interface may be deprecated in favor of two new functions: one that returns data pointers and the other that returns function pointers.

FUTURE DIRECTIONS

None.

SEE ALSO

dlclose() , dlerror() , dlopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <dlfcn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_trid_eventid_open (3p)

 Continue to this page.


isdigit(3p)

ISDIGIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isdigit - test for a decimal digit

SYNOPSIS

#include <ctype.h>

int isdigit(int c);

DESCRIPTION

The isdigit() function shall test whether c is a character of class digit in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isdigit() function shall return non-zero if c is a decimal digit; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isgraph() , islower() , isprint() , ispunct() , isspace() , isupper() , isxdigit() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getnetbyname (3p)

 Continue to this page.


setstate (3p)

 Continue to this page.


remquof (3p)

 Continue to this page.


lrand48 (3p)

 Continue to this page.


remquol (3p)

 Continue to this page.


twalk (3p)

 Continue to this page.


wcstoull (3p)

 Continue to this page.


isxdigit(3p)

ISXDIGIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isxdigit - test for a hexadecimal digit

SYNOPSIS

#include <ctype.h>

int isxdigit(int c);

DESCRIPTION

The isxdigit() function shall test whether c is a character of class xdigit in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isxdigit() function shall return non-zero if c is a hexadecimal digit; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isspace() , isupper() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


stdin(3p)

STDIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

stderr, stdin, stdout - standard I/O streams

SYNOPSIS

#include <stdio.h>

extern FILE *stderr, *stdin, *stdout;

DESCRIPTION

A file with associated buffering is called a stream and is declared to be a pointer to a defined type FILE. The fopen() function shall create certain descriptive data for a stream and return a pointer to designate the stream in all further transactions. Normally, there are three open streams with constant pointers declared in the <stdio.h> header and associated with the standard open files.

At program start-up, three streams shall be predefined and need not be opened explicitly: standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). When opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

The following symbolic values in <unistd.h> define the file descriptors that shall be associated with the C-language stdin, stdout, and stderr when the application is started:

STDIN_FILENO
Standard input value, stdin. Its value is 0.
STDOUT_FILENO
Standard output value, stdout. Its value is 1.
STDERR_FILENO
Standard error value, stderr. Its value is 2.

The stderr stream is expected to be open for reading and writing.

RETURN VALUE

None.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fclose() , feof() , ferror() , fileno() , fopen() , fread() , fseek() , getc() , gets() , popen() , printf() , putc() , puts() , read() , scanf() , setbuf() , setvbuf() , tmpfile() , ungetc() , vprintf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fseek(3p)

FSEEK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fseek, fseeko - reposition a file-position indicator in a stream

SYNOPSIS

#include <stdio.h>

int fseek(FILE *stream, long offset, int whence);

int fseeko(FILE *stream, off_t offset, int whence);

DESCRIPTION

The fseek() function shall set the file-position indicator for the stream pointed to by stream. If a read or write error occurs, the error indicator for the stream shall be set and fseek() fails.

The new position, measured in bytes from the beginning of the file, shall be obtained by adding offset to the position specified by whence. The specified point is the beginning of the file for SEEK_SET, the current value of the file-position indicator for SEEK_CUR, or end-of-file for SEEK_END.

If the stream is to be used with wide-character input/output functions, the application shall ensure that offset is either 0 or a value returned by an earlier call to ftell() on the same stream and whence is SEEK_SET.

A successful call to fseek() shall clear the end-of-file indicator for the stream and undo any effects of ungetc() and ungetwc() on the same stream. After an fseek() call, the next operation on an update stream may be either input or output.

If the most recent operation, other than ftell(), on a given stream is fflush(), the file offset in the underlying open file description shall be adjusted to reflect the location specified by fseek().

The fseek() function shall allow the file-position indicator to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

The behavior of fseek() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined.

If the stream is writable and buffered data had not been written to the underlying file, fseek() shall cause the unwritten data to be written to the file and shall mark the st_ctime and st_mtime fields of the file for update.

In a locale with state-dependent encoding, whether fseek() restores the stream's shift state is implementation-defined.

The fseeko() function shall be equivalent to the fseek() function except that the offset argument is of type off_t.

RETURN VALUE

The fseek() and fseeko() functions shall return 0 if they succeed.

Otherwise, they shall return -1 and set errno to indicate the error.

ERRORS

The fseek() and fseeko() functions shall fail if, either the stream is unbuffered or the stream's buffer needed to be flushed, and the call to fseek() or fseeko() causes an underlying lseek() or write() to be invoked, and:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor and the process would be delayed in the write operation.
EBADF
The file descriptor underlying the stream file is not open for writing or the stream's buffer needed to be flushed and the file is not open.
EFBIG
An attempt was made to write a file that exceeds the maximum file size.
EFBIG
An attempt was made to write a file that exceeds the process' file size limit.
EFBIG
The file is a regular file and an attempt was made to write at or beyond the offset maximum associated with the corresponding stream.
EINTR
The write operation was terminated due to the receipt of a signal, and no data was transferred.
EINVAL
The whence argument is invalid. The resulting file-position indicator would be set to a negative value.
EIO
A physical I/O error has occurred, or the process is a member of a background process group attempting to perform a write() to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the process group of the process is orphaned. This error may also be returned under implementation-defined conditions.
ENOSPC
There was no free space remaining on the device containing the file.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.
EOVERFLOW
For fseek(), the resulting file offset would be a value which cannot be represented correctly in an object of type long.
EOVERFLOW
For fseeko(), the resulting file offset would be a value which cannot be represented correctly in an object of type off_t.
EPIPE
An attempt was made to write to a pipe or FIFO that is not open for reading by any process; a SIGPIPE signal shall also be sent to the thread.
ESPIPE
The file descriptor underlying stream is associated with a pipe or FIFO.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , fsetpos() , ftell() , getrlimit() , lseek() , rewind() , ulimit() , ungetc() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tcflow(3p)

TCFLOW

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcflow - suspend or restart the transmission or reception of data

SYNOPSIS

#include <termios.h>

int tcflow(int fildes, int action);

DESCRIPTION

The tcflow() function shall suspend or restart transmission or reception of data on the object referred to by fildes, depending on the value of action. The fildes argument is an open file descriptor associated with a terminal.

*
If action is TCOOFF, output shall be suspended.

*
If action is TCOON, suspended output shall be restarted.

*
If action is TCIOFF, the system shall transmit a STOP character, which is intended to cause the terminal device to stop transmitting data to the system.

*
If action is TCION, the system shall transmit a START character, which is intended to cause the terminal device to start transmitting data to the system.

The default on the opening of a terminal file is that neither its input nor its output are suspended.

Attempts to use tcflow() from a process which is a member of a background process group on a fildes associated with its controlling terminal, shall cause the process group to be sent a SIGTTOU signal. If the calling process is blocking or ignoring SIGTTOU signals, the process shall be allowed to perform the operation, and no signal is sent.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcflow() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
EINVAL
The action argument is not a supported value.
ENOTTY
The file associated with fildes is not a terminal.

The tcflow() function may fail if:

EIO
The process group of the writing process is orphaned, and the writing process is not ignoring or blocking SIGTTOU.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

tcsendbreak() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mkdir(3p)

MKDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mkdir - make a directory

SYNOPSIS

#include <sys/stat.h>

int mkdir(const char *path, mode_t mode);

DESCRIPTION

The mkdir() function shall create a new directory with name path. The file permission bits of the new directory shall be initialized from mode. These file permission bits of the mode argument shall be modified by the process' file creation mask.

When bits in mode other than the file permission bits are set, the meaning of these additional bits is implementation-defined.

The directory's user ID shall be set to the process' effective user ID. The directory's group ID shall be set to the group ID of the parent directory or to the effective group ID of the process. Implementations shall provide a way to initialize the directory's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the directory's group ID to the effective group ID of the calling process.

The newly created directory shall be an empty directory.

If path names a symbolic link, mkdir() shall fail and set errno to [EEXIST].

Upon successful completion, mkdir() shall mark for update the st_atime, st_ctime, and st_mtime fields of the directory. Also, the st_ctime and st_mtime fields of the directory that contains the new entry shall be marked for update.

RETURN VALUE

Upon successful completion, mkdir() shall return 0. Otherwise, -1 shall be returned, no directory shall be created, and errno shall be set to indicate the error.

ERRORS

The mkdir() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix, or write permission is denied on the parent directory of the directory to be created.
EEXIST
The named file exists.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMLINK
The link count of the parent directory would exceed {LINK_MAX}.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of the path prefix specified by path does not name an existing directory or path is an empty string.
ENOSPC
The file system does not contain enough space to hold the contents of the new directory or to extend the parent directory of the new directory.
ENOTDIR
A component of the path prefix is not a directory.
EROFS
The parent directory resides on a read-only file system.

The mkdir() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Creating a Directory

The following example shows how to create a directory named /home/cnd/mod1, with read/write/search permissions for owner and group, and with read/search permissions for others.

#include <sys/types.h>
#include <sys/stat.h>

int status;
...
status = mkdir("/home/cnd/mod1", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

APPLICATION USAGE

None.

RATIONALE

The mkdir() function originated in 4.2 BSD and was added to System V in Release 3.0.

4.3 BSD detects [ENAMETOOLONG].

The POSIX.1-1990 standard required that the group ID of a newly created directory be set to the group ID of its parent directory or to the effective group ID of the creating process. FIPS 151-2 required that implementations provide a way to have the group ID be set to the group ID of the containing directory, but did not prohibit implementations also supporting a way to set the group ID to the effective group ID of the creating process. Conforming applications should not assume which group ID will be used. If it matters, an application can use chown() to set the group ID after the directory is created, or determine under what conditions the implementation will set the desired group ID.

FUTURE DIRECTIONS

None.

SEE ALSO

umask() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


globfree (3p)

 Continue to this page.


bcmp(3p)

BCMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bcmp - memory operations (LEGACY)

SYNOPSIS

#include <strings.h>

int bcmp(const void *s1, const void *s2, size_t n);

DESCRIPTION

The bcmp() function shall compare the first n bytes of the area pointed to by s1 with the area pointed to by s2.

RETURN VALUE

The bcmp() function shall return 0 if s1 and s2 are identical; otherwise, it shall return non-zero. Both areas are assumed to be n bytes long. If the value of n is 0, bcmp() shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The memcmp() function is preferred over this function.

For maximum portability, it is recommended to replace the function call to bcmp() as follows:

#define bcmp(b1,b2,len) memcmp((b1), (b2), (size_t)(len))

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

memcmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


drand48(3p)

DRAND48

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

drand48, erand48, jrand48, lcong48, lrand48, mrand48, nrand48, seed48, srand48 - generate uniformly distributed pseudo-random numbers

SYNOPSIS

#include <stdlib.h>

double drand48(void);
double erand48(unsigned short xsubi[3]);
long jrand48(unsigned short xsubi[3]);
void lcong48(unsigned short param[7]);
long lrand48(void);
long mrand48(void);
long nrand48(unsigned short xsubi[3]);
unsigned short *seed48(unsigned short seed16v[3]);
void srand48(long seedval);

DESCRIPTION

This family of functions shall generate pseudo-random numbers using a linear congruential algorithm and 48-bit integer arithmetic.

The drand48() and erand48() functions shall return non-negative, double-precision, floating-point values, uniformly distributed over the interval [0.0,1.0).

The lrand48() and nrand48() functions shall return non-negative, long integers, uniformly distributed over the interval [0,2**31).

The mrand48() and jrand48() functions shall return signed long integers uniformly distributed over the interval [-2**31,2**31).

The srand48(), seed48(), and lcong48() functions are initialization entry points, one of which should be invoked before either drand48(), lrand48(), or mrand48() is called. (Although it is not recommended practice, constant default initializer values shall be supplied automatically if drand48(), lrand48(), or mrand48() is called without a prior call to an initialization entry point.) The erand48(), nrand48(), and jrand48() functions do not require an initialization entry point to be called first.

All the routines work by generating a sequence of 48-bit integer values, X_i , according to the linear congruential formula: X_n+1 = (aX_n + c)_mod m n>= 0

The parameter m = 2**48; hence 48-bit integer arithmetic is performed. Unless lcong48() is invoked, the multiplier value a and the addend value c are given by: a = 5DEECE66D_16 = 273673163155_8

c = B_16 = 13_8

The value returned by any of the drand48(), erand48(), jrand48(), lrand48(), mrand48(), or nrand48() functions is computed by first generating the next 48-bit X_i in the sequence. Then the appropriate number of bits, according to the type of data item to be returned, are copied from the high-order (leftmost) bits of X_i and transformed into the returned value.

The drand48(), lrand48(), and mrand48() functions store the last 48-bit X_i generated in an internal buffer; that is why the application shall ensure that these are initialized prior to being invoked. The erand48(), nrand48(), and jrand48() functions require the calling program to provide storage for the successive X_i values in the array specified as an argument when the functions are invoked. That is why these routines do not have to be initialized; the calling program merely has to place the desired initial value of X_i into the array and pass it as an argument. By using different arguments, erand48(), nrand48(), and jrand48() allow separate modules of a large program to generate several independent streams of pseudo-random numbers; that is, the sequence of numbers in each stream shall not depend upon how many times the routines are called to generate numbers for the other streams.

The initializer function srand48() sets the high-order 32 bits of X_i to the low-order 32 bits contained in its argument. The low-order 16 bits of X_i are set to the arbitrary value 330E_16.

The initializer function seed48() sets the value of X_i to the 48-bit value specified in the argument array. The low-order 16 bits of X_i are set to the low-order 16 bits of seed16v[0]. The mid-order 16 bits of X_i are set to the low-order 16 bits of seed16v[1]. The high-order 16 bits of X_i are set to the low-order 16 bits of seed16v[2]. In addition, the previous value of X_i is copied into a 48-bit internal buffer, used only by seed48(), and a pointer to this buffer is the value returned by seed48(). This returned pointer, which can just be ignored if not needed, is useful if a program is to be restarted from a given point at some future time-use the pointer to get at and store the last X_i value, and then use this value to reinitialize via seed48() when the program is restarted.

The initializer function lcong48() allows the user to specify the initial X_i , the multiplier value a, and the addend value c. Argument array elements param[0-2] specify X_i , param[3-5] specify the multiplier a, and param[6] specifies the 16-bit addend c. After lcong48() is called, a subsequent call to either srand48() or seed48() shall restore the standard multiplier and addend values, a and c, specified above.

The drand48(), lrand48(), and mrand48() functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

As described in the DESCRIPTION above.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

rand() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setvbuf(3p)

SETVBUF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setvbuf - assign buffering to a stream

SYNOPSIS

#include <stdio.h>

int setvbuf(FILE *restrict stream, char *restrict buf, int type,
size_t size);

DESCRIPTION

The setvbuf() function may be used after the stream pointed to by stream is associated with an open file but before any other operation (other than an unsuccessful call to setvbuf()) is performed on the stream. The argument type determines how stream shall be buffered, as follows:

*
{_IOFBF} shall cause input/output to be fully buffered.

*
{_IOLBF} shall cause input/output to be line buffered.

*
{_IONBF} shall cause input/output to be unbuffered.

If buf is not a null pointer, the array it points to may be used instead of a buffer allocated by setvbuf() and the argument size specifies the size of the array; otherwise, size may determine the size of a buffer allocated by the setvbuf() function. The contents of the array at any time are unspecified.

For information about streams, see Standard I/O Streams .

RETURN VALUE

Upon successful completion, setvbuf() shall return 0. Otherwise, it shall return a non-zero value if an invalid value is given for type or if the request cannot be honored, and may set errno to indicate the error.

ERRORS

The setvbuf() function may fail if:

EBADF
The file descriptor underlying stream is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

A common source of error is allocating buffer space as an "automatic" variable in a code block, and then failing to close the stream in the same block.

With setvbuf(), allocating a buffer of size bytes does not necessarily imply that all of size bytes are used for the buffer area.

Applications should note that many implementations only provide line buffering on input from terminal devices.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Standard I/O Streams , fopen() , setbuf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


freeaddrinfo (3p)

 Continue to this page.


crealf (3p)

 Continue to this page.


creall (3p)

 Continue to this page.


optopt (3p)

 Continue to this page.


mq_setattr(3p)

MQ_SETATTR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_setattr - set message queue attributes (REALTIME)

SYNOPSIS

#include <mqueue.h>

int mq_setattr(mqd_t mqdes, const struct mq_attr *restrict mqstat,
struct mq_attr *restrict omqstat);

DESCRIPTION

The mq_setattr() function shall set attributes associated with the open message queue description referenced by the message queue descriptor specified by mqdes.

The message queue attributes corresponding to the following members defined in the mq_attr structure shall be set to the specified values upon successful completion of mq_setattr():

mq_flags
The value of this member is the bitwise-logical OR of zero or more of O_NONBLOCK and any implementation-defined flags.

The values of the mq_maxmsg, mq_msgsize, and mq_curmsgs members of the mq_attr structure shall be ignored by mq_setattr().

If omqstat is non-NULL, the mq_setattr() function shall store, in the location referenced by omqstat, the previous message queue attributes and the current queue status. These values shall be the same as would be returned by a call to mq_getattr() at that point.

RETURN VALUE

Upon successful completion, the function shall return a value of zero and the attributes of the message queue shall have been changed as specified.

Otherwise, the message queue attributes shall be unchanged, and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The mq_setattr() function shall fail if:

EBADF
The mqdes argument is not a valid message queue descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_open() , mq_send() , mq_timedsend() , msgctl() , msgget() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mq_close(3p)

MQ_CLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_close - close a message queue (REALTIME)

SYNOPSIS

#include <mqueue.h>

int mq_close(mqd_t mqdes);

DESCRIPTION

The mq_close() function shall remove the association between the message queue descriptor, mqdes, and its message queue. The results of using this message queue descriptor after successful return from this mq_close(), and until the return of this message queue descriptor from a subsequent mq_open(), are undefined.

If the process has successfully attached a notification request to the message queue via this mqdes, this attachment shall be removed, and the message queue is available for another process to attach for notification.

RETURN VALUE

Upon successful completion, the mq_close() function shall return a value of zero; otherwise, the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The mq_close() function shall fail if:

EBADF
The mqdes argument is not a valid message queue descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_open() , mq_unlink() , msgctl() , msgget() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_getsigmask(3p)

POSIX_SPAWNATTR_GETSIGMASK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawnattr_getsigmask, posix_spawnattr_setsigmask - get and set the spawn-sigmask attribute of a spawn attributes object (ADVANCED REALTIME)

SYNOPSIS

#include <signal.h>
#include <spawn.h>

int posix_spawnattr_getsigmask(const posix_spawnattr_t *restrict attr,
sigset_t *restrict sigmask);
int posix_spawnattr_setsigmask(posix_spawnattr_t *restrict attr,
const sigset_t *restrict sigmask);

DESCRIPTION

The posix_spawnattr_getsigmask() function shall obtain the value of the spawn-sigmask attribute from the attributes object referenced by attr.

The posix_spawnattr_setsigmask() function shall set the spawn-sigmask attribute in an initialized attributes object referenced by attr.

The spawn-sigmask attribute represents the signal mask in effect in the new process image of a spawn operation (if POSIX_SPAWN_SETSIGMASK is set in the spawn-flags attribute). The default value of this attribute is unspecified.

RETURN VALUE

Upon successful completion, posix_spawnattr_getsigmask() shall return zero and store the value of the spawn-sigmask attribute of attr into the object referenced by the sigmask parameter; otherwise, an error number shall be returned to indicate the error.

Upon successful completion, posix_spawnattr_setsigmask() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The posix_spawnattr_setsigmask() function may fail if:

EINVAL
The value of the attribute being set is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnattr_destroy() , posix_spawnattr_init()
, posix_spawnattr_getsigdefault() , posix_spawnattr_getflags()
, posix_spawnattr_getpgroup() , posix_spawnattr_getschedparam()
, posix_spawnattr_getschedpolicy() , posix_spawnattr_setsigdefault()
, posix_spawnattr_setflags() , posix_spawnattr_setpgroup()
, posix_spawnattr_setschedparam() , posix_spawnattr_setschedpolicy()
, posix_spawnp() , the Base Definitions volume of IEEE Std 1003.1-2001,
<signal.h>, <spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getpwuid_r (3p)

 Continue to this page.


aio_write(3p)

AIO_WRITE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio_write - asynchronous write to a file (REALTIME)

SYNOPSIS

#include <aio.h>

int aio_write(struct aiocb *aiocbp);

DESCRIPTION

The aio_write() function shall write aiocbp->aio_nbytes to the file associated with aiocbp->aio_fildes from the buffer pointed to by aiocbp->aio_buf. The function shall return when the write request has been initiated or, at a minimum, queued to the file or device.

If prioritized I/O is supported for this file, then the asynchronous operation shall be submitted at a priority equal to the scheduling priority of the process minus aiocbp->aio_reqprio.

The aiocbp argument may be used as an argument to aio_error() and aio_return() in order to determine the error status and return status, respectively, of the asynchronous operation while it is proceeding.

The aiocbp argument points to an aiocb structure. If the buffer pointed to by aiocbp->aio_buf or the control block pointed to by aiocbp becomes an illegal address prior to asynchronous I/O completion, then the behavior is undefined.

If O_APPEND is not set for the file descriptor aio_fildes, then the requested operation shall take place at the absolute position in the file as given by aio_offset, as if lseek() were called immediately prior to the operation with an offset equal to aio_offset and a whence equal to SEEK_SET. If O_APPEND is set for the file descriptor, write operations append to the file in the same order as the calls were made. After a successful call to enqueue an asynchronous I/O operation, the value of the file offset for the file is unspecified.

The aiocbp->aio_lio_opcode field shall be ignored by aio_write().

Simultaneous asynchronous operations using the same aiocbp produce undefined results.

If synchronized I/O is enabled on the file associated with aiocbp->aio_fildes, the behavior of this function shall be according to the definitions of synchronized I/O data integrity completion, and synchronized I/O file integrity completion.

For any system action that changes the process memory space while an asynchronous I/O is outstanding to the address range being changed, the result of that action is undefined.

For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with aiocbp->aio_fildes.

RETURN VALUE

The aio_write() function shall return the value zero to the calling process if the I/O operation is successfully queued; otherwise, the function shall return the value -1 and set errno to indicate the error.

ERRORS

The aio_write() function shall fail if:

EAGAIN
The requested asynchronous I/O operation was not queued due to system resource limitations.

Each of the following conditions may be detected synchronously at the time of the call to aio_write(), or asynchronously. If any of the conditions below are detected synchronously, the aio_write() function shall return -1 and set errno to the corresponding value. If any of the conditions below are detected asynchronously, the return status of the asynchronous operation shall be set to -1, and the error status of the asynchronous operation is set to the corresponding value.

EBADF
The aiocbp->aio_fildes argument is not a valid file descriptor open for writing.
EINVAL
The file offset value implied by aiocbp->aio_offset would be invalid, aiocbp->aio_reqprio is not a valid value, or aiocbp->aio_nbytes is an invalid value.

In the case that the aio_write() successfully queues the I/O operation, the return status of the asynchronous operation shall be one of the values normally returned by the write() function call. If the operation is successfully queued but is subsequently canceled or encounters an error, the error status for the asynchronous operation contains one of the values normally set by the write() function call, or one of the following:

EBADF
The aiocbp->aio_fildes argument is not a valid file descriptor open for writing.
EINVAL
The file offset value implied by aiocbp->aio_offset would be invalid.
ECANCELED
The requested I/O was canceled before the I/O completed due to an explicit aio_cancel() request.

The following condition may be detected synchronously or asynchronously:

EFBIG
The file is a regular file, aiobcp->aio_nbytes is greater than 0, and the starting offset in aiobcp->aio_offset is at or beyond the offset maximum in the open file description associated with aiocbp->aio_fildes.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The aio_write() function is part of the Asynchronous Input and Output option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_cancel() , aio_error() , aio_read() , aio_return() , close() , exec() , exit() , fork() , lio_listio() , lseek() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


memchr(3p)

MEMCHR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

memchr - find byte in memory

SYNOPSIS

#include <string.h>

void *memchr(const void *s, int c, size_t n);

DESCRIPTION

The memchr() function shall locate the first occurrence of c (converted to an unsigned char) in the initial n bytes (each interpreted as unsigned char) of the object pointed to by s.

RETURN VALUE

The memchr() function shall return a pointer to the located byte, or a null pointer if the byte does not occur in the object.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


memmove(3p)

MEMMOVE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

memmove - copy bytes in memory with overlapping areas

SYNOPSIS

#include <string.h>

void *memmove(void *s1, const void *s2, size_t n);

DESCRIPTION

The memmove() function shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n bytes from the object pointed to by s2 are first copied into a temporary array of n bytes that does not overlap the objects pointed to by s1 and s2, and then the n bytes from the temporary array are copied into the object pointed to by s1.

RETURN VALUE

The memmove() function shall return s1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutexattr_setprioceiling (3p)

 Continue to this page.


strtoumax (3p)

 Continue to this page.


pthread_attr_getdetachstate(3p)

PTHREAD_ATTR_GETDETACHSTATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_getdetachstate, pthread_attr_setdetachstate - get and set the detachstate attribute

SYNOPSIS

#include <pthread.h>

int pthread_attr_getdetachstate(const pthread_attr_t *attr,
int *detachstate);
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);

DESCRIPTION

The detachstate attribute controls whether the thread is created in a detached state. If the thread is created detached, then use of the ID of the newly created thread by the pthread_detach() or pthread_join() function is an error.

The pthread_attr_getdetachstate() and pthread_attr_setdetachstate() functions, respectively, shall get and set the detachstate attribute in the attr object.

For pthread_attr_getdetachstate(), detachstate shall be set to either PTHREAD_CREATE_DETACHED or PTHREAD_CREATE_JOINABLE.

For pthread_attr_setdetachstate(), the application shall set detachstate to either PTHREAD_CREATE_DETACHED or PTHREAD_CREATE_JOINABLE.

A value of PTHREAD_CREATE_DETACHED shall cause all threads created with attr to be in the detached state, whereas using a value of PTHREAD_CREATE_JOINABLE shall cause all threads created with attr to be in the joinable state. The default value of the detachstate attribute shall be PTHREAD_CREATE_JOINABLE.

RETURN VALUE

Upon successful completion, pthread_attr_getdetachstate() and pthread_attr_setdetachstate() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.

The pthread_attr_getdetachstate() function stores the value of the detachstate attribute in detachstate if successful.

ERRORS

The pthread_attr_setdetachstate() function shall fail if:

EINVAL
The value of detachstate was not valid

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_attr_getstackaddr() , pthread_attr_getstacksize() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


logbf (3p)

 Continue to this page.


memcmp(3p)

MEMCMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

memcmp - compare bytes in memory

SYNOPSIS

#include <string.h>

int memcmp(const void *s1, const void *s2, size_t n);

DESCRIPTION

The memcmp() function shall compare the first n bytes (each interpreted as unsigned char) of the object pointed to by s1 to the first n bytes of the object pointed to by s2.

The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the objects being compared.

RETURN VALUE

The memcmp() function shall return an integer greater than, equal to, or less than 0, if the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2, respectively.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


logbl (3p)

 Continue to this page.


posix_trace_eventid_get_name(3p)

POSIX_TRACE_EVENTID_EQUAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_eventid_equal, posix_trace_eventid_get_name, posix_trace_trid_eventid_open - manipulate the trace event type identifier (TRACING)

SYNOPSIS

#include <trace.h>

int posix_trace_eventid_equal(trace_id_t trid, trace_event_id_t event1,
trace_event_id_t event2);
int posix_trace_eventid_get_name(trace_id_t trid,
trace_event_id_t event, char *event_name);

int posix_trace_trid_eventid_open(trace_id_t trid,
const char *restrict event_name,
trace_event_id_t *restrict event);

DESCRIPTION

The posix_trace_eventid_equal() function shall compare the trace event type identifiers event1 and event2 from the same trace stream or the same trace log identified by the trid argument. If the trace event type identifiers event1 and event2 are from different trace streams, the return value shall be unspecified.

The posix_trace_eventid_get_name() function shall return, in the argument pointed to by event_name, the trace event name associated with the trace event type identifier identified by the argument event, for the trace stream or for the trace log identified by the trid argument. The name of the trace event shall have a maximum of {TRACE_EVENT_NAME_MAX} characters (which has the minimum value {_POSIX_TRACE_EVENT_NAME_MAX}). Successive calls to this function with the same trace event type identifier and the same trace stream identifier shall return the same event name.

The posix_trace_trid_eventid_open() function shall associate a user trace event name with a trace event type identifier for a given trace stream. The trace stream is identified by the trid argument, and it shall be an active trace stream. The trace event name is the string pointed to by the argument event_name. It shall have a maximum of {TRACE_EVENT_NAME_MAX} characters (which has the minimum value {_POSIX_TRACE_EVENT_NAME_MAX}). The number of user trace event type identifiers that can be defined for any given process is limited by the maximum value {TRACE_USER_EVENT_MAX}, which has the minimum value {_POSIX_TRACE_USER_EVENT_MAX}.

If the Trace Inherit option is not supported, the posix_trace_trid_eventid_open() function shall associate the user trace event name pointed to by the event_name argument with a trace event type identifier that is unique for the process being traced in the trace stream identified by the trid argument, and is returned in the variable pointed to by the event argument. If the user trace event name has already been mapped for the traced process, then the previously assigned trace event type identifier shall be returned. If the per-process user trace event name limit represented by {TRACE_USER_EVENT_MAX} has been reached, the pre-defined POSIX_TRACE_UNNAMED_USEREVENT (see Trace Option: User Trace Event ) user trace event shall be returned.

If the Trace Inherit option is supported, the posix_trace_trid_eventid_open() function shall associate the user trace event name pointed to by the event_name argument with a trace event type identifier that is unique for all the processes being traced in the trace stream identified by the trid argument, and is returned in the variable pointed to by the event argument. If the user trace event name has already been mapped for the traced processes, then the previously assigned trace event type identifier shall be returned. If the per-process user trace event name limit represented by {TRACE_USER_EVENT_MAX} has been reached, the pre-defined POSIX_TRACE_UNNAMED_USEREVENT (see Trace Option: User Trace Event ) user trace event shall be returned.

RETURN VALUE

Upon successful completion, the posix_trace_eventid_get_name() and posix_trace_trid_eventid_open() functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

The posix_trace_eventid_equal() function shall return a non-zero value if event1 and event2 are equal; otherwise, a value of zero shall be returned. No errors are defined. If either event1 or event2 are not valid trace event type identifiers for the trace stream specified by trid or if the trid is invalid, the behavior shall be unspecified.

The posix_trace_eventid_get_name() function stores the trace event name value in the object pointed to by event_name, if successful.

The posix_trace_trid_eventid_open() function stores the trace event type identifier value in the object pointed to by event, if successful.

ERRORS

The posix_trace_eventid_get_name() and posix_trace_trid_eventid_open() functions shall fail if:

EINVAL
The trid argument was not a valid trace stream identifier.

The posix_trace_trid_eventid_open() function shall fail if:

ENAMETOOLONG

The size of the name pointed to by the event_name argument was longer than the implementation-defined value {TRACE_EVENT_NAME_MAX}.

The posix_trace_eventid_get_name() function shall fail if:

EINVAL
The trace event type identifier event was not associated with any name.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Trace Option: User Trace Event , posix_trace_event() , posix_trace_getnext_event() , the Base Definitions volume of IEEE Std 1003.1-2001, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_spin_lock(3p)

PTHREAD_SPIN_LOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_spin_lock, pthread_spin_trylock - lock a spin lock object (ADVANCED REALTIME THREADS)

SYNOPSIS

#include <pthread.h>

int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_trylock(pthread_spinlock_t *lock);

DESCRIPTION

The pthread_spin_lock() function shall lock the spin lock referenced by lock. The calling thread shall acquire the lock if it is not held by another thread. Otherwise, the thread shall spin (that is, shall not return from the pthread_spin_lock() call) until the lock becomes available. The results are undefined if the calling thread holds the lock at the time the call is made. The pthread_spin_trylock() function shall lock the spin lock referenced by lock if it is not held by any thread. Otherwise, the function shall fail.

The results are undefined if any of these functions is called with an uninitialized spin lock.

RETURN VALUE

Upon successful completion, these functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by lock does not refer to an initialized spin lock object.

The pthread_spin_lock() function may fail if:

EDEADLK
The calling thread already holds the lock.

The pthread_spin_trylock() function shall fail if:

EBUSY
A thread currently holds the lock.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using this function may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

The pthread_spin_lock() and pthread_spin_trylock() functions are part of the Spin Locks option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_spin_destroy() , pthread_spin_unlock() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fscanf (3p)

 Continue to this page.


dbm_nextkey (3p)

 Continue to this page.


frexpf (3p)

 Continue to this page.


memcpy(3p)

MEMCPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

memcpy - copy bytes in memory

SYNOPSIS

#include <string.h>

void *memcpy(void *restrict s1, const void *restrict s2, size_t n);

DESCRIPTION

The memcpy() function shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The memcpy() function shall return s1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The memcpy() function does not check for the overflow of the receiving memory area.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


frexpl (3p)

 Continue to this page.


posix_trace_eventset_del (3p)

 Continue to this page.


encrypt(3p)

ENCRYPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

encrypt - encoding function (CRYPT)

SYNOPSIS

#include <unistd.h>

void encrypt(char block[64], int edflag);

DESCRIPTION

The encrypt() function shall provide access to an implementation-defined encoding algorithm. The key generated by setkey() is used to encrypt the string block with encrypt().

The block argument to encrypt() shall be an array of length 64 bytes containing only the bytes with values of 0 and 1. The array is modified in place to a similar array using the key set by setkey(). If edflag is 0, the argument is encoded. If edflag is 1, the argument may be decoded (see the APPLICATION USAGE section); if the argument is not decoded, errno shall be set to [ENOSYS].

The encrypt() function shall not change the setting of errno if successful. An application wishing to check for error situations should set errno to 0 before calling encrypt(). If errno is non-zero on return, an error has occurred.

The encrypt() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The encrypt() function shall not return a value.

ERRORS

The encrypt() function shall fail if:

ENOSYS
The functionality is not supported on this implementation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Historical implementations of the encrypt() function used a rather primitive encoding algorithm.

In some environments, decoding might not be implemented. This is related to some Government restrictions on encryption and decryption routines. Historical practice has been to ship a different version of the encryption library without the decryption feature in the routines supplied. Thus the exported version of encrypt() does encoding but not decoding.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

crypt() , setkey() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_rewind (3p)

 Continue to this page.


ccosf (3p)

 Continue to this page.


sched_setparam(3p)

SCHED_SETPARAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sched_setparam - set scheduling parameters (REALTIME)

SYNOPSIS

#include <sched.h>

int sched_setparam(pid_t pid, const struct sched_param *param);

DESCRIPTION

The sched_setparam() function shall set the scheduling parameters of the process specified by pid to the values specified by the sched_param structure pointed to by param. The value of the sched_priority member in the sched_param structure shall be any integer within the inclusive priority range for the current scheduling policy of the process specified by pid. Higher numerical values for the priority represent higher priorities. If the value of pid is negative, the behavior of the sched_setparam() function is unspecified.

If a process specified by pid exists, and if the calling process has permission, the scheduling parameters shall be set for the process whose process ID is equal to pid.

If pid is zero, the scheduling parameters shall be set for the calling process.

The conditions under which one process has permission to change the scheduling parameters of another process are implementation-defined.

Implementations may require the requesting process to have the appropriate privilege to set its own scheduling parameters or those of another process.

The target process, whether it is running or not running, shall be moved to the tail of the thread list for its priority.

If the priority of the process specified by the pid argument is set higher than that of the lowest priority running process and if the specified process is ready to run, the process specified by the pid argument shall preempt a lowest priority running process. Similarly, if the process calling sched_setparam() sets its own priority lower than that of one or more other non-empty process lists, then the process that is the head of the highest priority list shall also preempt the calling process. Thus, in either case, the originating process might not receive notification of the completion of the requested priority change until the higher priority process has executed.

If the scheduling policy of the target process is SCHED_SPORADIC, the value specified by the sched_ss_low_priority member of the param argument shall be any integer within the inclusive priority range for the sporadic server policy. The sched_ss_repl_period and sched_ss_init_budget members of the param argument shall represent the time parameters to be used by the sporadic server scheduling policy for the target process. The sched_ss_max_repl member of the param argument shall represent the maximum number of replenishments that are allowed to be pending simultaneously for the process scheduled under this scheduling policy.

The specified sched_ss_repl_period shall be greater than or equal to the specified sched_ss_init_budget for the function to succeed; if it is not, then the function shall fail.

The value of sched_ss_max_repl shall be within the inclusive range [1, {SS_REPL_MAX}] for the function to succeed; if not, the function shall fail.

If the scheduling policy of the target process is either SCHED_FIFO or SCHED_RR, the sched_ss_low_priority, sched_ss_repl_period, and sched_ss_init_budget members of the param argument shall have no effect on the scheduling behavior. If the scheduling policy of this process is not SCHED_FIFO, SCHED_RR, or SCHED_SPORADIC, the effects of these members are implementation-defined; this case includes the SCHED_OTHER policy.

If the current scheduling policy for the process specified by pid is not SCHED_FIFO, SCHED_RR, or SCHED_SPORADIC, the result is implementation-defined; this case includes the SCHED_OTHER policy.

The effect of this function on individual threads is dependent on the scheduling contention scope of the threads:

*
For threads with system scheduling contention scope, these functions shall have no effect on their scheduling.

*
For threads with process scheduling contention scope, the threads' scheduling parameters shall not be affected. However, the scheduling of these threads with respect to threads in other processes may be dependent on the scheduling parameters of their process, which are governed using these functions.

If an implementation supports a two-level scheduling model in which library threads are multiplexed on top of several kernel-scheduled entities, then the underlying kernel-scheduled entities for the system contention scope threads shall not be affected by these functions.

The underlying kernel-scheduled entities for the process contention scope threads shall have their scheduling parameters changed to the value specified in param. Kernel-scheduled entities for use by process contention scope threads that are created after this call completes shall inherit their scheduling policy and associated scheduling parameters from the process.

This function is not atomic with respect to other threads in the process. Threads may continue to execute while this function call is in the process of changing the scheduling policy for the underlying kernel-scheduled entities used by the process contention scope threads.

RETURN VALUE

If successful, the sched_setparam() function shall return zero.

If the call to sched_setparam() is unsuccessful, the priority shall remain unchanged, and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sched_setparam() function shall fail if:

EINVAL
One or more of the requested scheduling parameters is outside the range defined for the scheduling policy of the specified pid.
EPERM
The requesting process does not have permission to set the scheduling parameters for the specified process, or does not have the appropriate privilege to invoke sched_setparam().
ESRCH
No process can be found corresponding to that specified by pid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sched_getparam() , sched_getscheduler() , sched_setscheduler() , the Base Definitions volume of IEEE Std 1003.1-2001, <sched.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ccosh(3p)

CCOSH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ccosh, ccoshf, ccoshl - complex hyperbolic cosine functions

SYNOPSIS

#include <complex.h>

double complex ccosh(double complex z);
float complex ccoshf(float complex z);
long double complex ccoshl(long double complex z);

DESCRIPTION

These functions shall compute the complex hyperbolic cosine of z.

RETURN VALUE

These functions shall return the complex hyperbolic cosine value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cacosh() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ccosl (3p)

 Continue to this page.


isgraph(3p)

ISGRAPH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isgraph - test for a visible character

SYNOPSIS

#include <ctype.h>

int isgraph(int c);

DESCRIPTION

The isgraph() function shall test whether c is a character of class graph in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isgraph() function shall return non-zero if c is a character with a visible representation; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , islower() , isprint() , ispunct() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getprotobynumber (3p)

 Continue to this page.


lgamma(3p)

LGAMMA

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

lgamma, lgammaf, lgammal - log gamma function

SYNOPSIS

#include <math.h>

double lgamma(double x);
float lgammaf(float x);
long double lgammal(long double x);

extern int signgam;

DESCRIPTION

These functions shall compute

The argument x need not be a non-positive integer (Gamma(x) is defined over the reals, except the non-positive integers).

The sign of Gamma(x) is returned in the external integer signgam.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the logarithmic gamma of x.

If x is a non-positive integer, a pole error shall occur and lgamma(), lgammaf(), and lgammal() shall return +HUGE_VAL, +HUGE_VALF, and +HUGE_VALL, respectively.

If the correct value would cause overflow, a range error shall occur and lgamma(), lgammaf(), and lgammal() shall return ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (having the same sign as the correct value), respectively.

If x is NaN, a NaN shall be returned.

If x is 1 or 2, +0 shall be returned.

If x is ±Inf, +Inf shall be returned.

ERRORS

These functions shall fail if:

Pole Error
The x argument is a negative integer or zero.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exp() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wait(3p)

WAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wait, waitpid - wait for a child process to stop or terminate

SYNOPSIS

#include <sys/wait.h>

pid_t wait(int *stat_loc);
pid_t waitpid(pid_t pid, int *stat_loc, int options);

DESCRIPTION

The wait() and waitpid() functions shall obtain status information pertaining to one of the caller's child processes. Various options permit status information to be obtained for child processes that have terminated or stopped. If status information is available for two or more child processes, the order in which their status is reported is unspecified.

The wait() function shall suspend execution of the calling thread until status information for one of the terminated child processes of the calling process is available, or until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process. If more than one thread is suspended in wait() or waitpid() awaiting termination of the same process, exactly one thread shall return the process status at the time of the target process termination. If status information is available prior to the call to wait(), return shall be immediate.

The waitpid() function shall be equivalent to wait() if the pid argument is (pid_t)-1 and the options argument is 0. Otherwise, its behavior shall be modified by the values of the pid and options arguments.

The pid argument specifies a set of child processes for which status is requested. The waitpid() function shall only return the status of a child process from this set:

*
If pid is equal to (pid_t)-1, status is requested for any child process. In this respect, waitpid() is then equivalent to wait().

*
If pid is greater than 0, it specifies the process ID of a single child process for which status is requested.

*
If pid is 0, status is requested for any child process whose process group ID is equal to that of the calling process.

*
If pid is less than (pid_t)-1, status is requested for any child process whose process group ID is equal to the absolute value of pid.

The options argument is constructed from the bitwise-inclusive OR of zero or more of the following flags, defined in the <sys/wait.h> header:

WCONTINUED
The waitpid() function shall report the status of any continued child process specified by pid whose status has not been reported since it continued from a job control stop.
WNOHANG
The waitpid() function shall not suspend execution of the calling thread if status is not immediately available for one of the child processes specified by pid.
WUNTRACED
The status of any child processes specified by pid that are stopped, and whose status has not yet been reported since they stopped, shall also be reported to the requesting process.

If the calling process has SA_NOCLDWAIT set or has SIGCHLD set to SIG_IGN, and the process has no unwaited-for children that were transformed into zombie processes, the calling thread shall block until all of the children of the process containing the calling thread terminate, and wait() and waitpid() shall fail and set errno to [ECHILD].

If wait() or waitpid() return because the status of a child process is available, these functions shall return a value equal to the process ID of the child process. In this case, if the value of the argument stat_loc is not a null pointer, information shall be stored in the location pointed to by stat_loc. The value stored at the location pointed to by stat_loc shall be 0 if and only if the status returned is from a terminated child process that terminated by one of the following means:

1.
The process returned 0 from main().

2.
The process called _exit() or exit() with a status argument of 0.

3.
The process was terminated because the last thread in the process terminated.

Regardless of its value, this information may be interpreted using the following macros, which are defined in <sys/wait.h> and evaluate to integral expressions; the stat_val argument is the integer value pointed to by stat_loc.

WIFEXITED(stat_val)

Evaluates to a non-zero value if status was returned for a child process that terminated normally.

WEXITSTATUS(stat_val)

If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().

WIFSIGNALED(stat_val)

Evaluates to a non-zero value if status was returned for a child process that terminated due to the receipt of a signal that was not caught (see <signal.h>).

WTERMSIG(stat_val)

If the value of WIFSIGNALED(stat_val) is non-zero, this macro evaluates to the number of the signal that caused the termination of the child process.

WIFSTOPPED(stat_val)

Evaluates to a non-zero value if status was returned for a child process that is currently stopped.

WSTOPSIG(stat_val)

If the value of WIFSTOPPED(stat_val) is non-zero, this macro evaluates to the number of the signal that caused the child process to stop.

WIFCONTINUED(stat_val)

Evaluates to a non-zero value if status was returned for a child process that has continued from a job control stop.

It is unspecified whether the status value returned by calls to wait() or waitpid() for processes created by posix_spawn() or posix_spawnp() can indicate a WIFSTOPPED(stat_val) before subsequent calls to wait() or waitpid() indicate WIFEXITED(stat_val) as the result of an error detected before the new process image starts executing.

It is unspecified whether the status value returned by calls to wait() or waitpid() for processes created by posix_spawn() or posix_spawnp() can indicate a WIFSIGNALED(stat_val) if a signal is sent to the parent's process group after posix_spawn() or posix_spawnp() is called.

If the information pointed to by stat_loc was stored by a call to waitpid() that specified the WUNTRACED flag and did not specify the WCONTINUED flag, exactly one of the macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc), and WIFSTOPPED(*stat_loc) shall evaluate to a non-zero value.

If the information pointed to by stat_loc was stored by a call to waitpid() that specified the WUNTRACED and WCONTINUED flags, exactly one of the macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc), WIFSTOPPED(*stat_loc), and WIFCONTINUED(*stat_loc) shall evaluate to a non-zero value.

If the information pointed to by stat_loc was stored by a call to waitpid() that did not specify the WUNTRACED or WCONTINUED flags, or by a call to the wait() function, exactly one of the macros WIFEXITED(*stat_loc) and WIFSIGNALED(*stat_loc) shall evaluate to a non-zero value.

If the information pointed to by stat_loc was stored by a call to waitpid() that did not specify the WUNTRACED flag and specified the WCONTINUED flag, or by a call to the wait() function, exactly one of the macros WIFEXITED(*stat_loc), WIFSIGNALED(*stat_loc), and WIFCONTINUED(*stat_loc) shall evaluate to a non-zero value.

If _POSIX_REALTIME_SIGNALS is defined, and the implementation queues the SIGCHLD signal, then if wait() or waitpid() returns because the status of a child process is available, any pending SIGCHLD signal associated with the process ID of the child process shall be discarded. Any other pending SIGCHLD signals shall remain pending.

Otherwise, if SIGCHLD is blocked, if wait() or waitpid() return because the status of a child process is available, any pending SIGCHLD signal shall be cleared unless the status of another child process is available.

For all other conditions, it is unspecified whether child status will be available when a SIGCHLD signal is delivered.

There may be additional implementation-defined circumstances under which wait() or waitpid() report status. This shall not occur unless the calling process or one of its child processes explicitly makes use of a non-standard extension. In these cases the interpretation of the reported status is implementation-defined.

If a parent process terminates without waiting for all of its child processes to terminate, the remaining child processes shall be assigned a new parent process ID corresponding to an implementation-defined system process.

RETURN VALUE

If wait() or waitpid() returns because the status of a child process is available, these functions shall return a value equal to the process ID of the child process for which status is reported. If wait() or waitpid() returns due to the delivery of a signal to the calling process, -1 shall be returned and errno set to [EINTR]. If waitpid() was invoked with WNOHANG set in options, it has at least one child process specified by pid for which status is not available, and status is not available for any process specified by pid, 0 is returned. Otherwise, (pid_t)-1 shall be returned, and errno set to indicate the error.

ERRORS

The wait() function shall fail if:

ECHILD
The calling process has no existing unwaited-for child processes.
EINTR
The function was interrupted by a signal. The value of the location pointed to by stat_loc is undefined.

The waitpid() function shall fail if:

ECHILD
The process specified by pid does not exist or is not a child of the calling process, or the process group specified by pid does not exist or does not have any member process that is a child of the calling process.
EINTR
The function was interrupted by a signal. The value of the location pointed to by stat_loc is undefined.
EINVAL
The options argument is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

A call to the wait() or waitpid() function only returns status on an immediate child process of the calling process; that is, a child that was produced by a single fork() call (perhaps followed by an exec or other function calls) from the parent. If a child produces grandchildren by further use of fork(), none of those grandchildren nor any of their descendants affect the behavior of a wait() from the original parent process. Nothing in this volume of IEEE Std 1003.1-2001 prevents an implementation from providing extensions that permit a process to get status from a grandchild or any other process, but a process that does not use such extensions must be guaranteed to see status from only its direct children.

The waitpid() function is provided for three reasons:

1.
To support job control

2.
To permit a non-blocking version of the wait() function

3.
To permit a library routine, such as system() or pclose(), to wait for its children without interfering with other terminated children for which the process has not waited

The first two of these facilities are based on the wait3() function provided by 4.3 BSD. The function uses the options argument, which is equivalent to an argument to wait3(). The WUNTRACED flag is used only in conjunction with job control on systems supporting job control. Its name comes from 4.3 BSD and refers to the fact that there are two types of stopped processes in that implementation: processes being traced via the ptrace() debugging facility and (untraced) processes stopped by job control signals. Since ptrace() is not part of this volume of IEEE Std 1003.1-2001, only the second type is relevant. The name WUNTRACED was retained because its usage is the same, even though the name is not intuitively meaningful in this context.

The third reason for the waitpid() function is to permit independent sections of a process to spawn and wait for children without interfering with each other. For example, the following problem occurs in developing a portable shell, or command interpreter:

stream = popen("/bin/true");
(void) system("sleep 100");
(void) pclose(stream);

On all historical implementations, the final pclose() fails to reap the wait() status of the popen().

The status values are retrieved by macros, rather than given as specific bit encodings as they are in most historical implementations (and thus expected by existing programs). This was necessary to eliminate a limitation on the number of signals an implementation can support that was inherent in the traditional encodings. This volume of IEEE Std 1003.1-2001 does require that a status value of zero corresponds to a process calling _exit(0), as this is the most common encoding expected by existing programs. Some of the macro names were adopted from 4.3 BSD.

These macros syntactically operate on an arbitrary integer value. The behavior is undefined unless that value is one stored by a successful call to wait() or waitpid() in the location pointed to by the stat_loc argument. An early proposal attempted to make this clearer by specifying each argument as *stat_loc rather than stat_val. However, that did not follow the conventions of other specifications in this volume of IEEE Std 1003.1-2001 or traditional usage. It also could have implied that the argument to the macro must literally be *stat_loc; in fact, that value can be stored or passed as an argument to other functions before being interpreted by these macros.

The extension that affects wait() and waitpid() and is common in historical implementations is the ptrace() function. It is called by a child process and causes that child to stop and return a status that appears identical to the status indicated by WIFSTOPPED. The status of ptrace() children is traditionally returned regardless of the WUNTRACED flag (or by the wait() function). Most applications do not need to concern themselves with such extensions because they have control over what extensions they or their children use. However, applications, such as command interpreters, that invoke arbitrary processes may see this behavior when those arbitrary processes misuse such extensions.

Implementations that support core file creation or other implementation-defined actions on termination of some processes traditionally provide a bit in the status returned by wait() to indicate that such actions have occurred.

Allowing the wait() family of functions to discard a pending SIGCHLD signal that is associated with a successfully waited-for child process puts them into the sigwait() and sigwaitinfo() category with respect to SIGCHLD.

This definition allows implementations to treat a pending SIGCHLD signal as accepted by the process in wait(), with the same meaning of "accepted" as when that word is applied to the sigwait() family of functions.

Allowing the wait() family of functions to behave this way permits an implementation to be able to deal precisely with SIGCHLD signals.

In particular, an implementation that does accept (discard) the SIGCHLD signal can make the following guarantees regardless of the queuing depth of signals in general (the list of waitable children can hold the SIGCHLD queue):

1.
If a SIGCHLD signal handler is established via sigaction() without the SA_RESETHAND flag, SIGCHLD signals can be accurately counted; that is, exactly one SIGCHLD signal will be delivered to or accepted by the process for every child process that terminates.

2.
A single wait() issued from a SIGCHLD signal handler can be guaranteed to return immediately with status information for a child process.

3.
When SA_SIGINFO is requested, the SIGCHLD signal handler can be guaranteed to receive a non-NULL pointer to a siginfo_t structure that describes a child process for which a wait via waitpid() or waitid() will not block or fail.

4.
The system() function will not cause a process' SIGCHLD handler to be called as a result of the fork()/ exec executed within system() because system() will accept the SIGCHLD signal when it performs a waitpid() for its child process. This is a desirable behavior of system() so that it can be used in a library without causing side effects to the application linked with the library.

An implementation that does not permit the wait() family of functions to accept (discard) a pending SIGCHLD signal associated with a successfully waited-for child, cannot make the guarantees described above for the following reasons:

Guarantee #1

Although it might be assumed that reliable queuing of all SIGCHLD signals generated by the system can make this guarantee, the counter-example is the case of a process that blocks SIGCHLD and performs an indefinite loop of fork()/ wait() operations. If the implementation supports queued signals, then eventually the system will run out of memory for the queue. The guarantee cannot be made because there must be some limit to the depth of queuing.

Guarantees #2 and #3

These cannot be guaranteed unless the wait() family of functions accepts the SIGCHLD signal. Otherwise, a fork()/ wait() executed while SIGCHLD is blocked (as in the system() function) will result in an invocation of the handler when SIGCHLD is unblocked, after the process has disappeared.

Guarantee #4

Although possible to make this guarantee, system() would have to set the SIGCHLD handler to SIG_DFL so that the SIGCHLD signal generated by its fork() would be discarded (the SIGCHLD default action is to be ignored), then restore it to its previous setting. This would have the undesirable side effect of discarding all SIGCHLD signals pending to the process.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , exit() , fork() , waitid() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>, <sys/wait.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_setstacksize (3p)

 Continue to this page.


initstate (3p)

 Continue to this page.


posix_trace_attr_getmaxsystemeventsize (3p)

 Continue to this page.


dbm_firstkey (3p)

 Continue to this page.


remainder(3p)

REMAINDER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

remainder, remainderf, remainderl - remainder function

SYNOPSIS

#include <math.h>

double remainder(double x, double y);
float remainderf(float x, float y);
long double remainderl(long double x, long double y);

DESCRIPTION

These functions shall return the floating-point remainder r= x- ny when y is non-zero. The value n is the integral value nearest the exact value x/ y. When |n-x/y|=0.5, the value n is chosen to be even.

The behavior of remainder() shall be independent of the rounding mode.

RETURN VALUE

Upon successful completion, these functions shall return the floating-point remainder r= x- ny when y is non-zero.

If x or y is NaN, a NaN shall be returned.

If x is infinite or y is 0 and the other is non-NaN, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is ±Inf, or the y argument is ±0 and the other argument is non-NaN.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

abs() , div() , feclearexcept() , fetestexcept() , ldiv() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_once(3p)

PTHREAD_ONCE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_once - dynamic package initialization

SYNOPSIS

#include <pthread.h>

int pthread_once(pthread_once_t *once_control,
void (*init_routine)(void));
pthread_once_t once_control = PTHREAD_ONCE_INIT;

DESCRIPTION

The first call to pthread_once() by any thread in a process, with a given once_control, shall call the init_routine with no arguments. Subsequent calls of pthread_once() with the same once_control shall not call the init_routine. On return from pthread_once(), init_routine shall have completed. The once_control parameter shall determine whether the associated initialization routine has been called.

The pthread_once() function is not a cancellation point. However, if init_routine is a cancellation point and is canceled, the effect on once_control shall be as if pthread_once() was never called.

The constant PTHREAD_ONCE_INIT is defined in the <pthread.h> header.

The behavior of pthread_once() is undefined if once_control has automatic storage duration or is not initialized by PTHREAD_ONCE_INIT.

RETURN VALUE

Upon successful completion, pthread_once() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_once() function may fail if:

EINVAL
If either once_control or init_routine is invalid.

The pthread_once() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Some C libraries are designed for dynamic initialization. That is, the global initialization for the library is performed when the first procedure in the library is called. In a single-threaded program, this is normally implemented using a static variable whose value is checked on entry to a routine, as follows:

static int random_is_initialized = 0;
extern int initialize_random();

int random_function()
{
    if (random_is_initialized == 0) {
        initialize_random();
        random_is_initialized = 1;
    }
    ... /* Operations performed after initialization. */
}

To keep the same structure in a multi-threaded program, a new primitive is needed. Otherwise, library initialization has to be accomplished by an explicit call to a library-exported initialization function prior to any use of the library.

For dynamic library initialization in a multi-threaded process, a simple initialization flag is not sufficient; the flag needs to be protected against modification by multiple threads simultaneously calling into the library. Protecting the flag requires the use of a mutex; however, mutexes have to be initialized before they are used. Ensuring that the mutex is only initialized once requires a recursive solution to this problem.

The use of pthread_once() not only supplies an implementation-guaranteed means of dynamic initialization, it provides an aid to the reliable construction of multi-threaded and realtime systems. The preceding example then becomes:

#include <pthread.h>
static pthread_once_t random_is_initialized = PTHREAD_ONCE_INIT;
extern int initialize_random();

int random_function()
{
    (void) pthread_once(&random_is_initialized, initialize_random);
    ... /* Operations performed after initialization. */
}

Note that a pthread_once_t cannot be an array because some compilers do not accept the construct &<array_name>.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawn_file_actions_addopen(3p)

POSIX_SPAWN_FILE_ACTIONS_ADDCLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawn_file_actions_addclose, posix_spawn_file_actions_addopen - add close or open action to spawn file actions object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *
file_actions, int fildes);
int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *
restrict file_actions, int fildes,
const char *restrict path, int oflag, mode_t mode);

DESCRIPTION

These functions shall add or delete a close or open action to a spawn file actions object.

A spawn file actions object is of type posix_spawn_file_actions_t (defined in <spawn.h>) and is used to specify a series of actions to be performed by a posix_spawn() or posix_spawnp() operation in order to arrive at the set of open file descriptors for the child process given the set of open file descriptors of the parent. IEEE Std 1003.1-2001 does not define comparison or assignment operators for the type posix_spawn_file_actions_t.

A spawn file actions object, when passed to posix_spawn() or posix_spawnp(), shall specify how the set of open file descriptors in the calling process is transformed into a set of potentially open file descriptors for the spawned process. This transformation shall be as if the specified sequence of actions was performed exactly once, in the context of the spawned process (prior to execution of the new process image), in the order in which the actions were added to the object; additionally, when the new process image is executed, any file descriptor (from this new set) which has its FD_CLOEXEC flag set shall be closed (see posix_spawn() ).

The posix_spawn_file_actions_addclose() function shall add a close action to the object referenced by file_actions that shall cause the file descriptor fildes to be closed (as if close( fildes) had been called) when a new process is spawned using this file actions object.

The posix_spawn_file_actions_addopen() function shall add an open action to the object referenced by file_actions that shall cause the file named by path to be opened (as if open( path, oflag, mode) had been called, and the returned file descriptor, if not fildes, had been changed to fildes) when a new process is spawned using this file actions object. If fildes was already an open file descriptor, it shall be closed before the new file is opened.

The string described by path shall be copied by the posix_spawn_file_actions_addopen() function.

RETURN VALUE

Upon successful completion, these functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions shall fail if:

EBADF
The value specified by fildes is negative or greater than or equal to {OPEN_MAX}.

These functions may fail if:

EINVAL
The value specified by file_actions is invalid.
ENOMEM
Insufficient memory exists to add to the spawn file actions object.

It shall not be considered an error for the fildes argument passed to these functions to specify a file descriptor for which the specified operation could not be performed at the time of the call. Any such error will be detected when the associated file actions object is later used during a posix_spawn() or posix_spawnp() operation.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

A spawn file actions object may be initialized to contain an ordered sequence of close(), dup2(), and open() operations to be used by posix_spawn() or posix_spawnp() to arrive at the set of open file descriptors inherited by the spawned process from the set of open file descriptors in the parent at the time of the posix_spawn() or posix_spawnp() call. It had been suggested that the close() and dup2() operations alone are sufficient to rearrange file descriptors, and that files which need to be opened for use by the spawned process can be handled either by having the calling process open them before the posix_spawn() or posix_spawnp() call (and close them after), or by passing filenames to the spawned process (in argv) so that it may open them itself. The standard developers recommend that applications use one of these two methods when practical, since detailed error status on a failed open operation is always available to the application this way. However, the standard developers feel that allowing a spawn file actions object to specify open operations is still appropriate because:

1.
It is consistent with equivalent POSIX.5 (Ada) functionality.

2.
It supports the I/O redirection paradigm commonly employed by POSIX programs designed to be invoked from a shell. When such a program is the child process, it may not be designed to open files on its own.

3.
It allows file opens that might otherwise fail or violate file ownership/access rights if executed by the parent process.

Regarding 2. above, note that the spawn open file action provides to posix_spawn() and posix_spawnp() the same capability that the shell redirection operators provide to system(), only without the intervening execution of a shell; for example:

system ("myprog <file1 3<file2");

Regarding 3. above, note that if the calling process needs to open one or more files for access by the spawned process, but has insufficient spare file descriptors, then the open action is necessary to allow the open() to occur in the context of the child process after other file descriptors have been closed (that must remain open in the parent).

Additionally, if a parent is executed from a file having a "set-user-id" mode bit set and the POSIX_SPAWN_RESETIDS flag is set in the spawn attributes, a file created within the parent process will (possibly incorrectly) have the parent's effective user ID as its owner, whereas a file created via an open() action during posix_spawn() or posix_spawnp() will have the parent's real ID as its owner; and an open by the parent process may successfully open a file to which the real user should not have access or fail to open a file to which the real user should have access.

File Descriptor Mapping

The standard developers had originally proposed using an array which specified the mapping of child file descriptors back to those of the parent. It was pointed out by the ballot group that it is not possible to reshuffle file descriptors arbitrarily in a library implementation of posix_spawn() or posix_spawnp() without provision for one or more spare file descriptor entries (which simply may not be available). Such an array requires that an implementation develop a complex strategy to achieve the desired mapping without inadvertently closing the wrong file descriptor at the wrong time.

It was noted by a member of the Ada Language Bindings working group that the approved Ada Language Start_Process family of POSIX process primitives use a caller-specified set of file actions to alter the normal fork()/ exec semantics for inheritance of file descriptors in a very flexible way, yet no such problems exist because the burden of determining how to achieve the final file descriptor mapping is completely on the application. Furthermore, although the file actions interface appears frightening at first glance, it is actually quite simple to implement in either a library or the kernel.

FUTURE DIRECTIONS

None.

SEE ALSO

close() , dup() , open() , posix_spawn() , posix_spawn_file_actions_adddup2() , posix_spawn_file_actions_destroy() , posix_spawnp() , the Base Definitions volume of IEEE Std 1003.1-2001, <spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


asctime(3p)

ASCTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

asctime, asctime_r - convert date and time to a string

SYNOPSIS

#include <time.h>

char *asctime(const struct tm *timeptr);

char *asctime_r(const struct tm *restrict tm, char *restrict buf);

DESCRIPTION

For asctime(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The asctime() function shall convert the broken-down time in the structure pointed to by timeptr into a string in the form:

Sun Sep 16 01:03:52 1973\n\0

using the equivalent of the following algorithm:

char *asctime(const struct tm *timeptr)
{
    static char wday_name[7][3] = {
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
    };
    static char mon_name[12][3] = {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };
    static char result[26];

    sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
        wday_name[timeptr->tm_wday],
        mon_name[timeptr->tm_mon],
        timeptr->tm_mday, timeptr->tm_hour,
        timeptr->tm_min, timeptr->tm_sec,
        1900 + timeptr->tm_year);
    return result;
}

The tm structure is defined in the <time.h> header.

The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions.

The asctime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The asctime_r() function shall convert the broken-down time in the structure pointed to by tm into a string (of the same form as that returned by asctime()) that is placed in the user-supplied buffer pointed to by buf (which shall contain at least 26 bytes) and then return buf.

RETURN VALUE

Upon successful completion, asctime() shall return a pointer to the string.

Upon successful completion, asctime_r() shall return a pointer to a character string containing the date and time. This string is pointed to by the argument buf. If the function is unsuccessful, it shall return NULL.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Values for the broken-down time structure can be obtained by calling gmtime() or localtime(). This function is included for compatibility with older implementations, and does not support localized date and time formats. Applications should use strftime() to achieve maximum portability.

The asctime_r() function is thread-safe and shall return values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clock() , ctime() , difftime() , gmtime() , localtime() , mktime() , strftime() , strptime() , time() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_getsigdefault(3p)

POSIX_SPAWNATTR_GETSIGDEFAULT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawnattr_getsigdefault, posix_spawnattr_setsigdefault - get and set the spawn-sigdefault attribute of a spawn attributes object (ADVANCED REALTIME)

SYNOPSIS

#include <signal.h>
#include <spawn.h>

int posix_spawnattr_getsigdefault(const posix_spawnattr_t *
restrict attr, sigset_t *restrict sigdefault);
int posix_spawnattr_setsigdefault(posix_spawnattr_t *restrict attr,
const sigset_t *restrict sigdefault);

DESCRIPTION

The posix_spawnattr_getsigdefault() function shall obtain the value of the spawn-sigdefault attribute from the attributes object referenced by attr.

The posix_spawnattr_setsigdefault() function shall set the spawn-sigdefault attribute in an initialized attributes object referenced by attr.

The spawn-sigdefault attribute represents the set of signals to be forced to default signal handling in the new process image (if POSIX_SPAWN_SETSIGDEF is set in the spawn-flags attribute) by a spawn operation. The default value of this attribute shall be an empty signal set.

RETURN VALUE

Upon successful completion, posix_spawnattr_getsigdefault() shall return zero and store the value of the spawn-sigdefault attribute of attr into the object referenced by the sigdefault parameter; otherwise, an error number shall be returned to indicate the error.

Upon successful completion, posix_spawnattr_setsigdefault() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The posix_spawnattr_setsigdefault() function may fail if:

EINVAL
The value of the attribute being set is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnattr_destroy() , posix_spawnattr_init()
, posix_spawnattr_getflags() , posix_spawnattr_getpgroup()
, posix_spawnattr_getschedparam() , posix_spawnattr_getschedpolicy()
, posix_spawnattr_getsigmask() , posix_spawnattr_setflags()
, posix_spawnattr_setpgroup() , posix_spawnattr_setschedparam()
, posix_spawnattr_setschedpolicy() , posix_spawnattr_setsigmask()
, posix_spawnp() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>,
<spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


grantpt(3p)

GRANTPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

grantpt - grant access to the slave pseudo-terminal device

SYNOPSIS

#include <stdlib.h>

int grantpt(int fildes);

DESCRIPTION

The grantpt() function shall change the mode and ownership of the slave pseudo-terminal device associated with its master pseudo-terminal counterpart. The fildes argument is a file descriptor that refers to a master pseudo-terminal device. The user ID of the slave shall be set to the real UID of the calling process and the group ID shall be set to an unspecified group ID. The permission mode of the slave pseudo-terminal shall be set to readable and writable by the owner, and writable by the group.

The behavior of the grantpt() function is unspecified if the application has installed a signal handler to catch SIGCHLD signals.

RETURN VALUE

Upon successful completion, grantpt() shall return 0; otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The grantpt() function may fail if:

EBADF
The fildes argument is not a valid open file descriptor.
EINVAL
The fildes argument is not associated with a master pseudo-terminal device.
EACCES
The corresponding slave pseudo-terminal device could not be accessed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

open() , ptsname() , unlockpt() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlock_rdlock(3p)

PTHREAD_RWLOCK_RDLOCK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_rwlock_rdlock, pthread_rwlock_tryrdlock - lock a read-write lock object for reading

SYNOPSIS

#include <pthread.h>

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);

DESCRIPTION

The pthread_rwlock_rdlock() function shall apply a read lock to the read-write lock referenced by rwlock. The calling thread acquires the read lock if a writer does not hold the lock and there are no writers blocked on the lock.

If the Thread Execution Scheduling option is supported, and the threads involved in the lock are executing with the scheduling policies SCHED_FIFO or SCHED_RR, the calling thread shall not acquire the lock if a writer holds the lock or if writers of higher or equal priority are blocked on the lock; otherwise, the calling thread shall acquire the lock.

If the Threads Execution Scheduling option is supported, and the threads involved in the lock are executing with the SCHED_SPORADIC scheduling policy, the calling thread shall not acquire the lock if a writer holds the lock or if writers of higher or equal priority are blocked on the lock; otherwise, the calling thread shall acquire the lock.

If the Thread Execution Scheduling option is not supported, it is implementation-defined whether the calling thread acquires the lock when a writer does not hold the lock and there are writers blocked on the lock. If a writer holds the lock, the calling thread shall not acquire the read lock. If the read lock is not acquired, the calling thread shall block until it can acquire the lock. The calling thread may deadlock if at the time the call is made it holds a write lock.

A thread may hold multiple concurrent read locks on rwlock (that is, successfully call the pthread_rwlock_rdlock() function n times). If so, the application shall ensure that the thread performs matching unlocks (that is, it calls the pthread_rwlock_unlock() function n times).

The maximum number of simultaneous read locks that an implementation guarantees can be applied to a read-write lock shall be implementation-defined. The pthread_rwlock_rdlock() function may fail if this maximum would be exceeded.

The pthread_rwlock_tryrdlock() function shall apply a read lock as in the pthread_rwlock_rdlock() function, with the exception that the function shall fail if the equivalent pthread_rwlock_rdlock() call would have blocked the calling thread. In no case shall the pthread_rwlock_tryrdlock() function ever block; it always either acquires the lock or fails and returns immediately.

Results are undefined if any of these functions are called with an uninitialized read-write lock.

If a signal is delivered to a thread waiting for a read-write lock for reading, upon return from the signal handler the thread resumes waiting for the read-write lock for reading as if it was not interrupted.

RETURN VALUE

If successful, the pthread_rwlock_rdlock() function shall return zero; otherwise, an error number shall be returned to indicate the error.

The pthread_rwlock_tryrdlock() function shall return zero if the lock for reading on the read-write lock object referenced by rwlock is acquired. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_rwlock_tryrdlock() function shall fail if:

EBUSY
The read-write lock could not be acquired for reading because a writer holds the lock or a writer with the appropriate priority was blocked on it.

The pthread_rwlock_rdlock() and pthread_rwlock_tryrdlock() functions may fail if:

EINVAL
The value specified by rwlock does not refer to an initialized read-write lock object.
EAGAIN
The read lock could not be acquired because the maximum number of read locks for rwlock has been exceeded.

The pthread_rwlock_rdlock() function may fail if:

EDEADLK
The current thread already owns the read-write lock for writing.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_rwlock_destroy() , pthread_rwlock_timedrdlock()
, pthread_rwlock_timedwrlock() , pthread_rwlock_trywrlock()
, pthread_rwlock_unlock() , pthread_rwlock_wrlock() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswprint(3p)

ISWPRINT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswprint - test for a printable wide-character code

SYNOPSIS

#include <wctype.h>

int iswprint(wint_t wc);

DESCRIPTION

The iswprint() function shall test whether wc is a wide-character code representing a character of class print in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswprint() function shall return non-zero if wc is a printable wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


waitid(3p)

WAITID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

waitid - wait for a child process to change state

SYNOPSIS

#include <sys/wait.h>

int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);

DESCRIPTION

The waitid() function shall suspend the calling thread until one child of the process containing the calling thread changes state. It records the current state of a child in the structure pointed to by infop. If a child process changed state prior to the call to waitid(), waitid() shall return immediately. If more than one thread is suspended in wait() or waitpid() waiting for termination of the same process, exactly one thread shall return the process status at the time of the target process termination.

The idtype and id arguments are used to specify which children waitid() waits for.

If idtype is P_PID, waitid() shall wait for the child with a process ID equal to (pid_t)id.

If idtype is P_PGID, waitid() shall wait for any child with a process group ID equal to (pid_t)id.

If idtype is P_ALL, waitid() shall wait for any children and id is ignored.

The options argument is used to specify which state changes waitid() shall wait for. It is formed by OR'ing together one or more of the following flags:

WEXITED
Wait for processes that have exited.
WSTOPPED
Status shall be returned for any child that has stopped upon receipt of a signal.
WCONTINUED
Status shall be returned for any child that was stopped and has been continued.
WNOHANG
Return immediately if there are no children to wait for.
WNOWAIT
Keep the process whose status is returned in infop in a waitable state. This shall not affect the state of the process; the process may be waited for again after this call completes.

The application shall ensure that the infop argument points to a siginfo_t structure. If waitid() returns because a child process was found that satisfied the conditions indicated by the arguments idtype and options, then the structure pointed to by infop shall be filled in by the system with the status of the process. The si_signo member shall always be equal to SIGCHLD.

RETURN VALUE

If WNOHANG was specified and there are no children to wait for, 0 shall be returned. If waitid() returns due to the change of state of one of its children, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The waitid() function shall fail if:

ECHILD
The calling process has no existing unwaited-for child processes.
EINTR
The waitid() function was interrupted by a signal.
EINVAL
An invalid value was specified for options, or idtype and id specify an invalid set of processes.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , exit() , wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/wait.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_spin_destroy (3p)

 Continue to this page.


index(3p)

INDEX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

index - character string operations (LEGACY)

SYNOPSIS

#include <strings.h>

char *index(const char *s, int c);

DESCRIPTION

The index() function shall be equivalent to strchr().

RETURN VALUE

See strchr() .

ERRORS

See strchr() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The strchr() function is preferred over this function.

For maximum portability, it is recommended to replace the function call to index() as follows:

#define index(a,b) strchr((a),(b))

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

strchr() , the Base Definitions volume of IEEE Std 1003.1-2001, <strings.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_cancel(3p)

PTHREAD_CANCEL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_cancel - cancel execution of a thread

SYNOPSIS

#include <pthread.h>

int pthread_cancel(pthread_t thread);

DESCRIPTION

The pthread_cancel() function shall request that thread be canceled. The target thread's cancelability state and type determines when the cancellation takes effect. When the cancellation is acted on, the cancellation cleanup handlers for thread shall be called. When the last cancellation cleanup handler returns, the thread-specific data destructor functions shall be called for thread. When the last destructor function returns, thread shall be terminated.

The cancellation processing in the target thread shall run asynchronously with respect to the calling thread returning from pthread_cancel().

RETURN VALUE

If successful, the pthread_cancel() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_cancel() function may fail if:

ESRCH
No thread could be found corresponding to that specified by the given thread ID.

The pthread_cancel() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Two alternative functions were considered for sending the cancellation notification to a thread. One would be to define a new SIGCANCEL signal that had the cancellation semantics when delivered; the other was to define the new pthread_cancel() function, which would trigger the cancellation semantics.

The advantage of a new signal was that so much of the delivery criteria were identical to that used when trying to deliver a signal that making cancellation notification a signal was seen as consistent. Indeed, many implementations implement cancellation using a special signal. On the other hand, there would be no signal functions that could be used with this signal except pthread_kill(), and the behavior of the delivered cancellation signal would be unlike any previously existing defined signal.

The benefits of a special function include the recognition that this signal would be defined because of the similar delivery criteria and that this is the only common behavior between a cancellation request and a signal. In addition, the cancellation delivery mechanism does not have to be implemented as a signal. There are also strong, if not stronger, parallels with language exception mechanisms than with signals that are potentially obscured if the delivery mechanism is visibly closer to signals.

In the end, it was considered that as there were so many exceptions to the use of the new signal with existing signals functions it would be misleading. A special function has resolved this problem. This function was carefully defined so that an implementation wishing to provide the cancellation functions on top of signals could do so. The special function also means that implementations are not obliged to implement cancellation with signals.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_exit() , pthread_cond_timedwait() , pthread_join() , pthread_setcancelstate() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


truncate(3p)

TRUNCATE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

truncate - truncate a file to a specified length

SYNOPSIS

#include <unistd.h>

int truncate(const char *path, off_t length);

DESCRIPTION

The truncate() function shall cause the regular file named by path to have a size which shall be equal to length bytes.

If the file previously was larger than length, the extra data is discarded. If the file was previously shorter than length, its size is increased, and the extended area appears as if it were zero-filled.

The application shall ensure that the process has write permission for the file.

If the request would cause the file size to exceed the soft file size limit for the process, the request shall fail and the implementation shall generate the SIGXFSZ signal for the process.

This function shall not modify the file offset for any open file descriptions associated with the file. Upon successful completion, if the file size is changed, this function shall mark for update the st_ctime and st_mtime fields of the file, and the S_ISUID and S_ISGID bits of the file mode may be cleared.

RETURN VALUE

Upon successful completion, truncate() shall return 0. Otherwise, -1 shall be returned, and errno set to indicate the error.

ERRORS

The truncate() function shall fail if:

EINTR
A signal was caught during execution.
EINVAL
The length argument was less than 0.
EFBIG or EINVAL
The length argument was greater than the maximum file size.
EIO
An I/O error occurred while reading from or writing to a file system.
EACCES
A component of the path prefix denies search permission, or write permission is denied on the file.
EISDIR
The named file is a directory.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix of path is not a directory.
EROFS
The named file resides on a read-only file system.

The truncate() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

open() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getprotoent(3p)

ENDPROTOENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

endprotoent, getprotobyname, getprotobynumber, getprotoent, setprotoent - network protocol database functions

SYNOPSIS

#include <netdb.h>

void endprotoent(void);
struct protoent *getprotobyname(const char *name);
struct protoent *getprotobynumber(int proto);
struct protoent *getprotoent(void);
void setprotoent(int stayopen);

DESCRIPTION

These functions shall retrieve information about protocols. This information is considered to be stored in a database that can be accessed sequentially or randomly. The implementation of this database is unspecified.

The setprotoent() function shall open a connection to the database, and set the next entry to the first entry. If the stayopen argument is non-zero, the connection to the network protocol database shall not be closed after each call to getprotoent() (either directly, or indirectly through one of the other getproto*() functions), and the implementation may maintain an open file descriptor for the database.

The getprotobyname() function shall search the database from the beginning and find the first entry for which the protocol name specified by name matches the p_name member, opening and closing a connection to the database as necessary.

The getprotobynumber() function shall search the database from the beginning and find the first entry for which the protocol number specified by proto matches the p_proto member, opening and closing a connection to the database as necessary.

The getprotoent() function shall read the next entry of the database, opening and closing a connection to the database as necessary.

The getprotobyname(), getprotobynumber(), and getprotoent() functions shall each return a pointer to a protoent structure, the members of which shall contain the fields of an entry in the network protocol database.

The endprotoent() function shall close the connection to the database, releasing any open file descriptor.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, getprotobyname(), getprotobynumber(), and getprotoent() return a pointer to a protoent structure if the requested entry was found, and a null pointer if the end of the database was reached or the requested entry was not found. Otherwise, a null pointer is returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The getprotobyname(), getprotobynumber(), and getprotoent() functions may return pointers to static data, which may be overwritten by subsequent calls to any of these functions.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ftello (3p)

 Continue to this page.


toascii(3p)

TOASCII

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

toascii - translate an integer to a 7-bit ASCII character

SYNOPSIS

#include <ctype.h>

int toascii(int c);

DESCRIPTION

The toascii() function shall convert its argument into a 7-bit ASCII character.

RETURN VALUE

The toascii() function shall return the value (c &0x7f).

ERRORS

No errors are returned.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isascii() , the Base Definitions volume of IEEE Std 1003.1-2001, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


open(3p)

OPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

open - open a file

SYNOPSIS

#include <sys/stat.h>
#include <fcntl.h>

int open(const char *path, int oflag, ... );

DESCRIPTION

The open() function shall establish the connection between a file and a file descriptor. It shall create an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file.

The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor shall be cleared.

The file offset used to mark the current position within the file shall be set to the beginning of the file.

The file status flags and file access modes of the open file description shall be set according to the value of oflag.

Values for oflag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h>. Applications shall specify exactly one of the first three values (file access modes) below in the value of oflag:

O_RDONLY
Open for reading only.
O_WRONLY
Open for writing only.
O_RDWR
Open for reading and writing. The result is undefined if this flag is applied to a FIFO.

Any combination of the following may be used:

O_APPEND
If set, the file offset shall be set to the end of the file prior to each write.
O_CREAT
If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file shall be created; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see <sys/stat.h>) of the file mode shall be set to the value of the third argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process.
O_DSYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.
O_EXCL
If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.
O_NOCTTY
If set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
O_NONBLOCK
When opening a FIFO with O_RDONLY or O_WRONLY set:
*
If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process currently has the file open for reading.

*
If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading.

When opening a block special or character special file that supports non-blocking opens:

*
If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific.

*
If O_NONBLOCK is clear, the open() function shall block the calling thread until the device is ready or available before returning.

Otherwise, the behavior of O_NONBLOCK is unspecified.

O_RSYNC
Read I/O operations on the file descriptor shall complete at the same level of integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are set in oflag, all I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If both O_SYNC and O_RSYNC are set in flags, all I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_SYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_TRUNC
If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of using O_TRUNC with O_RDONLY is undefined.

If O_CREAT is set and the file did not previously exist, upon successful completion, open() shall mark for update the st_atime, st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.

If O_TRUNC is set and the file did previously exist, upon successful completion, open() shall mark for update the st_ctime and st_mtime fields of the file.

If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set.

If path refers to a STREAMS file, oflag may be constructed from O_NONBLOCK OR'ed with either O_RDONLY, O_WRONLY, or O_RDWR. Other flag values are not applicable to STREAMS devices and shall have no effect on them. The value O_NONBLOCK affects the operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMS drivers, the implementation of O_NONBLOCK is device-specific.

If path names the master side of a pseudo-terminal device, then it is unspecified whether open() locks the slave side so that it cannot be opened. Conforming applications shall call unlockpt() before opening the slave side.

The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description.

RETURN VALUE

Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1.

ERRORS

The open() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by oflag are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created, or O_TRUNC is specified and write permission is denied.
EEXIST
O_CREAT and O_EXCL are set, and the named file exists.
EINTR
A signal was caught during open().
EINVAL
The implementation does not support synchronized I/O for this file.
EIO
The path argument names a STREAMS file and a hangup or error occurred during the open().
EISDIR
The named file is a directory and oflag includes O_WRONLY or O_RDWR.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
The maximum allowable number of files is currently open in the system.
ENOENT
O_CREAT is not set and the named file does not exist; or O_CREAT is set and either the path prefix does not exist or the path argument points to an empty string.
ENOSR
The path argument names a STREAMS-based file and the system is unable to allocate a STREAM.
ENOSPC
The directory or file system that would contain the new file cannot be expanded, the file does not exist, and O_CREAT is specified.
ENOTDIR
A component of the path prefix is not a directory.
ENXIO
O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set, and no process has the file open for reading.
ENXIO
The named file is a character special or block special file, and the device associated with this special file does not exist.
EOVERFLOW
The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only file system and either O_WRONLY, O_RDWR, O_CREAT (if the file does not exist), or O_TRUNC is set in the oflag argument.

The open() function may fail if:

EAGAIN
The path argument names the slave side of a pseudo-terminal device that is locked.
EINVAL
The value of the oflag argument is not valid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ENOMEM
The path argument names a STREAMS file and the system is unable to allocate resources.
ETXTBSY
The file is a pure procedure (shared text) file that is being executed and oflag is O_WRONLY or O_RDWR.

The following sections are informative.

EXAMPLES

Opening a File for Writing by the Owner

The following example opens the file /tmp/file, either by creating it (if it does not already exist), or by truncating its length to 0 (if it does exist). In the former case, if the call creates a new file, the access permission bits in the file mode of the file are set to permit reading and writing by the owner, and to permit reading only by group members and others.

If the call to open() is successful, the file is opened for writing.

#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *filename = "/tmp/file";
...
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, mode);
...

Opening a File Using an Existence Check

The following example uses the open() function to try to create the LOCKFILE file and open it for writing. Since the open() function specifies the O_EXCL flag, the call fails if the file already exists. In that case, the program assumes that someone else is updating the password file and exits.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

#define LOCKFILE "/etc/ptmp"
...
int pfd; /* Integer for file descriptor returned by open() call. */
...
if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
    fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
    exit(1);
}
...

Opening a File for Writing

The following example opens a file for writing, creating the file if it does not already exist. If the file does exist, the system truncates the file to zero bytes.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

#define LOCKFILE "/etc/ptmp"
...
int pfd;
char filename[PATH_MAX+1];
...
if ((pfd = open(filename, O_WRONLY | O_CREAT | O_TRUNC,
    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
    perror("Cannot open output file\n"); exit(1);
}
...

APPLICATION USAGE

None.

RATIONALE

Except as specified in this volume of IEEE Std 1003.1-2001, the flags allowed in oflag are not mutually-exclusive and any number of them may be used simultaneously.

Some implementations permit opening FIFOs with O_RDWR. Since FIFOs could be implemented in other ways, and since two file descriptors can be used to the same effect, this possibility is left as undefined.

See getgroups() about the group of a newly created file.

The use of open() to create a regular file is preferable to the use of creat(), because the latter is redundant and included only for historical reasons.

The use of the O_TRUNC flag on FIFOs and directories (pipes cannot be open()-ed) must be permissible without unexpected side effects (for example, creat() on a FIFO must not remove data). Since terminal special files might have type-ahead data stored in the buffer, O_TRUNC should not affect their content, particularly if a program that normally opens a regular file should open the current controlling terminal instead. Other file types, particularly implementation-defined ones, are left implementation-defined.

IEEE Std 1003.1-2001 permits [EACCES] to be returned for conditions other than those explicitly listed.

The O_NOCTTY flag was added to allow applications to avoid unintentionally acquiring a controlling terminal as a side effect of opening a terminal file. This volume of IEEE Std 1003.1-2001 does not specify how a controlling terminal is acquired, but it allows an implementation to provide this on open() if the O_NOCTTY flag is not set and other conditions specified in the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface are met. The O_NOCTTY flag is an effective no-op if the file being opened is not a terminal device.

In historical implementations the value of O_RDONLY is zero. Because of that, it is not possible to detect the presence of O_RDONLY and another option. Future implementations should encode O_RDONLY and O_WRONLY as bit flags so that:

O_RDONLY | O_WRONLY == O_RDWR

In general, the open() function follows the symbolic link if path names a symbolic link. However, the open() function, when called with O_CREAT and O_EXCL, is required to fail with [EEXIST] if path names an existing symbolic link, even if the symbolic link refers to a nonexistent file. This behavior is required so that privileged applications can create a new file in a known location without the possibility that a symbolic link might cause the file to be created in a different location.

For example, a privileged application that must create a file with a predictable name in a user-writable directory, such as the user's home directory, could be compromised if the user creates a symbolic link with that name that refers to a nonexistent file in a system directory. If the user can influence the contents of a file, the user could compromise the system by creating a new system configuration or spool file that would then be interpreted by the system. The test for a symbolic link which refers to a nonexisting file must be atomic with the creation of a new file.

The POSIX.1-1990 standard required that the group ID of a newly created file be set to the group ID of its parent directory or to the effective group ID of the creating process. FIPS 151-2 required that implementations provide a way to have the group ID be set to the group ID of the containing directory, but did not prohibit implementations also supporting a way to set the group ID to the effective group ID of the creating process. Conforming applications should not assume which group ID will be used. If it matters, an application can use chown() to set the group ID after the file is created, or determine under what conditions the implementation will set the desired group ID.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , close() , creat() , dup() , fcntl() , lseek() , read() , umask() , unlockpt() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_rwlock_destroy (3p)

 Continue to this page.


bsd_signal(3p)

BSD_SIGNAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bsd_signal - simplified signal facilities

SYNOPSIS

#include <signal.h>

void (*bsd_signal(int sig, void (*func)(int)))(int);

DESCRIPTION

The bsd_signal() function provides a partially compatible interface for programs written to historical system interfaces (see APPLICATION USAGE).

The function call bsd_signal(sig, func) shall be equivalent to the following:

void (*bsd_signal(int sig, void (*func)(int)))(int)
{
    struct sigaction act, oact;

    act.sa_handler = func;
    act.sa_flags = SA_RESTART;

    sigemptyset(&act.sa_mask);
    sigaddset(&act.sa_mask, sig);
    if (sigaction(sig, &act, &oact) == -1)
        return(SIG_ERR);

    return(oact.sa_handler);
}

The handler function should be declared:

void handler(int sig);

where sig is the signal number. The behavior is undefined if func is a function that takes more than one argument, or an argument of a different type.

RETURN VALUE

Upon successful completion, bsd_signal() shall return the previous action for sig. Otherwise, SIG_ERR shall be returned and errno shall be set to indicate the error.

ERRORS

Refer to sigaction() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

This function is a direct replacement for the BSD signal() function for simple applications that are installing a single-argument signal handler function. If a BSD signal handler function is being installed that expects more than one argument, the application has to be modified to use sigaction(). The bsd_signal() function differs from signal() in that the SA_RESTART flag is set and the SA_RESETHAND is clear when bsd_signal() is used. The state of these flags is not specified for signal().

It is recommended that new applications use the sigaction() function.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

sigaction() , sigaddset() , sigemptyset() , signal() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ctermid(3p)

CTERMID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ctermid - generate a pathname for the controlling terminal

SYNOPSIS

#include <stdio.h>

char *ctermid(char *s);

DESCRIPTION

The ctermid() function shall generate a string that, when used as a pathname, refers to the current controlling terminal for the current process. If ctermid() returns a pathname, access to the file is not guaranteed.

If the application uses any of the _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS functions, it shall ensure that the ctermid() function is called with a non-NULL parameter.

RETURN VALUE

If s is a null pointer, the string shall be generated in an area that may be static (and therefore may be overwritten by each call), the address of which shall be returned. Otherwise, s is assumed to point to a character array of at least L_ctermid bytes; the string is placed in this array and the value of s shall be returned. The symbolic constant L_ctermid is defined in <stdio.h>, and shall have a value greater than 0.

The ctermid() function shall return an empty string if the pathname that would refer to the controlling terminal cannot be determined, or if the function is unsuccessful.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Determining the Controlling Terminal for the Current Process

The following example returns a pointer to a string that identifies the controlling terminal for the current process. The pathname for the terminal is stored in the array pointed to by the ptr argument, which has a size of L_ctermid bytes, as indicated by the term argument.

#include <stdio.h>
...
char term[L_ctermid];
char *ptr;

ptr = ctermid(term);

APPLICATION USAGE

The difference between ctermid() and ttyname() is that ttyname() must be handed a file descriptor and return a path of the terminal associated with that file descriptor, while ctermid() returns a string (such as "/dev/tty" ) that refers to the current controlling terminal if used as a pathname.

RATIONALE

L_ctermid must be defined appropriately for a given implementation and must be greater than zero so that array declarations using it are accepted by the compiler. The value includes the terminating null byte.

Conforming applications that use threads cannot call ctermid() with NULL as the parameter if either _POSIX_THREAD_SAFE_FUNCTIONS or _POSIX_THREADS is defined. If s is not NULL, the ctermid() function generates a string that, when used as a pathname, refers to the current controlling terminal for the current process. If s is NULL, the return value of ctermid() is undefined.

There is no additional burden on the programmer-changing to use a hypothetical thread-safe version of ctermid() along with allocating a buffer is more of a burden than merely allocating a buffer. Application code should not assume that the returned string is short, as some implementations have more than two pathname components before reaching a logical device name.

FUTURE DIRECTIONS

None.

SEE ALSO

ttyname() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ntohl (3p)

 Continue to this page.


environ (3p)

 Continue to this page.


ntohs (3p)

 Continue to this page.


creal(3p)

CREAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

creal, crealf, creall - complex real functions

SYNOPSIS

#include <complex.h>

double creal(double complex z);
float crealf(float complex z);
long double creall(long double complex z);

DESCRIPTION

These functions shall compute the real part of z.

RETURN VALUE

These functions shall return the real part value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

For a variable z of type complex:

z == creal(z) + cimag(z)*I

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

carg() , cimag() , conj() , cproj() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_cond_signal(3p)

PTHREAD_COND_BROADCAST

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_cond_broadcast, pthread_cond_signal - broadcast or signal a condition

SYNOPSIS

#include <pthread.h>

int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);

DESCRIPTION

These functions shall unblock threads blocked on a condition variable.

The pthread_cond_broadcast() function shall unblock all threads currently blocked on the specified condition variable cond.

The pthread_cond_signal() function shall unblock at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond).

If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked. When each thread unblocked as a result of a pthread_cond_broadcast() or pthread_cond_signal() returns from its call to pthread_cond_wait() or pthread_cond_timedwait(), the thread shall own the mutex with which it called pthread_cond_wait() or pthread_cond_timedwait(). The thread(s) that are unblocked shall contend for the mutex according to the scheduling policy (if applicable), and as if each had called pthread_mutex_lock().

The pthread_cond_broadcast() or pthread_cond_signal() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits; however, if predictable scheduling behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal().

The pthread_cond_broadcast() and pthread_cond_signal() functions shall have no effect if there are no threads currently blocked on cond.

RETURN VALUE

If successful, the pthread_cond_broadcast() and pthread_cond_signal() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_cond_broadcast() and pthread_cond_signal() function may fail if:

EINVAL
The value cond does not refer to an initialized condition variable.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The pthread_cond_broadcast() function is used whenever the shared-variable state has been changed in a way that more than one thread can proceed with its task. Consider a single producer/multiple consumer problem, where the producer can insert multiple items on a list that is accessed one item at a time by the consumers. By calling the pthread_cond_broadcast() function, the producer would notify all consumers that might be waiting, and thereby the application would receive more throughput on a multi-processor. In addition, pthread_cond_broadcast() makes it easier to implement a read-write lock. The pthread_cond_broadcast() function is needed in order to wake up all waiting readers when a writer releases its lock. Finally, the two-phase commit algorithm can use this broadcast function to notify all clients of an impending transaction commit.

It is not safe to use the pthread_cond_signal() function in a signal handler that is invoked asynchronously. Even if it were safe, there would still be a race between the test of the Boolean pthread_cond_wait() that could not be efficiently eliminated.

Mutexes and condition variables are thus not suitable for releasing a waiting thread by signaling from code running in a signal handler.

RATIONALE

Multiple Awakenings by Condition Signal

On a multi-processor, it may be impossible for an implementation of pthread_cond_signal() to avoid the unblocking of more than one thread blocked on a condition variable. For example, consider the following partial implementation of pthread_cond_wait() and pthread_cond_signal(), executed by two threads in the order given. One thread is trying to wait on the condition variable, another is concurrently executing pthread_cond_signal(), while a third thread is already waiting.

pthread_cond_wait(mutex, cond):
    value = cond->value; /* 1 */
    pthread_mutex_unlock(mutex); /* 2 */
    pthread_mutex_lock(cond->mutex); /* 10 */
    if (value == cond->value) { /* 11 */
        me->next_cond = cond->waiter;
        cond->waiter = me;
        pthread_mutex_unlock(cond->mutex);
        unable_to_run(me);
    } else
        pthread_mutex_unlock(cond->mutex); /* 12 */
    pthread_mutex_lock(mutex); /* 13 */

pthread_cond_signal(cond):
    pthread_mutex_lock(cond->mutex); /* 3 */
    cond->value++; /* 4 */
    if (cond->waiter) { /* 5 */
        sleeper = cond->waiter; /* 6 */
        cond->waiter = sleeper->next_cond; /* 7 */
        able_to_run(sleeper); /* 8 */
    }
    pthread_mutex_unlock(cond->mutex); /* 9 */

The effect is that more than one thread can return from its call to pthread_cond_wait() or pthread_cond_timedwait() as a result of one call to pthread_cond_signal(). This effect is called "spurious wakeup". Note that the situation is self-correcting in that the number of threads that are so awakened is finite; for example, the next thread to call pthread_cond_wait() after the sequence of events above blocks.

While this problem could be resolved, the loss of efficiency for a fringe condition that occurs only rarely is unacceptable, especially given that one has to check the predicate associated with a condition variable anyway. Correcting this problem would unnecessarily reduce the degree of concurrency in this basic building block for all higher-level synchronization operations.

An added benefit of allowing spurious wakeups is that applications are forced to code a predicate-testing-loop around the condition wait. This also makes the application tolerate superfluous condition broadcasts or signals on the same condition variable that may be coded in some other part of the application. The resulting applications are thus more robust. Therefore, IEEE Std 1003.1-2001 explicitly documents that spurious wakeups may occur.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_destroy() , pthread_cond_timedwait() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


creat(3p)

CREAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

creat - create a new file or rewrite an existing one

SYNOPSIS

#include <sys/stat.h>
#include <fcntl.h>

int creat(const char *path, mode_t mode);

DESCRIPTION

The function call:

creat(path, mode)

shall be equivalent to:

open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)

RETURN VALUE

Refer to open() .

ERRORS

Refer to open() .

The following sections are informative.

EXAMPLES

Creating a File

The following example creates the file /tmp/file with read and write permissions for the file owner and read permission for group and others. The resulting file descriptor is assigned to the fd variable.

#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *filename = "/tmp/file";
...
fd = creat(filename, mode);
...

APPLICATION USAGE

None.

RATIONALE

The creat() function is redundant. Its services are also provided by the open() function. It has been included primarily for historical purposes since many existing applications depend on it. It is best considered a part of the C binding rather than a function that should be provided in other languages.

FUTURE DIRECTIONS

None.

SEE ALSO

open() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_condattr_setpshared (3p)

 Continue to this page.


getpriority(3p)

GETPRIORITY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getpriority, setpriority - get and set the nice value

SYNOPSIS

#include <sys/resource.h>

int getpriority(int which, id_t who);
int setpriority(int which, id_t who, int value);

DESCRIPTION

The getpriority() function shall obtain the nice value of a process, process group, or user. The setpriority() function shall set the nice value of a process, process group, or user to value+ {NZERO}.

Target processes are specified by the values of the which and who arguments. The which argument may be one of the following values: PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, indicating that the who argument is to be interpreted as a process ID, a process group ID, or an effective user ID, respectively. A 0 value for the who argument specifies the current process, process group, or user.

The nice value set with setpriority() shall be applied to the process. If the process is multi-threaded, the nice value shall affect all system scope threads in the process.

If more than one process is specified, getpriority() shall return value {NZERO} less than the lowest nice value pertaining to any of the specified processes, and setpriority() shall set the nice values of all of the specified processes to value+ {NZERO}.

The default nice value is {NZERO}; lower nice values shall cause more favorable scheduling. While the range of valid nice values is [0,{NZERO}*2-1], implementations may enforce more restrictive limits. If value+ {NZERO} is less than the system's lowest supported nice value, setpriority() shall set the nice value to the lowest supported value; if value+ {NZERO} is greater than the system's highest supported nice value, setpriority() shall set the nice value to the highest supported value.

Only a process with appropriate privileges can lower its nice value.

Any processes or threads using SCHED_FIFO or SCHED_RR shall be unaffected by a call to setpriority(). This is not considered an error. A process which subsequently reverts to SCHED_OTHER need not have its priority affected by such a setpriority() call.

The effect of changing the nice value may vary depending on the process-scheduling algorithm in effect.

Since getpriority() can return the value -1 on successful completion, it is necessary to set errno to 0 prior to a call to getpriority(). If getpriority() returns the value -1, then errno can be checked to see if an error occurred or if the value is a legitimate nice value.

RETURN VALUE

Upon successful completion, getpriority() shall return an integer in the range -{NZERO} to {NZERO}-1. Otherwise, -1 shall be returned and errno set to indicate the error.

Upon successful completion, setpriority() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The getpriority() and setpriority() functions shall fail if:

ESRCH
No process could be located using the which and who argument values specified.
EINVAL
The value of the which argument was not recognized, or the value of the who argument is not a valid process ID, process group ID, or user ID.

In addition, setpriority() may fail if:

EPERM
A process was located, but neither the real nor effective user ID of the executing process match the effective user ID of the process whose nice value is being changed.
EACCES
A request was made to change the nice value to a lower numeric value and the current process does not have appropriate privileges.

The following sections are informative.

EXAMPLES

Using getpriority()

The following example returns the current scheduling priority for the process ID returned by the call to getpid().

#include <sys/resource.h>
...
int which = PRIO_PROCESS;
id_t pid;
int ret;

pid = getpid();
ret = getpriority(which, pid);

Using setpriority()

The following example sets the priority for the current process ID to -20.

#include <sys/resource.h>
...
int which = PRIO_PROCESS;
id_t pid;
int priority = -20;
int ret;

pid = getpid();
ret = setpriority(which, pid, priority);

APPLICATION USAGE

The getpriority() and setpriority() functions work with an offset nice value (nice value -{NZERO}). The nice value is in the range [0,2*{NZERO} -1], while the return value for getpriority() and the third parameter for setpriority() are in the range [-{NZERO},{NZERO} -1].

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

nice() , sched_get_priority_max() , sched_setscheduler() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/resource.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nexttowardf (3p)

 Continue to this page.


pthread_attr_setscope (3p)

 Continue to this page.


nexttowardl (3p)

 Continue to this page.


opendir(3p)

OPENDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

opendir - open a directory

SYNOPSIS

#include <dirent.h>

DIR *opendir(const char *dirname);

DESCRIPTION

The opendir() function shall open a directory stream corresponding to the directory named by the dirname argument. The directory stream is positioned at the first entry. If the type DIR is implemented using a file descriptor, applications shall only be able to open up to a total of {OPEN_MAX} files and directories.

RETURN VALUE

Upon successful completion, opendir() shall return a pointer to an object of type DIR. Otherwise, a null pointer shall be returned and errno set to indicate the error.

ERRORS

The opendir() function shall fail if:

EACCES
Search permission is denied for the component of the path prefix of dirname or read permission is denied for dirname.
ELOOP
A loop exists in symbolic links encountered during resolution of the dirname argument.
ENAMETOOLONG
The length of the dirname argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of dirname does not name an existing directory or dirname is an empty string.
ENOTDIR
A component of dirname is not a directory.

The opendir() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the dirname argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the dirname argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ENFILE
Too many files are currently open in the system.

The following sections are informative.

EXAMPLES

Open a Directory Stream

The following program fragment demonstrates how the opendir() function is used.

#include <sys/types.h>
#include <dirent.h>
#include <libgen.h>
...
    DIR *dir;
    struct dirent *dp;
...
    if ((dir = opendir (".")) == NULL) {
        perror ("Cannot open .");
        exit (1);
    }

    while ((dp = readdir (dir)) != NULL) {
...

APPLICATION USAGE

The opendir() function should be used in conjunction with readdir(), closedir(), and rewinddir() to examine the contents of the directory (see the EXAMPLES section in readdir() ). This method is recommended for portability.

RATIONALE

Based on historical implementations, the rules about file descriptors apply to directory streams as well. However, this volume of IEEE Std 1003.1-2001 does not mandate that the directory stream be implemented using file descriptors. The description of closedir() clarifies that if a file descriptor is used for the directory stream, it is mandatory that closedir() deallocate the file descriptor. When a file descriptor is used to implement the directory stream, it behaves as if the FD_CLOEXEC had been set for the file descriptor.

The directory entries for dot and dot-dot are optional. This volume of IEEE Std 1003.1-2001 does not provide a way to test a priori for their existence because an application that is portable must be written to look for (and usually ignore) those entries. Writing code that presumes that they are the first two entries does not always work, as many implementations permit them to be other than the first two entries, with a "normal" entry preceding them. There is negligible value in providing a way to determine what the implementation does because the code to deal with dot and dot-dot must be written in any case and because such a flag would add to the list of those flags (which has proven in itself to be objectionable) and might be abused.

Since the structure and buffer allocation, if any, for directory operations are defined by the implementation, this volume of IEEE Std 1003.1-2001 imposes no portability requirements for erroneous program constructs, erroneous data, or the use of unspecified values such as the use or referencing of a dirp value or a dirent structure value after a directory stream has been closed or after a fork() or one of the exec function calls.

FUTURE DIRECTIONS

None.

SEE ALSO

closedir() , lstat() , readdir() , rewinddir() , symlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <dirent.h>, <limits.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


asin(3p)

ASIN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

asin, asinf, asinl - arc sine function

SYNOPSIS

#include <math.h>

double asin(double x);
float asinf(float x);
long double asinl(long double x);

DESCRIPTION

These functions shall compute the principal value of the arc sine of their argument x. The value of x should be in the range [-1,1].

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the arc sine of x, in the range [-pi/2,pi/2] radians.

For finite values of x not in the range [-1,1], a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0, x shall be returned.

If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is finite and is not in the range [-1,1], or is ±Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

These functions may fail if:

Range Error
The value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , sin() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getnetent(3p)

ENDNETENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

endnetent, getnetbyaddr, getnetbyname, getnetent, setnetent - network database functions

SYNOPSIS

#include <netdb.h>

void endnetent(void);
struct netent *getnetbyaddr(uint32_t net, int type);
struct netent *getnetbyname(const char *name);
struct netent *getnetent(void);
void setnetent(int stayopen);

DESCRIPTION

These functions shall retrieve information about networks. This information is considered to be stored in a database that can be accessed sequentially or randomly. The implementation of this database is unspecified.

The setnetent() function shall open and rewind the database. If the stayopen argument is non-zero, the connection to the net database shall not be closed after each call to getnetent() (either directly, or indirectly through one of the other getnet*() functions), and the implementation may maintain an open file descriptor to the database.

The getnetent() function shall read the next entry of the database, opening and closing a connection to the database as necessary.

The getnetbyaddr() function shall search the database from the beginning, and find the first entry for which the address family specified by type matches the n_addrtype member and the network number net matches the n_net member, opening and closing a connection to the database as necessary. The net argument shall be the network number in host byte order.

The getnetbyname() function shall search the database from the beginning and find the first entry for which the network name specified by name matches the n_name member, opening and closing a connection to the database as necessary.

The getnetbyaddr(), getnetbyname(), and getnetent() functions shall each return a pointer to a netent structure, the members of which shall contain the fields of an entry in the network database.

The endnetent() function shall close the database, releasing any open file descriptor.

These functions need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, getnetbyaddr(), getnetbyname(), and getnetent() shall return a pointer to a netent structure if the requested entry was found, and a null pointer if the end of the database was reached or the requested entry was not found. Otherwise, a null pointer shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The getnetbyaddr(), getnetbyname(), and getnetent() functions may return pointers to static data, which may be overwritten by subsequent calls to any of these functions.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


timer_delete(3p)

TIMER_DELETE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

timer_delete - delete a per-process timer (REALTIME)

SYNOPSIS

#include <time.h>

int timer_delete(timer_t timerid);

DESCRIPTION

The timer_delete() function deletes the specified timer, timerid, previously created by the timer_create() function. If the timer is armed when timer_delete() is called, the behavior shall be as if the timer is automatically disarmed before removal. The disposition of pending signals for the deleted timer is unspecified.

RETURN VALUE

If successful, the timer_delete() function shall return a value of zero. Otherwise, the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The timer_delete() function shall fail if:

EINVAL
The timer ID specified by timerid is not a valid timer ID.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

timer_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutex_destroy (3p)

 Continue to this page.


posix_spawnp (3p)

 Continue to this page.


mbrlen(3p)

MBRLEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mbrlen - get number of bytes in a character (restartable)

SYNOPSIS

#include <wchar.h>

size_t mbrlen(const char *restrict s, size_t n,
mbstate_t *restrict ps);

DESCRIPTION

If s is not a null pointer, mbrlen() shall determine the number of bytes constituting the character pointed to by s. It shall be equivalent to:

mbstate_t internal;
mbrtowc(NULL, s, n, ps != NULL ? ps : &internal);

If ps is a null pointer, the mbrlen() function shall use its own internal mbstate_t object, which is initialized at program start-up to the initial conversion state. Otherwise, the mbstate_t object pointed to by ps shall be used to completely describe the current conversion state of the associated character sequence. The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls mbrlen().

The behavior of this function is affected by the LC_CTYPE category of the current locale.

RETURN VALUE

The mbrlen() function shall return the first of the following that applies:

0
If the next n or fewer bytes complete the character that corresponds to the null wide character.
positive
If the next n or fewer bytes complete a valid character; the value returned shall be the number of bytes that complete the character.
(size_t)-2
If the next n bytes contribute to an incomplete but potentially valid character, and all n bytes have been processed. When n has at least the value of the {MB_CUR_MAX} macro, this case can only occur if s points at a sequence of redundant shift sequences (for implementations with state-dependent encodings).
(size_t)-1
If an encoding error occurs, in which case the next n or fewer bytes do not contribute to a complete and valid character. In this case, [EILSEQ] shall be stored in errno and the conversion state is undefined.

ERRORS

The mbrlen() function may fail if:

EINVAL
ps points to an object that contains an invalid conversion state.
EILSEQ
Invalid character sequence is detected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mbsinit() , mbrtowc() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atan(3p)

ATAN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

atan, atanf, atanl - arc tangent function

SYNOPSIS

#include <math.h>

double atan(double x);
float atanf(float x);
long double atanl(long double x);

DESCRIPTION

These functions shall compute the principal value of the arc tangent of their argument x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the arc tangent of x in the range [-pi/2,pi/2] radians.

If x is NaN, a NaN shall be returned.

If x is ±0, x shall be returned.

If x is ±Inf, ±pi/2 shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions may fail if:

Range Error
The value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

atan2() , feclearexcept() , fetestexcept() , isnan() , tan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fpathconf (3p)

 Continue to this page.


rename(3p)

RENAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

rename - rename a file

SYNOPSIS

#include <stdio.h>

int rename(const char *old, const char *new);

DESCRIPTION

The rename() function shall change the name of a file. The old argument points to the pathname of the file to be renamed. The new argument points to the new pathname of the file.

If either the old or new argument names a symbolic link, rename() shall operate on the symbolic link itself, and shall not resolve the last component of the argument. If the old argument and the new argument resolve to the same existing file, rename() shall return successfully and perform no other action.

If the old argument points to the pathname of a file that is not a directory, the new argument shall not point to the pathname of a directory. If the link named by the new argument exists, it shall be removed and old renamed to new. In this case, a link named new shall remain visible to other processes throughout the renaming operation and refer either to the file referred to by new or old before the operation began. Write access permission is required for both the directory containing old and the directory containing new.

If the old argument points to the pathname of a directory, the new argument shall not point to the pathname of a file that is not a directory. If the directory named by the new argument exists, it shall be removed and old renamed to new. In this case, a link named new shall exist throughout the renaming operation and shall refer either to the directory referred to by new or old before the operation began. If new names an existing directory, it shall be required to be an empty directory.

If the old argument points to a pathname of a symbolic link, the symbolic link shall be renamed. If the new argument points to a pathname of a symbolic link, the symbolic link shall be removed.

The new pathname shall not contain a path prefix that names old. Write access permission is required for the directory containing old and the directory containing new. If the old argument points to the pathname of a directory, write access permission may be required for the directory named by old, and, if it exists, the directory named by new.

If the link named by the new argument exists and the file's link count becomes 0 when it is removed and no process has the file open, the space occupied by the file shall be freed and the file shall no longer be accessible. If one or more processes have the file open when the last link is removed, the link shall be removed before rename() returns, but the removal of the file contents shall be postponed until all references to the file are closed.

Upon successful completion, rename() shall mark for update the st_ctime and st_mtime fields of the parent directory of each file.

If the rename() function fails for any reason other than [EIO], any file named by new shall be unaffected.

RETURN VALUE

Upon successful completion, rename() shall return 0; otherwise, -1 shall be returned, errno shall be set to indicate the error, and neither the file named by old nor the file named by new shall be changed or created.

ERRORS

The rename() function shall fail if:

EACCES
A component of either path prefix denies search permission; or one of the directories containing old or new denies write permissions; or, write permission is required and is denied for a directory pointed to by the old or new arguments.
EBUSY
The directory named by old or new is currently in use by the system or another process, and the implementation considers this an error.
EEXIST or ENOTEMPTY

The link named by new is a directory that is not an empty directory.

EINVAL
The new directory pathname contains a path prefix that names the old directory.
EIO
A physical I/O error has occurred.
EISDIR
The new argument points to a directory and the old argument points to a file that is not a directory.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMLINK
The file named by old is a directory, and the link count of the parent directory of new would exceed {LINK_MAX}.
ENAMETOOLONG

The length of the old or new argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

ENOENT
The link named by old does not name an existing file, or either old or new points to an empty string.
ENOSPC
The directory that would contain new cannot be extended.
ENOTDIR
A component of either path prefix is not a directory; or the old argument names a directory and new argument names a non-directory file.
EPERM or EACCES

The S_ISVTX flag is set on the directory containing the file referred to by old and the caller is not the file owner, nor is the caller the directory owner, nor does the caller have appropriate privileges; or new refers to an existing file, the S_ISVTX flag is set on the directory containing this file, and the caller is not the file owner, nor is the caller the directory owner, nor does the caller have appropriate privileges.

EROFS
The requested operation requires writing in a directory on a read-only file system.
EXDEV
The links named by new and old are on different file systems and the implementation does not support links between file systems.

The rename() function may fail if:

EBUSY
The file named by the old or new arguments is a named STREAM.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG

As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

ETXTBSY
The file to be renamed is a pure procedure (shared text) file that is being executed.

The following sections are informative.

EXAMPLES

Renaming a File

The following example shows how to rename a file named /home/cnd/mod1 to /home/cnd/mod2.

#include <stdio.h>

int status;
...
status = rename("/home/cnd/mod1", "/home/cnd/mod2");

APPLICATION USAGE

Some implementations mark for update the st_ctime field of renamed files and some do not. Applications which make use of the st_ctime field may behave differently with respect to renamed files unless they are designed to allow for either behavior.

RATIONALE

This rename() function is equivalent for regular files to that defined by the ISO C standard. Its inclusion here expands that definition to include actions on directories and specifies behavior when the new parameter names a file that already exists. That specification requires that the action of the function be atomic.

One of the reasons for introducing this function was to have a means of renaming directories while permitting implementations to prohibit the use of link() and unlink() with directories, thus constraining links to directories to those made by mkdir().

The specification that if old and new refer to the same file is intended to guarantee that:

rename("x", "x");

does not remove the file.

Renaming dot or dot-dot is prohibited in order to prevent cyclical file system paths.

See also the descriptions of [ENOTEMPTY] and [ENAMETOOLONG] in rmdir() and [EBUSY] in unlink() . For a discussion of [EXDEV], see link() .

FUTURE DIRECTIONS

None.

SEE ALSO

link() , rmdir() , symlink() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


feraiseexcept(3p)

FERAISEEXCEPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

feraiseexcept - raise floating-point exception

SYNOPSIS

#include <fenv.h>

int feraiseexcept(int excepts);

DESCRIPTION

The feraiseexcept() function shall attempt to raise the supported floating-point exceptions represented by the argument excepts. The order in which these floating-point exceptions are raised is unspecified. Whether the feraiseexcept() function additionally raises the inexact floating-point exception whenever it raises the overflow or underflow floating-point exception is implementation-defined.

RETURN VALUE

If the argument is zero or if all the specified exceptions were successfully raised, feraiseexcept() shall return zero. Otherwise, it shall return a non-zero value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The effect is intended to be similar to that of floating-point exceptions raised by arithmetic operations. Hence, enabled traps for floating-point exceptions raised by this function are taken.

RATIONALE

Raising overflow or underflow is allowed to also raise inexact because on some architectures the only practical way to raise an exception is to execute an instruction that has the exception as a side effect. The function is not restricted to accept only valid coincident expressions for atomic operations, so the function can be used to raise exceptions accrued over several operations.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fegetexceptflag() , fesetexceptflag() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cfgetispeed(3p)

CFGETISPEED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cfgetispeed - get input baud rate

SYNOPSIS

#include <termios.h>

speed_t cfgetispeed(const struct termios *termios_p);

DESCRIPTION

The cfgetispeed() function shall extract the input baud rate from the termios structure to which the termios_p argument points.

This function shall return exactly the value in the termios data structure, without interpretation.

RETURN VALUE

Upon successful completion, cfgetispeed() shall return a value of type speed_t representing the input baud rate.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The term "baud" is used historically here, but is not technically correct. This is properly "bits per second", which may not be the same as baud. However, the term is used because of the historical usage and understanding.

The cfgetospeed(), cfgetispeed(), cfsetospeed(), and cfsetispeed() functions do not take arguments as numbers, but rather as symbolic names. There are two reasons for this:

1.
Historically, numbers were not used because of the way the rate was stored in the data structure. This is retained even though a function is now used.

2.
More importantly, only a limited set of possible rates is at all portable, and this constrains the application to that set.

There is nothing to prevent an implementation accepting as an extension a number (such as 126), and since the encoding of the Bxxx symbols is not specified, this can be done to avoid introducing ambiguity.

Setting the input baud rate to zero was a mechanism to allow for split baud rates. Clarifications in this volume of IEEE Std 1003.1-2001 have made it possible to determine whether split rates are supported and to support them without having to treat zero as a special case. Since this functionality is also confusing, it has been declared obsolescent. The 0 argument referred to is the literal constant 0, not the symbolic constant B0. This volume of IEEE Std 1003.1-2001 does not preclude B0 from being defined as the value 0; in fact, implementations would likely benefit from the two being equivalent. This volume of IEEE Std 1003.1-2001 does not fully specify whether the previous cfsetispeed() value is retained after a tcgetattr() as the actual value or as zero. Therefore, conforming applications should always set both the input speed and output speed when setting either.

In historical implementations, the baud rate information is traditionally kept in c_cflag. Applications should be written to presume that this might be the case (and thus not blindly copy c_cflag), but not to rely on it in case it is in some other field of the structure. Setting the c_cflag field absolutely after setting a baud rate is a non-portable action because of this. In general, the unused parts of the flag fields might be used by the implementation and should not be blindly copied from the descriptions of one terminal device to another.

FUTURE DIRECTIONS

None.

SEE ALSO

cfgetospeed() , cfsetispeed() , cfsetospeed() , tcgetattr() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getpwnam(3p)

GETPWNAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getpwnam, getpwnam_r - search user database for a name

SYNOPSIS

#include <pwd.h>

struct passwd *getpwnam(const char *name);

int getpwnam_r(const char *name, struct passwd *pwd, char *buffer,
size_t bufsize, struct passwd **result);

DESCRIPTION

The getpwnam() function shall search the user database for an entry with a matching name.

The getpwnam() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

Applications wishing to check for error situations should set errno to 0 before calling getpwnam(). If getpwnam() returns a null pointer and errno is non-zero, an error occurred.

The getpwnam_r() function shall update the passwd structure pointed to by pwd and store a pointer to that structure at the location pointed to by result. The structure shall contain an entry from the user database with a matching name. Storage referenced by the structure is allocated from the memory provided with the buffer parameter, which is bufsize bytes in size. The maximum size needed for this buffer can be determined with the {_SC_GETPW_R_SIZE_MAX} sysconf() parameter. A NULL pointer shall be returned at the location pointed to by result on error or if the requested entry is not found.

RETURN VALUE

The getpwnam() function shall return a pointer to a struct passwd with the structure as defined in <pwd.h> with a matching entry if found. A null pointer shall be returned if the requested entry is not found, or an error occurs. On error, errno shall be set to indicate the error.

The return value may point to a static area which is overwritten by a subsequent call to getpwent(), getpwnam(), or getpwuid().

If successful, the getpwnam_r() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The getpwnam() and getpwnam_r() functions may fail if:

EIO
An I/O error has occurred.
EINTR
A signal was caught during getpwnam().
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.

The getpwnam_r() function may fail if:

ERANGE
Insufficient storage was supplied via buffer and bufsize to contain the data to be referenced by the resulting passwd structure.

The following sections are informative.

EXAMPLES

Getting an Entry for the Login Name

The following example uses the getlogin() function to return the name of the user who logged in; this information is passed to the getpwnam() function to get the user database entry for that user.

#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
...
char *lgn;
struct passwd *pw;
...
if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL) {
    fprintf(stderr, "Get of user information failed.\n"); exit(1);
}
...

APPLICATION USAGE

Three names associated with the current process can be determined: getpwuid( geteuid()) returns the name associated with the effective user ID of the process; getlogin() returns the name associated with the current login activity; and getpwuid( getuid()) returns the name associated with the real user ID of the process.

The getpwnam_r() function is thread-safe and returns values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getpwuid() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <pwd.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


asinf (3p)

 Continue to this page.


asinh(3p)

ASINH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

asinh, asinhf, asinhl - inverse hyperbolic sine functions

SYNOPSIS

#include <math.h>

double asinh(double x);
float asinhf(float x);
long double asinhl(long double x);

DESCRIPTION

These functions shall compute the inverse hyperbolic sine of their argument x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the inverse hyperbolic sine of their argument.

If x is NaN, a NaN shall be returned.

If x is ±0, or ±Inf, x shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions may fail if:

Range Error
The value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , sinh() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


copysign(3p)

COPYSIGN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

copysign, copysignf, copysignl - number manipulation function

SYNOPSIS

#include <math.h>

double copysign(double x, double y);
float copysignf(float x, float y);
long double copysignl(long double x, long double y);

DESCRIPTION

These functions shall produce a value with the magnitude of x and the sign of y. On implementations that represent a signed zero but do not treat negative zero consistently in arithmetic operations, these functions regard the sign of zero as positive.

RETURN VALUE

Upon successful completion, these functions shall return a value with the magnitude of x and the sign of y.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

signbit() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


dirname(3p)

DIRNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

dirname - report the parent directory name of a file pathname

SYNOPSIS

#include <libgen.h>

char *dirname(char *path);

DESCRIPTION

The dirname() function shall take a pointer to a character string that contains a pathname, and return a pointer to a string that is a pathname of the parent directory of that file. Trailing '/' characters in the path are not counted as part of the path.

If path does not contain a '/' , then dirname() shall return a pointer to the string "." . If path is a null pointer or points to an empty string, dirname() shall return a pointer to the string "." .

The dirname() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

The dirname() function shall return a pointer to a string that is the parent directory of path. If path is a null pointer or points to an empty string, a pointer to a string "." is returned.

The dirname() function may modify the string pointed to by path, and may return a pointer to static storage that may then be overwritten by subsequent calls to dirname().

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following code fragment reads a pathname, changes the current working directory to the parent directory, and opens the file.

char path[PATH_MAX], *pathcopy;
int fd;
fgets(path, PATH_MAX, stdin);
pathcopy = strdup(path);
chdir(dirname(pathcopy));
fd = open(basename(path), O_RDONLY);

Sample Input and Output Strings for dirname()

In the following table, the input string is the value pointed to by path, and the output string is the return value of the dirname() function.
Input String | Output String
"/usr/lib" | "/usr"
"/usr/" | "/"
"usr" | "."
"/" | "/"
"." | "."
".." | "."

Changing the Current Directory to the Parent Directory

The following program fragment reads a pathname, changes the current working directory to the parent directory, and opens the file.

#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <libgen.h>
...
char path[PATH_MAX], *pathcopy;
int fd;
...
fgets(path, PATH_MAX, stdin);
pathcopy = strdup(path);
chdir(dirname(pathcopy));
fd = open(basename(path), O_RDONLY);

APPLICATION USAGE

The dirname() and basename() functions together yield a complete pathname. The expression dirname(path) obtains the pathname of the directory where basename(path) is found.

Since the meaning of the leading "//" is implementation-defined, dirname(" //foo) may return either "//" or '/' (but nothing else).

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

basename() , the Base Definitions volume of IEEE Std 1003.1-2001, <libgen.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


asinl (3p)

 Continue to this page.


bind(3p)

BIND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

bind - bind a name to a socket

SYNOPSIS

#include <sys/socket.h>

int bind(int socket, const struct sockaddr *address,
socklen_t address_len);

DESCRIPTION

The bind() function shall assign a local socket address address to a socket identified by descriptor socket that has no local socket address assigned. Sockets created with the socket() function are initially unnamed; they are identified only by their address family.

The bind() function takes the following arguments:

socket
Specifies the file descriptor of the socket to be bound.
address
Points to a sockaddr structure containing the address to be bound to the socket. The length and format of the address depend on the address family of the socket.
address_len
Specifies the length of the sockaddr structure pointed to by the address argument.

The socket specified by socket may require the process to have appropriate privileges to use the bind() function.

RETURN VALUE

Upon successful completion, bind() shall return 0; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The bind() function shall fail if:

EADDRINUSE
The specified address is already in use.
EADDRNOTAVAIL
The specified address is not available from the local machine.
EAFNOSUPPORT
The specified address is not a valid address for the address family of the specified socket.
EBADF
The socket argument is not a valid file descriptor.
EINVAL
The socket is already bound to an address, and the protocol does not support binding to a new address; or the socket has been shut down.
ENOTSOCK
The socket argument does not refer to a socket.
EOPNOTSUPP
The socket type of the specified socket does not support binding to an address.

If the address family of the socket is AF_UNIX, then bind() shall fail if:

EACCES
A component of the path prefix denies search permission, or the requested name requires writing in a directory with a mode that denies write permission.
EDESTADDRREQ or EISDIR
The address argument is a null pointer.
EIO
An I/O error occurred.
ELOOP
A loop exists in symbolic links encountered during resolution of the pathname in address.
ENAMETOOLONG
A component of a pathname exceeded {NAME_MAX} characters, or an entire pathname exceeded {PATH_MAX} characters.
ENOENT
A component of the pathname does not name an existing file or the pathname is an empty string.
ENOTDIR
A component of the path prefix of the pathname in address is not a directory.
EROFS
The name would reside on a read-only file system.

The bind() function may fail if:

EACCES
The specified address is protected and the current user does not have permission to bind to it.
EINVAL
The address_len argument is not a valid length for the address family.
EISCONN
The socket is already connected.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the pathname in address.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.
ENOBUFS
Insufficient resources were available to complete the call.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

An application program can retrieve the assigned socket name with the getsockname() function.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

connect() , getsockname() , listen() , socket() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_setpgroup (3p)

 Continue to this page.


posix_trace_attr_destroy (3p)

 Continue to this page.


pthread_mutexattr_setprotocol (3p)

 Continue to this page.


va_start (3p)

 Continue to this page.


atof(3p)

ATOF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

atof - convert a string to a double-precision number

SYNOPSIS

#include <stdlib.h>

double atof(const char *str);

DESCRIPTION

The call atof(str) shall be equivalent to:

strtod(str,(char **)NULL),

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

RETURN VALUE

The atof() function shall return the converted value if the value can be represented.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The atof() function is subsumed by strtod() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtod() should be used because atof() is not required to perform any error checking.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strtod() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atoi(3p)

ATOI

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

atoi - convert a string to an integer

SYNOPSIS

#include <stdlib.h>

int atoi(const char *str);

DESCRIPTION

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

RETURN VALUE

The atoi() function shall return the converted value if the value can be represented.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Converting an Argument

The following example checks for proper usage of the program. If there is an argument and the decimal conversion of this argument (obtained using atoi()) is greater than 0, then the program has a valid number of minutes to wait for an event.

#include <stdlib.h>
#include <stdio.h>
...
int minutes_to_event;
...
if (argc < 2 || ((minutes_to_event = atoi (argv[1]))) <= 0) {
   fprintf(stderr, "Usage: %s minutes\n", argv[0]); exit(1);
}
...

APPLICATION USAGE

The atoi() function is subsumed by strtol() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtol() should be used because atoi() is not required to perform any error checking.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strtol() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atol(3p)

ATOL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

atol, atoll - convert a string to a long integer

SYNOPSIS

#include <stdlib.h>

long atol(const char *str);
long long atoll(const char *nptr);

DESCRIPTION

The call atol(str) shall be equivalent to:

strtol(str, (char **)NULL, 10)

The call atoll(str) shall be equivalent to:

strtoll(nptr, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

RETURN VALUE

These functions shall return the converted value if the value can be represented.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The atol() function is subsumed by strtol() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtol() should be used because atol() is not required to perform any error checking.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strtol() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ptsname(3p)

PTSNAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ptsname - get name of the slave pseudo-terminal device

SYNOPSIS

#include <stdlib.h>

char *ptsname(int fildes);

DESCRIPTION

The ptsname() function shall return the name of the slave pseudo-terminal device associated with a master pseudo-terminal device. The fildes argument is a file descriptor that refers to the master device. The ptsname() function shall return a pointer to a string containing the pathname of the corresponding slave device.

The ptsname() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, ptsname() shall return a pointer to a string which is the name of the pseudo-terminal slave device. Upon failure, ptsname() shall return a null pointer. This could occur if fildes is an invalid file descriptor or if the slave device name does not exist in the file system.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The value returned may point to a static data area that is overwritten by each call to ptsname().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

grantpt() , open() , ttyname() , unlockpt() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcsncat(3p)

WCSNCAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsncat - concatenate a wide-character string with part of another

SYNOPSIS

#include <wchar.h>

wchar_t *wcsncat(wchar_t *restrict ws1, const wchar_t *restrict ws2,
size_t n);

DESCRIPTION

The wcsncat() function shall append not more than n wide-character codes (a null wide-character code and wide-character codes that follow it are not appended) from the array pointed to by ws2 to the end of the wide-character string pointed to by ws1. The initial wide-character code of ws2 shall overwrite the null wide-character code at the end of ws1. A terminating null wide-character code shall always be appended to the result. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The wcsncat() function shall return ws1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcscat() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getprotobyname (3p)

 Continue to this page.


fmaxf (3p)

 Continue to this page.


closelog (3p)

 Continue to this page.


mq_notify(3p)

MQ_NOTIFY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_notify - notify process that a message is available (REALTIME)

SYNOPSIS

#include <mqueue.h>

int mq_notify(mqd_t mqdes, const struct sigevent *notification);

DESCRIPTION

If the argument notification is not NULL, this function shall register the calling process to be notified of message arrival at an empty message queue associated with the specified message queue descriptor, mqdes. The notification specified by the notification argument shall be sent to the process when the message queue transitions from empty to non-empty. At any time, only one process may be registered for notification by a message queue. If the calling process or any other process has already registered for notification of message arrival at the specified message queue, subsequent attempts to register for that message queue shall fail.

If notification is NULL and the process is currently registered for notification by the specified message queue, the existing registration shall be removed.

When the notification is sent to the registered process, its registration shall be removed. The message queue shall then be available for registration.

If a process has registered for notification of message arrival at a message queue and some thread is blocked in mq_receive() waiting to receive a message when a message arrives at the queue, the arriving message shall satisfy the appropriate mq_receive(). The resulting behavior is as if the message queue remains empty, and no notification shall be sent.

RETURN VALUE

Upon successful completion, the mq_notify() function shall return a value of zero; otherwise, the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The mq_notify() function shall fail if:

EBADF
The mqdes argument is not a valid message queue descriptor.
EBUSY
A process is already registered for notification by the message queue.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_open() , mq_send() , mq_timedsend() , msgctl() , msgget() , msgrcv() , msgsnd() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmaxl (3p)

 Continue to this page.


posix_trace_getnext_event(3p)

POSIX_TRACE_GETNEXT_EVENT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_trace_getnext_event, posix_trace_timedgetnext_event, posix_trace_trygetnext_event - retrieve a trace event (TRACING)

SYNOPSIS

#include <sys/types.h>
#include <trace.h>

int posix_trace_getnext_event(trace_id_t trid,
struct posix_trace_event_info *restrict event,
void *restrict data, size_t num_bytes,
size_t *restrict data_len, int *restrict unavailable);

int posix_trace_timedgetnext_event(trace_id_t trid,
struct posix_trace_event_info *restrict event,
void *restrict data, size_t num_bytes,
size_t *restrict data_len, int *restrict unavailable,
const struct timespec *restrict abs_timeout);

int posix_trace_trygetnext_event(trace_id_t trid,
struct posix_trace_event_info *restrict event,
void *restrict data, size_t num_bytes,
size_t *restrict data_len, int *restrict unavailable);

DESCRIPTION

The posix_trace_getnext_event() function shall report a recorded trace event either from an active trace stream without log or a pre-recorded trace stream identified by the trid argument. The posix_trace_trygetnext_event() function shall report a recorded trace event from an active trace stream without log identified by the trid argument.

The trace event information associated with the recorded trace event shall be copied by the function into the structure pointed to by the argument event and the data associated with the trace event shall be copied into the buffer pointed to by the data argument.

The posix_trace_getnext_event() function shall block if the trid argument identifies an active trace stream and there is currently no trace event ready to be retrieved. When returning, if a recorded trace event was reported, the variable pointed to by the unavailable argument shall be set to zero. Otherwise, the variable pointed to by the unavailable argument shall be set to a value different from zero.

The posix_trace_timedgetnext_event() function shall attempt to get another trace event from an active trace stream without log, as in the posix_trace_getnext_event() function. However, if no trace event is available from the trace stream, the implied wait shall be terminated when the timeout specified by the argument abs_timeout expires, and the function shall return the error [ETIMEDOUT].

The timeout shall expire when the absolute time specified by abs_timeout passes, as measured by the clock upon which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already passed at the time of the call.

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock; if the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function. The resolution of the timeout shall be the resolution of the clock on which it is based. The timespec data type is defined in the <time.h> header.

Under no circumstance shall the function fail with a timeout if a trace event is immediately available from the trace stream. The validity of the abs_timeout argument need not be checked if a trace event is immediately available from the trace stream.

The behavior of this function for a pre-recorded trace stream is unspecified.

The posix_trace_trygetnext_event() function shall not block. This function shall return an error if the trid argument identifies a pre-recorded trace stream. If a recorded trace event was reported, the variable pointed to by the unavailable argument shall be set to zero. Otherwise, if no trace event was reported, the variable pointed to by the unavailable argument shall be set to a value different from zero.

The argument num_bytes shall be the size of the buffer pointed to by the data argument. The argument data_len reports to the application the length in bytes of the data record just transferred. If num_bytes is greater than or equal to the size of the data associated with the trace event pointed to by the event argument, all the recorded data shall be transferred. In this case, the truncation-status member of the trace event structure shall be either POSIX_TRACE_NOT_TRUNCATED, if the trace event data was recorded without truncation while tracing, or POSIX_TRACE_TRUNCATED_RECORD, if the trace event data was truncated when it was recorded. If the num_bytes argument is less than the length of recorded trace event data, the data transferred shall be truncated to a length of num_bytes, the value stored in the variable pointed to by data_len shall be equal to num_bytes, and the truncation-status member of the event structure argument shall be set to POSIX_TRACE_TRUNCATED_READ (see the posix_trace_event_info structure defined in <trace.h>).

The report of a trace event shall be sequential starting from the oldest recorded trace event. Trace events shall be reported in the order in which they were generated, up to an implementation-defined time resolution that causes the ordering of trace events occurring very close to each other to be unknown. Once reported, a trace event cannot be reported again from an active trace stream. Once a trace event is reported from an active trace stream without log, the trace stream shall make the resources associated with that trace event available to record future generated trace events.

RETURN VALUE

Upon successful completion, these functions shall return a value of zero. Otherwise, they shall return the corresponding error number.

If successful, these functions store:

*
The recorded trace event in the object pointed to by event

*
The trace event information associated with the recorded trace event in the object pointed to by data

*
The length of this trace event information in the object pointed to by data_len

*
The value of zero in the object pointed to by unavailable

ERRORS

These functions shall fail if:

EINVAL
The trace stream identifier argument trid is invalid.

The posix_trace_getnext_event() and posix_trace_timedgetnext_event() functions shall fail if:

EINTR
The operation was interrupted by a signal, and so the call had no effect.

The posix_trace_trygetnext_event() function shall fail if:

EINVAL
The trace stream identifier argument trid does not correspond to an active trace stream.

The posix_trace_timedgetnext_event() function shall fail if:

EINVAL
There is no trace event immediately available from the trace stream, and the timeout argument is invalid.
ETIMEDOUT
No trace event was available from the trace stream before the specified timeout timeout expired.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_trace_create() , posix_trace_open() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <trace.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isless(3p)

ISLESS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isless - test if x is less than y

SYNOPSIS

#include <math.h>

int isless(real-floating x, real-floating y);

DESCRIPTION

The isless() macro shall determine whether its first argument is less than its second argument. The value of isless( x, y) shall be equal to (x) < (y); however, unlike (x) < (y), isless( x, y) shall not raise the invalid floating-point exception when x and y are unordered.

RETURN VALUE

Upon successful completion, the isless() macro shall return the value of (x) < (y).

If x or y is NaN, 0 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values, exactly one of the relationships (less, greater, and equal) is true. Relational operators may raise the invalid floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. This macro is a quiet (non-floating-point exception raising) version of a relational operator. It facilitates writing efficient code that accounts for NaNs without suffering the invalid floating-point exception. In the SYNOPSIS section, real-floating indicates that the argument shall be an expression of real-floating type.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isgreater() , isgreaterequal() , islessequal() , islessgreater() , isunordered() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutexattr_setpshared (3p)

 Continue to this page.


longjmp(3p)

LONGJMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

longjmp - non-local goto

SYNOPSIS

#include <setjmp.h>

void longjmp(jmp_buf env, int val);

DESCRIPTION

The longjmp() function shall restore the environment saved by the most recent invocation of setjmp() in the same thread, with the corresponding jmp_buf argument. If there is no such invocation, or if the function containing the invocation of setjmp() has terminated execution in the interim, or if the invocation of setjmp() was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined. It is unspecified whether longjmp() restores the signal mask, leaves the signal mask unchanged, or restores it to its value at the time setjmp() was called.

All accessible objects have values, and all other components of the abstract machine have state (for example, floating-point status flags and open files), as of the time longjmp() was called, except that the values of objects of automatic storage duration are unspecified if they meet all the following conditions:

*
They are local to the function containing the corresponding setjmp() invocation.

*
They do not have volatile-qualified type.

*
They are changed between the setjmp() invocation and longjmp() call.

As it bypasses the usual function call and return mechanisms, longjmp() shall execute correctly in contexts of interrupts, signals, and any of their associated functions. However, if longjmp() is invoked from a nested signal handler (that is, from a function invoked as a result of a signal raised during the handling of another signal), the behavior is undefined.

The effect of a call to longjmp() where initialization of the jmp_buf structure was not performed in the calling thread is undefined.

RETURN VALUE

After longjmp() is completed, program execution continues as if the corresponding invocation of setjmp() had just returned the value specified by val. The longjmp() function shall not cause setjmp() to return 0; if val is 0, setjmp() shall return 1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications whose behavior depends on the value of the signal mask should not use longjmp() and setjmp(), since their effect on the signal mask is unspecified, but should instead use the siglongjmp() and sigsetjmp() functions (which can save and restore the signal mask under application control).

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

setjmp() , sigaction() , siglongjmp() , sigsetjmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <setjmp.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ispunct(3p)

ISPUNCT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ispunct - test for a punctuation character

SYNOPSIS

#include <ctype.h>

int ispunct(int c);

DESCRIPTION

The ispunct() function shall test whether c is a character of class punct in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is an int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The ispunct() function shall return non-zero if c is a punctuation character; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


islessgreater(3p)

ISLESSGREATER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

islessgreater - test if x is less than or greater than y

SYNOPSIS

#include <math.h>

int islessgreater(real-floating x, real-floating y);

DESCRIPTION

The islessgreater() macro shall determine whether its first argument is less than or greater than its second argument. The islessgreater( x, y) macro is similar to (x) < (y) || (x) > (y); however, islessgreater( x, y) shall not raise the invalid floating-point exception when x and y are unordered (nor shall it evaluate x and y twice).

RETURN VALUE

Upon successful completion, the islessgreater() macro shall return the value of (x) < (y) || (x) > (y).

If x or y is NaN, 0 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The relational and equality operators support the usual mathematical relationships between numeric values. For any ordered pair of numeric values, exactly one of the relationships (less, greater, and equal) is true. Relational operators may raise the invalid floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. This macro is a quiet (non-floating-point exception raising) version of a relational operator. It facilitates writing efficient code that accounts for NaNs without suffering the invalid floating-point exception. In the SYNOPSIS section, real-floating indicates that the argument shall be an expression of real-floating type.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isgreater() , isgreaterequal() , isless() , islessequal() , isunordered() , the Base Definitions volume of IEEE Std 1003.1-2001 <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fattach(3p)

FATTACH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fattach - attach a STREAMS-based file descriptor to a file in the file system name space (STREAMS)

SYNOPSIS

#include <stropts.h>

int fattach(int fildes, const char *path);

DESCRIPTION

The fattach() function shall attach a STREAMS-based file descriptor to a file, effectively associating a pathname with fildes. The application shall ensure that the fildes argument is a valid open file descriptor associated with a STREAMS file. The path argument points to a pathname of an existing file. The application shall have the appropriate privileges or be the owner of the file named by path and have write permission. A successful call to fattach() shall cause all pathnames that name the file named by path to name the STREAMS file associated with fildes, until the STREAMS file is detached from the file. A STREAMS file can be attached to more than one file and can have several pathnames associated with it.

The attributes of the named STREAMS file shall be initialized as follows: the permissions, user ID, group ID, and times are set to those of the file named by path, the number of links is set to 1, and the size and device identifier are set to those of the STREAMS file associated with fildes. If any attributes of the named STREAMS file are subsequently changed (for example, by chmod()), neither the attributes of the underlying file nor the attributes of the STREAMS file to which fildes refers shall be affected.

File descriptors referring to the underlying file, opened prior to an fattach() call, shall continue to refer to the underlying file.

RETURN VALUE

Upon successful completion, fattach() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The fattach() function shall fail if:

EACCES
Search permission is denied for a component of the path prefix, or the process is the owner of path but does not have write permissions on the file named by path.
EBADF
The fildes argument is not a valid open file descriptor.
EBUSY
The file named by path is currently a mount point or has a STREAMS file attached to it.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The size of path exceeds {PATH_MAX} or a component of path is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The effective user ID of the process is not the owner of the file named by path and the process does not have appropriate privilege.

The fattach() function may fail if:

EINVAL
The fildes argument does not refer to a STREAMS file.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.
EXDEV
A link to a file on another file system was attempted.

The following sections are informative.

EXAMPLES

Attaching a File Descriptor to a File

In the following example, fd refers to an open STREAMS file. The call to fattach() associates this STREAM with the file /tmp/named-STREAM, such that any future calls to open /tmp/named-STREAM, prior to breaking the attachment via a call to fdetach(), will instead create a new file handle referring to the STREAMS file associated with fd.

#include <stropts.h>
...
    int fd;
    char *filename = "/tmp/named-STREAM";
    int ret;

    ret = fattach(fd, filename);

APPLICATION USAGE

The fattach() function behaves similarly to the traditional mount() function in the way a file is temporarily replaced by the root directory of the mounted file system. In the case of fattach(), the replaced file need not be a directory and the replacing file is a STREAMS file.

RATIONALE

The file attributes of a file which has been the subject of an fattach() call are specifically set because of an artefact of the original implementation. The internal mechanism was the same as for the mount() function. Since mount() is typically only applied to directories, the effects when applied to a regular file are a little surprising, especially as regards the link count which rigidly remains one, even if there were several links originally and despite the fact that all original links refer to the STREAM as long as the fattach() remains in effect.

FUTURE DIRECTIONS

None.

SEE ALSO

fdetach() , isastream() , the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


daylight (3p)

 Continue to this page.


clock_getres (3p)

 Continue to this page.


wcsncmp(3p)

WCSNCMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsncmp - compare part of two wide-character strings

SYNOPSIS

#include <wchar.h>

int wcsncmp(const wchar_t *ws1, const wchar_t *ws2, size_t n);

DESCRIPTION

The wcsncmp() function shall compare not more than n wide-character codes (wide-character codes that follow a null wide-character code are not compared) from the array pointed to by ws1 to the array pointed to by ws2.

The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of wide-character codes that differ in the objects being compared.

RETURN VALUE

Upon successful completion, wcsncmp() shall return an integer greater than, equal to, or less than 0, if the possibly null-terminated array pointed to by ws1 is greater than, equal to, or less than the possibly null-terminated array pointed to by ws2, respectively.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcscmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ualarm(3p)

UALARM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ualarm - set the interval timer

SYNOPSIS

#include <unistd.h>

useconds_t ualarm(useconds_t useconds, useconds_t interval);

DESCRIPTION

The ualarm() function shall cause the SIGALRM signal to be generated for the calling process after the number of realtime microseconds specified by the useconds argument has elapsed. When the interval argument is non-zero, repeated timeout notification occurs with a period in microseconds specified by the interval argument. If the notification signal, SIGALRM, is not caught or ignored, the calling process is terminated.

Implementations may place limitations on the granularity of timer values. For each interval timer, if the requested timer value requires a finer granularity than the implementation supports, the actual timer value shall be rounded up to the next supported value.

Interactions between ualarm() and any of the following are unspecified:

alarm()
nanosleep()
setitimer()
timer_create()
timer_delete()
timer_getoverrun()
timer_gettime()
timer_settime()
sleep()

RETURN VALUE

The ualarm() function shall return the number of microseconds remaining from the previous ualarm() call. If no timeouts are pending or if ualarm() has not previously been called, ualarm() shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications are recommended to use nanosleep() if the Timers option is supported, or setitimer(), timer_create(), timer_delete(), timer_getoverrun(), timer_gettime(), or timer_settime() instead of this function.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , nanosleep() , setitimer() , sleep() , timer_create() , timer_delete() , timer_getoverrun() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fprintf (3p)

 Continue to this page.


times(3p)

TIMES

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

times - get process and waited-for child process times

SYNOPSIS

#include <sys/times.h>

clock_t times(struct tms *buffer);

DESCRIPTION

The times() function shall fill the tms structure pointed to by buffer with time-accounting information. The tms structure is defined in <sys/times.h>.

All times are measured in terms of the number of clock ticks used.

The times of a terminated child process shall be included in the tms_cutime and tms_cstime elements of the parent when wait() or waitpid() returns the process ID of this terminated child. If a child process has not waited for its children, their times shall not be included in its times.

*
The tms_utime structure member is the CPU time charged for the execution of user instructions of the calling process.

*
The tms_stime structure member is the CPU time charged for execution by the system on behalf of the calling process.

*
The tms_cutime structure member is the sum of the tms_utime and tms_cutime times of the child processes.

*
The tms_cstime structure member is the sum of the tms_stime and tms_cstime times of the child processes.

RETURN VALUE

Upon successful completion, times() shall return the elapsed real time, in clock ticks, since an arbitrary point in the past (for example, system start-up time). This point does not change from one invocation of times() within the process to another. The return value may overflow the possible range of type clock_t. If times() fails, (clock_t)-1 shall be returned and errno set to indicate the error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Timing a Database Lookup

The following example defines two functions, start_clock() and end_clock(), that are used to time a lookup. It also defines variables of type clock_t and tms to measure the duration of transactions. The start_clock() function saves the beginning times given by the times() function. The end_clock() function gets the ending times and prints the difference between the two times.

#include <sys/times.h>
#include <stdio.h>
...
void start_clock(void);
void end_clock(char *msg);
...
static clock_t st_time;
static clock_t en_time;
static struct tms st_cpu;
static struct tms en_cpu;
...
void
start_clock()
{
    st_time = times(&st_cpu);
}

/* This example assumes that the result of each subtraction
   is within the range of values that can be represented in
   an integer type. */
void
end_clock(char *msg)
{
    en_time = times(&en_cpu);

    fputs(msg,stdout);
    printf("Real Time: %jd, User Time %jd, System Time %jd\n",
        (intmax_t)(en_time - st_time),
        (intmax_t)(en_cpu.tms_utime - st_cpu.tms_utime),
        (intmax_t)(en_cpu.tms_stime - st_cpu.tms_stime));
}

APPLICATION USAGE

Applications should use sysconf(_SC_CLK_TCK) to determine the number of clock ticks per second as it may vary from system to system.

RATIONALE

The accuracy of the times reported is intentionally left unspecified to allow implementations flexibility in design, from uniprocessor to multi-processor networks.

The inclusion of times of child processes is recursive, so that a parent process may collect the total times of all of its descendants. But the times of a child are only added to those of its parent when its parent successfully waits on the child. Thus, it is not guaranteed that a parent process can always see the total times of all its descendants; see also the discussion of the term ``realtime'' in alarm() .

If the type clock_t is defined to be a signed 32-bit integer, it overflows in somewhat more than a year if there are 60 clock ticks per second, or less than a year if there are 100. There are individual systems that run continuously for longer than that. This volume of IEEE Std 1003.1-2001 permits an implementation to make the reference point for the returned value be the start-up time of the process, rather than system start-up time.

The term ``charge'' in this context has nothing to do with billing for services. The operating system accounts for time used in this way. That information must be correct, regardless of how that information is used.

FUTURE DIRECTIONS

None.

SEE ALSO

alarm() , exec() , fork() , sysconf() , time() , wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/times.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcsncpy(3p)

WCSNCPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsncpy - copy part of a wide-character string

SYNOPSIS

#include <wchar.h>

wchar_t *wcsncpy(wchar_t *restrict ws1, const wchar_t *restrict ws2,
size_t n);

DESCRIPTION

The wcsncpy() function shall copy not more than n wide-character codes (wide-character codes that follow a null wide-character code are not copied) from the array pointed to by ws2 to the array pointed to by ws1. If copying takes place between objects that overlap, the behavior is undefined.

If the array pointed to by ws2 is a wide-character string that is shorter than n wide-character codes, null wide-character codes shall be appended to the copy in the array pointed to by ws1, until n wide-character codes in all are written.

RETURN VALUE

The wcsncpy() function shall return ws1; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If there is no null wide-character code in the first n wide-character codes of the array pointed to by ws2, the result is not null-terminated.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wcscpy() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


aio_fsync(3p)

AIO_FSYNC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio_fsync - asynchronous file synchronization (REALTIME)

SYNOPSIS

#include <aio.h>

int aio_fsync(int op, struct aiocb *aiocbp);

DESCRIPTION

The aio_fsync() function shall asynchronously force all I/O operations associated with the file indicated by the file descriptor aio_fildes member of the aiocb structure referenced by the aiocbp argument and queued at the time of the call to aio_fsync() to the synchronized I/O completion state. The function call shall return when the synchronization request has been initiated or queued to the file or device (even when the data cannot be synchronized immediately).

If op is O_DSYNC, all currently queued I/O operations shall be completed as if by a call to fdatasync(); that is, as defined for synchronized I/O data integrity completion. If op is O_SYNC, all currently queued I/O operations shall be completed as if by a call to fsync(); that is, as defined for synchronized I/O file integrity completion. If the aio_fsync() function fails, or if the operation queued by aio_fsync() fails, then, as for fsync() and fdatasync(), outstanding I/O operations are not guaranteed to have been completed.

If aio_fsync() succeeds, then it is only the I/O that was queued at the time of the call to aio_fsync() that is guaranteed to be forced to the relevant completion state. The completion of subsequent I/O on the file descriptor is not guaranteed to be completed in a synchronized fashion.

The aiocbp argument refers to an asynchronous I/O control block. The aiocbp value may be used as an argument to aio_error() and aio_return() in order to determine the error status and return status, respectively, of the asynchronous operation while it is proceeding. When the request is queued, the error status for the operation is [EINPROGRESS]. When all data has been successfully transferred, the error status shall be reset to reflect the success or failure of the operation. If the operation does not complete successfully, the error status for the operation shall be set to indicate the error. The aio_sigevent member determines the asynchronous notification to occur as specified in Signal Generation and Delivery when all operations have achieved synchronized I/O completion. All other members of the structure referenced by aiocbp are ignored. If the control block referenced by aiocbp becomes an illegal address prior to asynchronous I/O completion, then the behavior is undefined.

If the aio_fsync() function fails or aiocbp indicates an error condition, data is not guaranteed to have been successfully transferred.

RETURN VALUE

The aio_fsync() function shall return the value 0 to the calling process if the I/O operation is successfully queued; otherwise, the function shall return the value -1 and set errno to indicate the error.

ERRORS

The aio_fsync() function shall fail if:

EAGAIN
The requested asynchronous operation was not queued due to temporary resource limitations.
EBADF
The aio_fildes member of the aiocb structure referenced by the aiocbp argument is not a valid file descriptor open for writing.
EINVAL
This implementation does not support synchronized I/O for this file.
EINVAL
A value of op other than O_DSYNC or O_SYNC was specified.

In the event that any of the queued I/O operations fail, aio_fsync() shall return the error condition defined for read() and write(). The error is returned in the error status for the asynchronous fsync() operation, which can be retrieved using aio_error().

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The aio_fsync() function is part of the Asynchronous Input and Output option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fcntl() , fdatasync() , fsync() , open() , read() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


cabs(3p)

CABS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cabs, cabsf, cabsl - return a complex absolute value

SYNOPSIS

#include <complex.h>

double cabs(double complex z);
float cabsf(float complex z);
long double cabsl(long double complex z);

DESCRIPTION

These functions shall compute the complex absolute value (also called norm, modulus, or magnitude) of z.

RETURN VALUE

These functions shall return the complex absolute value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getrlimit(3p)

GETRLIMIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getrlimit, setrlimit - control maximum resource consumption

SYNOPSIS

#include <sys/resource.h>

int getrlimit(int resource, struct rlimit *rlp);
int setrlimit(int resource, const struct rlimit *rlp);

DESCRIPTION

The getrlimit() function shall get, and the setrlimit() function shall set, limits on the consumption of a variety of resources.

Each call to either getrlimit() or setrlimit() identifies a specific resource to be operated upon as well as a resource limit. A resource limit is represented by an rlimit structure. The rlim_cur member specifies the current or soft limit and the rlim_max member specifies the maximum or hard limit. Soft limits may be changed by a process to any value that is less than or equal to the hard limit. A process may (irreversibly) lower its hard limit to any value that is greater than or equal to the soft limit. Only a process with appropriate privileges can raise a hard limit. Both hard and soft limits can be changed in a single call to setrlimit() subject to the constraints described above.

The value RLIM_INFINITY, defined in <sys/resource.h>, shall be considered to be larger than any other limit value. If a call to getrlimit() returns RLIM_INFINITY for a resource, it means the implementation shall not enforce limits on that resource. Specifying RLIM_INFINITY as any resource limit value on a successful call to setrlimit() shall inhibit enforcement of that resource limit.

The following resources are defined:

RLIMIT_CORE
This is the maximum size of a core file, in bytes, that may be created by a process. A limit of 0 shall prevent the creation of a core file. If this limit is exceeded, the writing of a core file shall terminate at this size.
RLIMIT_CPU
This is the maximum amount of CPU time, in seconds, used by a process. If this limit is exceeded, SIGXCPU shall be generated for the process. If the process is catching or ignoring SIGXCPU, or all threads belonging to that process are blocking SIGXCPU, the behavior is unspecified.
RLIMIT_DATA
This is the maximum size of a process' data segment, in bytes. If this limit is exceeded, the malloc() function shall fail with errno set to [ENOMEM].
RLIMIT_FSIZE
This is the maximum size of a file, in bytes, that may be created by a process. If a write or truncate operation would cause this limit to be exceeded, SIGXFSZ shall be generated for the thread. If the thread is blocking, or the process is catching or ignoring SIGXFSZ, continued attempts to increase the size of a file from end-of-file to beyond the limit shall fail with errno set to [EFBIG].
RLIMIT_NOFILE
This is a number one greater than the maximum value that the system may assign to a newly-created descriptor. If this limit is exceeded, functions that allocate a file descriptor shall fail with errno set to [EMFILE]. This limit constrains the number of file descriptors that a process may allocate.
RLIMIT_STACK
This is the maximum size of a process' stack, in bytes. The implementation does not automatically grow the stack beyond this limit. If this limit is exceeded, SIGSEGV shall be generated for the thread. If the thread is blocking SIGSEGV, or the process is ignoring or catching SIGSEGV and has not made arrangements to use an alternate stack, the disposition of SIGSEGV shall be set to SIG_DFL before it is generated.
RLIMIT_AS
This is the maximum size of a process' total available memory, in bytes. If this limit is exceeded, the malloc() and mmap() functions shall fail with errno set to [ENOMEM]. In addition, the automatic stack growth fails with the effects outlined above.

When using the getrlimit() function, if a resource limit can be represented correctly in an object of type rlim_t, then its representation is returned; otherwise, if the value of the resource limit is equal to that of the corresponding saved hard limit, the value returned shall be RLIM_SAVED_MAX; otherwise, the value returned shall be RLIM_SAVED_CUR.

When using the setrlimit() function, if the requested new limit is RLIM_INFINITY, the new limit shall be "no limit''; otherwise, if the requested new limit is RLIM_SAVED_MAX, the new limit shall be the corresponding saved hard limit; otherwise, if the requested new limit is RLIM_SAVED_CUR, the new limit shall be the corresponding saved soft limit; otherwise, the new limit shall be the requested value. In addition, if the corresponding saved limit can be represented correctly in an object of type rlim_t then it shall be overwritten with the new limit.

The result of setting a limit to RLIM_SAVED_MAX or RLIM_SAVED_CUR is unspecified unless a previous call to getrlimit() returned that value as the soft or hard limit for the corresponding resource limit.

The determination of whether a limit can be correctly represented in an object of type rlim_t is implementation-defined. For example, some implementations permit a limit whose value is greater than RLIM_INFINITY and others do not.

The exec family of functions shall cause resource limits to be saved.

RETURN VALUE

Upon successful completion, getrlimit() and setrlimit() shall return 0. Otherwise, these functions shall return -1 and set errno to indicate the error.

ERRORS

The getrlimit() and setrlimit() functions shall fail if:

EINVAL
An invalid resource was specified; or in a setrlimit() call, the new rlim_cur exceeds the new rlim_max.
EPERM
The limit specified to setrlimit() would have raised the maximum limit value, and the calling process does not have appropriate privileges.

The setrlimit() function may fail if:

EINVAL
The limit specified cannot be lowered because current usage is already higher than the limit.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If a process attempts to set the hard limit or soft limit for RLIMIT_NOFILE to less than the value of {_POSIX_OPEN_MAX} from <limits.h>, unexpected behavior may occur.

If a process attempts to set the hard limit or soft limit for RLIMIT_NOFILE to less than the highest currently open file descriptor +1, unexpected behavior may occur.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fork() , malloc() , open() , sigaltstack() , sysconf() , ulimit() , the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>, <sys/resource.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atan2(3p)

ATAN2

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

atan2, atan2f, atan2l - arc tangent functions

SYNOPSIS

#include <math.h>

double atan2(double y, double x);
float atan2f(float y, float x);
long double atan2l(long double y, long double x);

DESCRIPTION

These functions shall compute the principal value of the arc tangent of y/ x, using the signs of both arguments to determine the quadrant of the return value.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the arc tangent of y/ x in the range [-pi,pi] radians.

If y is ±0 and x is < 0, ±pi shall be returned.

If y is ±0 and x is > 0, ±0 shall be returned.

If y is < 0 and x is ±0, -pi/2 shall be returned.

If y is > 0 and x is ±0, pi/2 shall be returned.

If x is 0, a pole error shall not occur.

If either x or y is NaN, a NaN shall be returned.

If the result underflows, a range error may occur and y/ x should be returned.

If y is ±0 and x is -0, ±pi shall be returned.

If y is ±0 and x is +0, ±0 shall be returned.

For finite values of ± y > 0, if x is -Inf, ±pi shall be returned.

For finite values of ± y > 0, if x is +Inf, ±0 shall be returned.

For finite values of x, if y is ±Inf, ±pi/2 shall be returned.

If y is ±Inf and x is -Inf, ±3pi/4 shall be returned.

If y is ±Inf and x is +Inf, ±pi/4 shall be returned.

If both arguments are 0, a domain error shall not occur.

ERRORS

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

atan() , feclearexcept() , fetestexcept() , isnan() , tan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


asctime_r (3p)

 Continue to this page.


fputwc(3p)

FPUTWC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fputwc - put a wide-character code on a stream

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

wint_t fputwc(wchar_t wc, FILE *stream);

DESCRIPTION

The fputwc() function shall write the character corresponding to the wide-character code wc to the output stream pointed to by stream, at the position indicated by the associated file-position indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the output stream. If an error occurs while writing the character, the shift state of the output file is left in an undefined state.

The st_ctime and st_mtime fields of the file shall be marked for update between the successful execution of fputwc() and the next successful completion of a call to fflush() or fclose() on the same stream or a call to exit() or abort().

RETURN VALUE

Upon successful completion, fputwc() shall return wc. Otherwise, it shall return WEOF, the error indicator for the stream shall be set, and errno shall be set to indicate the error.

ERRORS

The fputwc() function shall fail if either the stream is unbuffered or data in the stream's buffer needs to be written, and:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor underlying stream and the process would be delayed in the write operation.
EBADF
The file descriptor underlying stream is not a valid file descriptor open for writing.
EFBIG
An attempt was made to write to a file that exceeds the maximum file size or the process' file size limit.
EFBIG
The file is a regular file and an attempt was made to write at or beyond the offset maximum associated with the corresponding stream.
EILSEQ
The wide-character code wc does not correspond to a valid character.
EINTR
The write operation was terminated due to the receipt of a signal, and no data was transferred.
EIO
A physical I/O error has occurred, or the process is a member of a background process group attempting to write to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the process group of the process is orphaned. This error may also be returned under implementation-defined conditions.
ENOSPC
There was no free space remaining on the device containing the file.
EPIPE
An attempt is made to write to a pipe or FIFO that is not open for reading by any process. A SIGPIPE signal shall also be sent to the thread.

The fputwc() function may fail if:

ENOMEM
Insufficient storage space is available.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ferror() , fopen() , setbuf() , ulimit() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcsftime(3p)

WCSFTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcsftime - convert date and time to a wide-character string

SYNOPSIS

#include <wchar.h>

size_t wcsftime(wchar_t *restrict wcs, size_t maxsize,
const wchar_t *restrict format, const struct tm *restrict timeptr);

DESCRIPTION

The wcsftime() function shall be equivalent to the strftime() function, except that:

*
The argument wcs points to the initial element of an array of wide characters into which the generated output is to be placed.

*
The argument maxsize indicates the maximum number of wide characters to be placed in the output array.

*
The argument format is a wide-character string and the conversion specifications are replaced by corresponding sequences of wide characters.

*
The return value indicates the number of wide characters placed in the output array.

If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

If the total number of resulting wide-character codes including the terminating null wide-character code is no more than maxsize, wcsftime() shall return the number of wide-character codes placed into the array pointed to by wcs, not including the terminating null wide-character code. Otherwise, zero is returned and the contents of the array are unspecified.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strftime() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fegetround(3p)

FEGETROUND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fegetround, fesetround - get and set current rounding direction

SYNOPSIS

#include <fenv.h>

int fegetround(void);
int fesetround(int round);

DESCRIPTION

The fegetround() function shall get the current rounding direction.

The fesetround() function shall establish the rounding direction represented by its argument round. If the argument is not equal to the value of a rounding direction macro, the rounding direction is not changed.

RETURN VALUE

The fegetround() function shall return the value of the rounding direction macro representing the current rounding direction or a negative value if there is no such rounding direction macro or the current rounding direction is not determinable.

The fesetround() function shall return a zero value if and only if the requested rounding direction was established.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

The following example saves, sets, and restores the rounding direction, reporting an error and aborting if setting the rounding direction fails:

#include <fenv.h>
#include <assert.h>
void f(int round_dir)
{
    #pragma STDC FENV_ACCESS ON
    int save_round;
    int setround_ok;
    save_round = fegetround();
    setround_ok = fesetround(round_dir);
    assert(setround_ok == 0);
    /* ... */
    fesetround(save_round);
    /* ... */
}

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <fenv.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


if_indextoname(3p)

IF_INDEXTONAME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

if_indextoname - map a network interface index to its corresponding name

SYNOPSIS

#include <net/if.h>

char *if_indextoname(unsigned ifindex, char *ifname);

DESCRIPTION

The if_indextoname() function shall map an interface index to its corresponding name.

When this function is called, ifname shall point to a buffer of at least {IF_NAMESIZE} bytes. The function shall place in this buffer the name of the interface with index ifindex.

RETURN VALUE

If ifindex is an interface index, then the function shall return the value supplied in ifname, which points to a buffer now containing the interface name. Otherwise, the function shall return a NULL pointer and set errno to indicate the error.

ERRORS

The if_indextoname() function shall fail if:

ENXIO
The interface does not exist.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getsockopt() , if_freenameindex() , if_nameindex() , if_nametoindex() , setsockopt() , the Base Definitions volume of IEEE Std 1003.1-2001, <net/if.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fputws(3p)

FPUTWS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fputws - put a wide-character string on a stream

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

int fputws(const wchar_t *restrict ws, FILE *restrict stream);

DESCRIPTION

The fputws() function shall write a character string corresponding to the (null-terminated) wide-character string pointed to by ws to the stream pointed to by stream. No character corresponding to the terminating null wide-character code shall be written.

The st_ctime and st_mtime fields of the file shall be marked for update between the successful execution of fputws() and the next successful completion of a call to fflush() or fclose() on the same stream or a call to exit() or abort().

RETURN VALUE

Upon successful completion, fputws() shall return a non-negative number. Otherwise, it shall return -1, set an error indicator for the stream, and set errno to indicate the error.

ERRORS

Refer to fputwc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The fputws() function does not append a <newline>.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atanf (3p)

 Continue to this page.


atanh(3p)

ATANH

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

atanh, atanhf, atanhl - inverse hyperbolic tangent functions

SYNOPSIS

#include <math.h>

double atanh(double x);
float atanhf(float x);
long double atanhl(long double x);

DESCRIPTION

These functions shall compute the inverse hyperbolic tangent of their argument x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the inverse hyperbolic tangent of their argument.

If x is ±1, a pole error shall occur, and atanh(), atanhf(), and atanhl() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively, with the same sign as the correct value of the function.

For finite |x|>1, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is NaN, a NaN shall be returned.

If x is ±0, x shall be returned.

If x is ±Inf, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is subnormal, a range error may occur and x should be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is finite and not in the range [-1,1], or is ±Inf.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

Pole Error
The x argument is ±1.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the divide-by-zero floating-point exception shall be raised.

These functions may fail if:

Range Error
The value of x is subnormal.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , tanh() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


atanl (3p)

 Continue to this page.


floor(3p)

FLOOR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

floor, floorf, floorl - floor function

SYNOPSIS

#include <math.h>

double floor(double x);
float floorf(float x);
long double floorl(long double x);

DESCRIPTION

These functions shall compute the largest integral value not greater than x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the largest integral value not greater than x, expressed as a double, float, or long double, as appropriate for the return type of the function.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

If the correct value would cause overflow, a range error shall occur and floor(), floorf(), and floorl() shall return the value of the macro -HUGE_VAL, -HUGE_VALF, and -HUGE_VALL, respectively.

ERRORS

These functions shall fail if:

Range Error
The result would cause an overflow.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The integral value returned by these functions might not be expressible as an int or long. The return value should be tested before assigning it to an integer type to avoid the undefined results of an integer overflow.

The floor() function can only overflow when the floating-point representation has DBL_MANT_DIG > DBL_MAX_EXP.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

ceil() , feclearexcept() , fetestexcept() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigignore (3p)

 Continue to this page.


getpgid(3p)

GETPGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getpgid - get the process group ID for a process

SYNOPSIS

#include <unistd.h>

pid_t getpgid(pid_t pid);

DESCRIPTION

The getpgid() function shall return the process group ID of the process whose process ID is equal to pid. If pid is equal to 0, getpgid() shall return the process group ID of the calling process.

RETURN VALUE

Upon successful completion, getpgid() shall return a process group ID. Otherwise, it shall return (pid_t)-1 and set errno to indicate the error.

ERRORS

The getpgid() function shall fail if:

EPERM
The process whose process ID is equal to pid is not in the same session as the calling process, and the implementation does not allow access to the process group ID of that process from the calling process.
ESRCH
There is no process with a process ID equal to pid.

The getpgid() function may fail if:

EINVAL
The value of the pid argument is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fork() , getpgrp() , getpid() , getsid() , setpgid() , setsid() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


if_nametoindex(3p)

IF_NAMETOINDEX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

if_nametoindex - map a network interface name to its corresponding index

SYNOPSIS

#include <net/if.h>

unsigned if_nametoindex(const char *ifname);

DESCRIPTION

The if_nametoindex() function shall return the interface index corresponding to name ifname.

RETURN VALUE

The corresponding index if ifname is the name of an interface; otherwise, zero.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getsockopt() , if_freenameindex() , if_indextoname() , if_nameindex() , setsockopt() , the Base Definitions volume of IEEE Std 1003.1-2001, <net/if.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nextafter(3p)

NEXTAFTER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nextafter, nextafterf, nextafterl, nexttoward, nexttowardf, nexttowardl - next representable floating-point number

SYNOPSIS

#include <math.h>

double nextafter(double x, double y);
float nextafterf(float x, float y);
long double nextafterl(long double x, long double y);
double nexttoward(double x, long double y);
float nexttowardf(float x, long double y);
long double nexttowardl(long double x, long double
y);

DESCRIPTION

The nextafter(), nextafterf(), and nextafterl() functions shall compute the next representable floating-point value following x in the direction of y. Thus, if y is less than x, nextafter() shall return the largest representable floating-point number less than x. The nextafter(), nextafterf(), and nextafterl() functions shall return y if x equals y.

The nexttoward(), nexttowardf(), and nexttowardl() functions shall be equivalent to the corresponding nextafter() functions, except that the second parameter shall have type long double and the functions shall return y converted to the type of the function if x equals y.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the next representable floating-point value following x in the direction of y.

If x== y, y (of the type x) shall be returned.

If x is finite and the correct function value would overflow, a range error shall occur and ±HUGE_VAL, ±HUGE_VALF, and ±HUGE_VALL (with the same sign as x) shall be returned as appropriate for the return type of the function.

If x or y is NaN, a NaN shall be returned.

If x!= y and the correct function value is subnormal, zero, or underflows, a range error shall occur, and either the correct function value (if representable) or 0.0 shall be returned.

ERRORS

These functions shall fail if:

Range Error
The correct value overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

Range Error
The correct value is subnormal or underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


remove(3p)

REMOVE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

remove - remove a file

SYNOPSIS

#include <stdio.h>

int remove(const char *path);

DESCRIPTION

The remove() function shall cause the file named by the pathname pointed to by path to be no longer accessible by that name. A subsequent attempt to open that file using that name shall fail, unless it is created anew.

If path does not name a directory, remove(path) shall be equivalent to unlink(path).

If path names a directory, remove(path) shall be equivalent to rmdir(path).

RETURN VALUE

Refer to rmdir() or unlink() .

ERRORS

Refer to rmdir() or unlink() .

The following sections are informative.

EXAMPLES

Removing Access to a File

The following example shows how to remove access to a file named /home/cnd/old_mods.

#include <stdio.h>

int status;
...
status = remove("/home/cnd/old_mods");

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

rmdir() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


gethostbyaddr (3p)

 Continue to this page.


execl (3p)

 Continue to this page.


pipe(3p)

PIPE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pipe - create an interprocess channel

SYNOPSIS

#include <unistd.h>

int pipe(int fildes[2]);

DESCRIPTION

The pipe() function shall create a pipe and place two file descriptors, one each into the arguments fildes[0] and fildes[1], that refer to the open file descriptions for the read and write ends of the pipe. Their integer values shall be the two lowest available at the time of the pipe() call. The O_NONBLOCK and FD_CLOEXEC flags shall be clear on both file descriptors. (The fcntl() function can be used to set both these flags.)

Data can be written to the file descriptor fildes[1] and read from the file descriptor fildes[0]. A read on the file descriptor fildes[0] shall access data written to the file descriptor fildes[1] on a first-in-first-out basis. It is unspecified whether fildes[0] is also open for writing and whether fildes[1] is also open for reading.

A process has the pipe open for reading (correspondingly writing) if it has a file descriptor open that refers to the read end, fildes[0] (write end, fildes[1]).

Upon successful completion, pipe() shall mark for update the st_atime, st_ctime, and st_mtime fields of the pipe.

RETURN VALUE

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The pipe() function shall fail if:

EMFILE
More than {OPEN_MAX} minus two file descriptors are already in use by this process.
ENFILE
The number of simultaneously open files in the system would exceed a system-imposed limit.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The wording carefully avoids using the verb "to open" in order to avoid any implication of use of open(); see also write() .

FUTURE DIRECTIONS

None.

SEE ALSO

fcntl() , read() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fchdir(3p)

FCHDIR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fchdir - change working directory

SYNOPSIS

#include <unistd.h>

int fchdir(int fildes);

DESCRIPTION

The fchdir() function shall be equivalent to chdir() except that the directory that is to be the new current working directory is specified by the file descriptor fildes.

A conforming application can obtain a file descriptor for a file of type directory using open(), provided that the file status flags and access modes do not contain O_WRONLY or O_RDWR.

RETURN VALUE

Upon successful completion, fchdir() shall return 0. Otherwise, it shall return -1 and set errno to indicate the error. On failure the current working directory shall remain unchanged.

ERRORS

The fchdir() function shall fail if:

EACCES
Search permission is denied for the directory referenced by fildes.
EBADF
The fildes argument is not an open file descriptor.
ENOTDIR
The open file descriptor fildes does not refer to a directory.

The fchdir() may fail if:

EINTR
A signal was caught during the execution of fchdir().
EIO
An I/O error occurred while reading from or writing to the file system.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

chdir() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


carg(3p)

CARG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

carg, cargf, cargl - complex argument functions

SYNOPSIS

#include <complex.h>

double carg(double complex z);
float cargf(float complex z);
long double cargl(long double complex z);

DESCRIPTION

These functions shall compute the argument (also called phase angle) of z, with a branch cut along the negative real axis.

RETURN VALUE

These functions shall return the value of the argument in the interval [-pi, +pi].

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cimag() , conj() , cproj() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


execv (3p)

 Continue to this page.


wctob(3p)

WCTOB

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wctob - wide-character to single-byte conversion

SYNOPSIS

#include <stdio.h>
#include <wchar.h>

int wctob(wint_t c);

DESCRIPTION

The wctob() function shall determine whether c corresponds to a member of the extended character set whose character representation is a single byte when in the initial shift state.

The behavior of this function shall be affected by the LC_CTYPE category of the current locale.

RETURN VALUE

The wctob() function shall return EOF if c does not correspond to a character with length one in the initial shift state. Otherwise, it shall return the single-byte representation of that character as an unsigned char converted to int.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

btowc() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


endutxent (3p)

 Continue to this page.


getpgrp(3p)

GETPGRP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getpgrp - get the process group ID of the calling process

SYNOPSIS

#include <unistd.h>

pid_t getpgrp(void);

DESCRIPTION

The getpgrp() function shall return the process group ID of the calling process.

RETURN VALUE

The getpgrp() function shall always be successful and no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

4.3 BSD provides a getpgrp() function that returns the process group ID for a specified process. Although this function supports job control, all known job control shells always specify the calling process with this function. Thus, the simpler System V getpgrp() suffices, and the added complexity of the 4.3 BSD getpgrp() is provided by the XSI extension getpgid().

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fork() , getpgid() , getpid() , getppid() , kill() , setpgid() , setsid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


flockfile(3p)

FLOCKFILE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

flockfile, ftrylockfile, funlockfile - stdio locking functions

SYNOPSIS

#include <stdio.h>

void flockfile(FILE *file);
int ftrylockfile(FILE *file);
void funlockfile(FILE *file);

DESCRIPTION

These functions shall provide for explicit application-level locking of stdio ( FILE *) objects. These functions can be used by a thread to delineate a sequence of I/O statements that are executed as a unit.

The flockfile() function shall acquire for a thread ownership of a ( FILE *) object.

The ftrylockfile() function shall acquire for a thread ownership of a ( FILE *) object if the object is available; ftrylockfile() is a non-blocking version of flockfile().

The funlockfile() function shall relinquish the ownership granted to the thread. The behavior is undefined if a thread other than the current owner calls the funlockfile() function.

The functions shall behave as if there is a lock count associated with each ( FILE *) object. This count is implicitly initialized to zero when the ( FILE *) object is created. The ( FILE *) object is unlocked when the count is zero. When the count is positive, a single thread owns the ( FILE *) object. When the flockfile() function is called, if the count is zero or if the count is positive and the caller owns the ( FILE *) object, the count shall be incremented. Otherwise, the calling thread shall be suspended, waiting for the count to return to zero. Each call to funlockfile() shall decrement the count. This allows matching calls to flockfile() (or successful calls to ftrylockfile()) and funlockfile() to be nested.

All functions that reference ( FILE *) objects shall behave as if they use flockfile() and funlockfile() internally to obtain ownership of these ( FILE *) objects.

RETURN VALUE

None for flockfile() and funlockfile().

The ftrylockfile() function shall return zero for success and non-zero to indicate that the lock cannot be acquired.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

RATIONALE

The flockfile() and funlockfile() functions provide an orthogonal mutual-exclusion lock for each FILE. The ftrylockfile() function provides a non-blocking attempt to acquire a file lock, analogous to pthread_mutex_trylock().

These locks behave as if they are the same as those used internally by stdio for thread-safety. This both provides thread-safety of these functions without requiring a second level of internal locking and allows functions in stdio to be implemented in terms of other stdio functions.

Application writers and implementors should be aware that there are potential deadlock problems on FILE objects. For example, the line-buffered flushing semantics of stdio (requested via {_IOLBF}) require that certain input operations sometimes cause the buffered contents of implementation-defined line-buffered output streams to be flushed. If two threads each hold the lock on the other's FILE, deadlock ensues. This type of deadlock can be avoided by acquiring FILE locks in a consistent order. In particular, the line-buffered output stream deadlock can typically be avoided by acquiring locks on input streams before locks on output streams if a thread would be acquiring both.

In summary, threads sharing stdio streams with other threads can use flockfile() and funlockfile() to cause sequences of I/O performed by a single thread to be kept bundled. The only case where the use of flockfile() and funlockfile() is required is to provide a scope protecting uses of the *_unlocked() functions/macros. This moves the cost/performance tradeoff to the optimal point.

FUTURE DIRECTIONS

None.

SEE ALSO

getc_unlocked() , putc_unlocked() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getnetbyaddr (3p)

 Continue to this page.


statvfs(3p)

FSTATVFS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fstatvfs, statvfs - get file system information

SYNOPSIS

#include <sys/statvfs.h>

int fstatvfs(int fildes, struct statvfs *buf);
int statvfs(const char *restrict path, struct statvfs *restrict buf);

DESCRIPTION

The fstatvfs() function shall obtain information about the file system containing the file referenced by fildes.

The statvfs() function shall obtain information about the file system containing the file named by path.

For both functions, the buf argument is a pointer to a statvfs structure that shall be filled. Read, write, or execute permission of the named file is not required.

The following flags can be returned in the f_flag member:

ST_RDONLY
Read-only file system.
ST_NOSUID
Setuid/setgid bits ignored by exec.

It is unspecified whether all members of the statvfs structure have meaningful values on all file systems.

RETURN VALUE

Upon successful completion, statvfs() shall return 0. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The fstatvfs() and statvfs() functions shall fail if:

EIO
An I/O error occurred while reading the file system.
EINTR
A signal was caught during execution of the function.
EOVERFLOW
One of the values to be returned cannot be represented correctly in the structure pointed to by buf.

The fstatvfs() function shall fail if:

EBADF
The fildes argument is not an open file descriptor.

The statvfs() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of a pathname exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix of path is not a directory.

The statvfs() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

Obtaining File System Information Using fstatvfs()

The following example shows how to obtain file system information for the file system upon which the file named /home/cnd/mod1 resides, using the fstatvfs() function. The /home/cnd/mod1 file is opened with read/write privileges and the open file descriptor is passed to the fstatvfs() function.

#include <statvfs.h>
#include <fcntl.h>

struct statvfs buffer;
int            status;
...
fildes = open("/home/cnd/mod1", O_RDWR);
status  = fstatvfs(fildes, &buffer);

Obtaining File System Information Using statvfs()

The following example shows how to obtain file system information for the file system upon which the file named /home/cnd/mod1 resides, using the statvfs() function.

#include <statvfs.h>

struct statvfs buffer;
int            status;
...
status = statvfs("/home/cnd/mod1", &buffer);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , chown() , creat() , dup() , exec() , fcntl() , link() , mknod() , open() , pipe() , read() , time() , unlink() , utime() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/statvfs.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstold (3p)

 Continue to this page.


socket(3p)

SOCKET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

socket - create an endpoint for communication

SYNOPSIS

#include <sys/socket.h>

int socket(int domain, int type, int protocol);

DESCRIPTION

The socket() function shall create an unbound socket in a communications domain, and return a file descriptor that can be used in later function calls that operate on sockets.

The socket() function takes the following arguments:

domain
Specifies the communications domain in which a socket is to be created.
type
Specifies the type of socket to be created.
protocol
Specifies a particular protocol to be used with the socket. Specifying a protocol of 0 causes socket() to use an unspecified default protocol appropriate for the requested socket type.

The domain argument specifies the address family used in the communications domain. The address families supported by the system are implementation-defined.

Symbolic constants that can be used for the domain argument are defined in the <sys/socket.h> header.

The type argument specifies the socket type, which determines the semantics of communication over the socket. The following socket types are defined; implementations may specify additional socket types:

SOCK_STREAM
Provides sequenced, reliable, bidirectional, connection-mode byte streams, and may provide a transmission mechanism for out-of-band data.
SOCK_DGRAM
Provides datagrams, which are connectionless-mode, unreliable messages of fixed maximum length.
SOCK_SEQPACKET
Provides sequenced, reliable, bidirectional, connection-mode transmission paths for records. A record can be sent using one or more output operations and received using one or more input operations, but a single operation never transfers part of more than one record. Record boundaries are visible to the receiver via the MSG_EOR flag.

If the protocol argument is non-zero, it shall specify a protocol that is supported by the address family. If the protocol argument is zero, the default protocol for this address family and type shall be used. The protocols supported by the system are implementation-defined.

The process may need to have appropriate privileges to use the socket() function or to create some sockets.

RETURN VALUE

Upon successful completion, socket() shall return a non-negative integer, the socket file descriptor. Otherwise, a value of -1 shall be returned and errno set to indicate the error.

ERRORS

The socket() function shall fail if:

EAFNOSUPPORT

The implementation does not support the specified address family.

EMFILE
No more file descriptors are available for this process.
ENFILE
No more file descriptors are available for the system.
EPROTONOSUPPORT

The protocol is not supported by the address family, or the protocol is not supported by the implementation.

EPROTOTYPE
The socket type is not supported by the protocol.

The socket() function may fail if:

EACCES
The process does not have appropriate privileges.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENOMEM
Insufficient memory was available to fulfill the request.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The documentation for specific address families specifies which protocols each address family supports. The documentation for specific protocols specifies which socket types each protocol supports.

The application can determine whether an address family is supported by trying to create a socket with domain set to the protocol in question.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

accept() , bind() , connect() , getsockname() , getsockopt() , listen() , recv() , recvfrom() , recvmsg() , send() , sendmsg() , setsockopt() , shutdown() , socketpair() , the Base Definitions volume of IEEE Std 1003.1-2001, <netinet/in.h>, <sys/socket.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstoll (3p)

 Continue to this page.


sigtimedwait (3p)

 Continue to this page.


mknod(3p)

MKNOD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mknod - make a directory, a special file, or a regular file

SYNOPSIS

#include <sys/stat.h>

int mknod(const char *path, mode_t mode, dev_t dev);

DESCRIPTION

The mknod() function shall create a new file named by the pathname to which the argument path points.

The file type for path is OR'ed into the mode argument, and the application shall select one of the following symbolic constants:
Name | Description
S_IFIFO | FIFO-special
S_IFCHR | Character-special (non-portable)
S_IFDIR | Directory (non-portable)
S_IFBLK | Block-special (non-portable)
S_IFREG | Regular (non-portable)

The only portable use of mknod() is to create a FIFO-special file. If mode is not S_IFIFO or dev is not 0, the behavior of mknod() is unspecified.

The permissions for the new file are OR'ed into the mode argument, and may be selected from any combination of the following symbolic constants:
Name | Description
S_ISUID | Set user ID on execution.
S_ISGID | Set group ID on execution.
S_IRWXU | Read, write, or execute (search) by owner.
S_IRUSR | Read by owner.
S_IWUSR | Write by owner.
S_IXUSR | Execute (search) by owner.
S_IRWXG | Read, write, or execute (search) by group.
S_IRGRP | Read by group.
S_IWGRP | Write by group.
S_IXGRP | Execute (search) by group.
S_IRWXO | Read, write, or execute (search) by others.
S_IROTH | Read by others.
S_IWOTH | Write by others.
S_IXOTH | Execute (search) by others.
S_ISVTX | On directories, restricted deletion flag.

The user ID of the file shall be initialized to the effective user ID of the process. The group ID of the file shall be initialized to either the effective group ID of the process or the group ID of the parent directory. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process. The owner, group, and other permission bits of mode shall be modified by the file mode creation mask of the process. The mknod() function shall clear each bit whose corresponding bit in the file mode creation mask of the process is set.

If path names a symbolic link, mknod() shall fail and set errno to [EEXIST].

Upon successful completion, mknod() shall mark for update the st_atime, st_ctime, and st_mtime fields of the file. Also, the st_ctime and st_mtime fields of the directory that contains the new entry shall be marked for update.

Only a process with appropriate privileges may invoke mknod() for file types other than FIFO-special.

RETURN VALUE

Upon successful completion, mknod() shall return 0. Otherwise, it shall return -1, the new file shall not be created, and errno shall be set to indicate the error.

ERRORS

The mknod() function shall fail if:

EACCES
A component of the path prefix denies search permission, or write permission is denied on the parent directory.
EEXIST
The named file exists.
EINVAL
An invalid argument exists.
EIO
An I/O error occurred while accessing the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of a pathname exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of the path prefix specified by path does not name an existing directory or path is an empty string.
ENOSPC
The directory that would contain the new file cannot be extended or the file system is out of file allocation resources.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The invoking process does not have appropriate privileges and the file type is not FIFO-special.
EROFS
The directory in which the file is to be created is located on a read-only file system.

The mknod() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

Creating a FIFO Special File

The following example shows how to create a FIFO special file named /home/cnd/mod_done, with read/write permissions for owner, and with read permissions for group and others.

#include <sys/types.h>
#include <sys/stat.h>

dev_t dev;
int   status;
...
status  = mknod("/home/cnd/mod_done", S_IFIFO | S_IWUSR |
    S_IRUSR | S_IRGRP | S_IROTH, dev);

APPLICATION USAGE

The mkfifo() function is preferred over this function for making FIFO special files.

RATIONALE

The POSIX.1-1990 standard required that the group ID of a newly created file be set to the group ID of its parent directory or to the effective group ID of the creating process. FIPS 151-2 required that implementations provide a way to have the group ID be set to the group ID of the containing directory, but did not prohibit implementations also supporting a way to set the group ID to the effective group ID of the creating process. Conforming applications should not assume which group ID will be used. If it matters, an application can use chown() to set the group ID after the file is created, or determine under what conditions the implementation will set the desired group ID.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , creat() , exec() , mkdir() , mkfifo() , open() , stat() , umask() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strerror(3p)

STRERROR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strerror, strerror_r - get error message string

SYNOPSIS

#include <string.h>

char *strerror(int errnum);

int strerror_r(int errnum, char *strerrbuf, size_t buflen);

DESCRIPTION

For strerror(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

The strerror() function shall map the error number in errnum to a locale-dependent error message string and shall return a pointer to it. Typically, the values for errnum come from errno, but strerror() shall map any value of type int to a message.

The string pointed to shall not be modified by the application, but may be overwritten by a subsequent call to strerror() or perror().

The contents of the error message strings returned by strerror() should be determined by the setting of the LC_MESSAGES category in the current locale.

The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls strerror().

The strerror() function shall not change the setting of errno if successful.

Since no return value is reserved to indicate an error, an application wishing to check for error situations should set errno to 0, then call strerror(), then check errno.

The strerror() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

The strerror_r() function shall map the error number in errnum to a locale-dependent error message string and shall return the string in the buffer pointed to by strerrbuf, with length buflen.

RETURN VALUE

Upon successful completion, strerror() shall return a pointer to the generated message string. On error errno may be set, but no return value is reserved to indicate an error.

Upon successful completion, strerror_r() shall return 0. Otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value of errnum is not a valid error number.

The strerror_r() function may fail if:

ERANGE
Insufficient storage was supplied via strerrbuf and buflen to contain the generated message string.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

perror() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


umask(3p)

UMASK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

umask - set and get the file mode creation mask

SYNOPSIS

#include <sys/stat.h>

mode_t umask(mode_t cmask);

DESCRIPTION

The umask() function shall set the process' file mode creation mask to cmask and return the previous value of the mask. Only the file permission bits of cmask (see <sys/stat.h>) are used; the meaning of the other bits is implementation-defined.

The process' file mode creation mask is used during open(), creat(), mkdir(), and mkfifo() to turn off permission bits in the mode argument supplied. Bit positions that are set in cmask are cleared in the mode of the created file.

RETURN VALUE

The file permission bits in the value returned by umask() shall be the previous value of the file mode creation mask. The state of any other bits in that value is unspecified, except that a subsequent call to umask() with the returned value as cmask shall leave the state of the mask the same as its state before the first call, including any unspecified use of those bits.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Unsigned argument and return types for umask() were proposed. The return type and the argument were both changed to mode_t.

Historical implementations have made use of additional bits in cmask for their implementation-defined purposes. The addition of the text that the meaning of other bits of the field is implementation-defined permits these implementations to conform to this volume of IEEE Std 1003.1-2001.

FUTURE DIRECTIONS

None.

SEE ALSO

creat() , mkdir() , mkfifo() , open() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


va_copy (3p)

 Continue to this page.


cbrt(3p)

CBRT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cbrt, cbrtf, cbrtl - cube root functions

SYNOPSIS

#include <math.h>

double cbrt(double x);
float cbrtf(float x);
long double cbrtl(long double x);

DESCRIPTION

These functions shall compute the real cube root of their argument x.

RETURN VALUE

Upon successful completion, these functions shall return the cube root of x.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

For some applications, a true cube root function, which returns negative results for negative arguments, is more appropriate than pow( x, 1.0/3.0), which returns a NaN for x less than 0.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


remque (3p)

 Continue to this page.


remquo(3p)

REMQUO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

remquo, remquof, remquol - remainder functions

SYNOPSIS

#include <math.h>

double remquo(double x, double y, int *quo);
float remquof(float x, float y, int *quo);
long double remquol(long double x, long double y, int *quo);

DESCRIPTION

The remquo(), remquof(), and remquol() functions shall compute the same remainder as the remainder(), remainderf(), and remainderl() functions, respectively. In the object pointed to by quo, they store a value whose sign is the sign of x/ y and whose magnitude is congruent modulo 2**n to the magnitude of the integral quotient of x/ y, where n is an implementation-defined integer greater than or equal to 3.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

These functions shall return x REM y.

If x or y is NaN, a NaN shall be returned.

If x is ±Inf or y is zero and the other argument is non-NaN, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is ±Inf, or the y argument is ±0 and the other argument is non-NaN.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

These functions are intended for implementing argument reductions which can exploit a few low-order bits of the quotient. Note that x may be so large in magnitude relative to y that an exact representation of the quotient is not practical.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , remainder() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wcstoul(3p)

WCSTOUL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wcstoul, wcstoull - convert a wide-character string to an unsigned long

SYNOPSIS

#include <wchar.h>

unsigned long wcstoul(const wchar_t *restrict nptr,
wchar_t **restrict endptr, int base);
unsigned long long wcstoull(const wchar_t *restrict nptr,
wchar_t **restrict endptr, int base);

DESCRIPTION

The wcstoul() and wcstoull() functions shall convert the initial portion of the wide-character string pointed to by nptr to unsigned long and unsigned long long representation, respectively. First, they shall decompose the input wide-character string into three parts:

1.
An initial, possibly empty, sequence of white-space wide-character codes (as specified by iswspace())

2.
A subject sequence interpreted as an integer represented in some radix determined by the value of base

3.
A final wide-character string of one or more unrecognized wide-character codes, including the terminating null wide-character code of the input wide-character string

Then they shall attempt to convert the subject sequence to an unsigned integer, and return the result.

If base is 0, the expected form of the subject sequence is that of a decimal constant, octal constant, or hexadecimal constant, any of which may be preceded by a '+' or '-' sign. A decimal constant begins with a non-zero digit, and consists of a sequence of decimal digits. An octal constant consists of the prefix '0' optionally followed by a sequence of the digits '0' to '7' only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and letters 'a' (or 'A' ) to 'f' (or 'F' ) with values 10 to 15 respectively.

If the value of base is between 2 and 36, the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a '+' or '-' sign, but not including an integer suffix. The letters from 'a' (or 'A' ) to 'z' (or 'Z' ) inclusive are ascribed the values 10 to 35; only letters whose ascribed values are less than that of base shall be permitted. If the value of base is 16, the wide-character codes 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.

The subject sequence is defined as the longest initial subsequence of the input wide-character string, starting with the first wide-character code that is not white space and is of the expected form. The subject sequence contains no wide-character codes if the input wide-character string is empty or consists entirely of white-space wide-character codes, or if the first wide-character code that is not white space is other than a sign or a permissible letter or digit.

If the subject sequence has the expected form and base is 0, the sequence of wide-character codes starting with the first digit shall be interpreted as an integer constant. If the subject sequence has the expected form and the value of base is between 2 and 36, it shall be used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion shall be negated. A pointer to the final wide-character string shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

In other than the C or POSIX locales, other implementation-defined subject sequences may be accepted.

If the subject sequence is empty or does not have the expected form, no conversion shall be performed; the value of nptr shall be stored in the object pointed to by endptr, provided that endptr is not a null pointer.

The wcstoul() function shall not change the setting of errno if successful.

Since 0, {ULONG_MAX}, and {ULLONG_MAX} are returned on error and 0 is also a valid return on success, an application wishing to check for error situations should set errno to 0, then call wcstoul() or wcstoull(), then check errno.

RETURN VALUE

Upon successful completion, the wcstoul() and wcstoull() functions shall return the converted value, if any. If no conversion could be performed, 0 shall be returned and errno may be set to indicate the error. If the correct value is outside the range of representable values, {ULONG_MAX} or {ULLONG_MAX} respectively shall be returned and errno set to [ERANGE].

ERRORS

These functions shall fail if:

EINVAL
The value of base is not supported.
ERANGE
The value to be returned is not representable.

These functions may fail if:

EINVAL
No conversion could be performed.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalpha() , scanf() , wcstod() , wcstol() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vfprintf (3p)

 Continue to this page.


ccos(3p)

CCOS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ccos, ccosf, ccosl - complex cosine functions

SYNOPSIS

#include <complex.h>

double complex ccos(double complex z);
float complex ccosf(float complex z);
long double complex ccosl(long double complex z);

DESCRIPTION

These functions shall compute the complex cosine of z.

RETURN VALUE

These functions shall return the complex cosine value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

cacos() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


inet_addr(3p)

INET_ADDR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

inet_addr, inet_ntoa - IPv4 address manipulation

SYNOPSIS

#include <arpa/inet.h>

in_addr_t inet_addr(const char *cp);
char *inet_ntoa(struct in_addr in);

DESCRIPTION

The inet_addr() function shall convert the string pointed to by cp, in the standard IPv4 dotted decimal notation, to an integer value suitable for use as an Internet address.

The inet_ntoa() function shall convert the Internet host address specified by in to a string in the Internet standard dot notation.

The inet_ntoa() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

All Internet addresses shall be returned in network order (bytes ordered from left to right).

Values specified using IPv4 dotted decimal notation take one of the following forms:

a.b.c.d
When four parts are specified, each shall be interpreted as a byte of data and assigned, from left to right, to the four bytes of an Internet address.
a.b.c
When a three-part address is specified, the last part shall be interpreted as a 16-bit quantity and placed in the rightmost two bytes of the network address. This makes the three-part address format convenient for specifying Class B network addresses as "128.net.host" .
a.b
When a two-part address is supplied, the last part shall be interpreted as a 24-bit quantity and placed in the rightmost three bytes of the network address. This makes the two-part address format convenient for specifying Class A network addresses as "net.host" .
a
When only one part is given, the value shall be stored directly in the network address without any byte rearrangement.

All numbers supplied as parts in IPv4 dotted decimal notation may be decimal, octal, or hexadecimal, as specified in the ISO C standard (that is, a leading 0x or 0X implies hexadecimal; otherwise, a leading '0' implies octal; otherwise, the number is interpreted as decimal).

RETURN VALUE

Upon successful completion, inet_addr() shall return the Internet address. Otherwise, it shall return ( in_addr_t)(-1).

The inet_ntoa() function shall return a pointer to the network address in Internet standard dot notation.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The return value of inet_ntoa() may point to static data that may be overwritten by subsequent calls to inet_ntoa().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

endhostent() , endnetent() , the Base Definitions volume of IEEE Std 1003.1-2001, <arpa/inet.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ftell(3p)

FTELL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ftell, ftello - return a file offset in a stream

SYNOPSIS

#include <stdio.h>

long ftell(FILE *stream);

off_t ftello(FILE *stream);

DESCRIPTION

The ftell() function shall obtain the current value of the file-position indicator for the stream pointed to by stream.

The ftello() function shall be equivalent to ftell(), except that the return value is of type off_t.

RETURN VALUE

Upon successful completion, ftell() and ftello() shall return the current value of the file-position indicator for the stream measured in bytes from the beginning of the file.

Otherwise, ftell() and ftello() shall return -1, cast to long and off_t respectively, and set errno to indicate the error.

ERRORS

The ftell() and ftello() functions shall fail if:

EBADF
The file descriptor underlying stream is not an open file descriptor.
EOVERFLOW
For ftell(), the current file offset cannot be represented correctly in an object of type long.
EOVERFLOW
For ftello(), the current file offset cannot be represented correctly in an object of type off_t.
ESPIPE
The file descriptor underlying stream is associated with a pipe or FIFO.

The ftell() function may fail if:

ESPIPE
The file descriptor underlying stream is associated with a socket.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fgetpos() , fopen() , fseek() , lseek() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_cond_wait(3p)

PTHREAD_COND_TIMEDWAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_cond_timedwait, pthread_cond_wait - wait on a condition

SYNOPSIS

#include <pthread.h>

int pthread_cond_timedwait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);

DESCRIPTION

The pthread_cond_timedwait() and pthread_cond_wait() functions shall block on a condition variable. They shall be called with mutex locked by the calling thread or undefined behavior results.

These functions atomically release mutex and cause the calling thread to block on the condition variable cond; atomically here means "atomically with respect to access by another thread to the mutex and then the condition variable". That is, if another thread is able to acquire the mutex after the about-to-block thread has released it, then a subsequent call to pthread_cond_broadcast() or pthread_cond_signal() in that thread shall behave as if it were issued after the about-to-block thread has blocked.

Upon successful return, the mutex shall have been locked and shall be owned by the calling thread.

When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

The effect of using more than one mutex for concurrent pthread_cond_timedwait() or pthread_cond_wait() operations on the same condition variable is undefined; that is, a condition variable becomes bound to a unique mutex when a thread waits on the condition variable, and this (dynamic) binding shall end when the wait returns.

A condition wait (whether timed or not) is a cancellation point. When the cancelability enable state of a thread is set to PTHREAD_CANCEL_DEFERRED, a side effect of acting upon a cancellation request while in a condition wait is that the mutex is (in effect) re-acquired before calling the first cancellation cleanup handler. The effect is as if the thread were unblocked, allowed to execute up to the point of returning from the call to pthread_cond_timedwait() or pthread_cond_wait(), but at that point notices the cancellation request and instead of returning to the caller of pthread_cond_timedwait() or pthread_cond_wait(), starts the thread cancellation activities, which includes calling cancellation cleanup handlers.

A thread that has been unblocked because it has been canceled while blocked in a call to pthread_cond_timedwait() or pthread_cond_wait() shall not consume any condition signal that may be directed concurrently at the condition variable if there are other threads blocked on the condition variable.

The pthread_cond_timedwait() function shall be equivalent to pthread_cond_wait(), except that an error is returned if the absolute time specified by abstime passes (that is, system time equals or exceeds abstime) before the condition cond is signaled or broadcasted, or if the absolute time specified by abstime has already been passed at the time of the call.

If the Clock Selection option is supported, the condition variable shall have a clock attribute which specifies the clock that shall be used to measure the time specified by the abstime argument. When such timeouts occur, pthread_cond_timedwait() shall nonetheless release and re-acquire the mutex referenced by mutex. The pthread_cond_timedwait() function is also a cancellation point.

If a signal is delivered to a thread waiting for a condition variable, upon return from the signal handler the thread resumes waiting for the condition variable as if it was not interrupted, or it shall return zero due to spurious wakeup.

RETURN VALUE

Except in the case of [ETIMEDOUT], all these error checks shall act as if they were performed immediately at the beginning of processing for the function and shall cause an error return, in effect, prior to modifying the state of the mutex specified by mutex or the condition variable specified by cond.

Upon successful completion, a value of zero shall be returned; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_cond_timedwait() function shall fail if:

ETIMEDOUT
The time specified by abstime to pthread_cond_timedwait() has passed.

The pthread_cond_timedwait() and pthread_cond_wait() functions may fail if:

EINVAL
The value specified by cond, mutex, or abstime is invalid.
EINVAL
Different mutexes were supplied for concurrent pthread_cond_timedwait() or pthread_cond_wait() operations on the same condition variable.
EPERM
The mutex was not owned by the current thread at the time of the call.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Condition Wait Semantics

It is important to note that when pthread_cond_wait() and pthread_cond_timedwait() return without error, the associated predicate may still be false. Similarly, when pthread_cond_timedwait() returns with the timeout error, the associated predicate may be true due to an unavoidable race between the expiration of the timeout and the predicate state change.

Some implementations, particularly on a multi-processor, may sometimes cause multiple threads to wake up when the condition variable is signaled simultaneously on different processors.

In general, whenever a condition wait returns, the thread has to re-evaluate the predicate associated with the condition wait to determine whether it can safely proceed, should wait again, or should declare a timeout. A return from the wait does not imply that the associated predicate is either true or false.

It is thus recommended that a condition wait be enclosed in the equivalent of a "while loop" that checks the predicate.

Timed Wait Semantics

An absolute time measure was chosen for specifying the timeout parameter for two reasons. First, a relative time measure can be easily implemented on top of a function that specifies absolute time, but there is a race condition associated with specifying an absolute timeout on top of a function that specifies relative timeouts. For example, assume that clock_gettime() returns the current time and cond_relative_timed_wait() uses relative timeouts:

clock_gettime(CLOCK_REALTIME, &now)
reltime = sleep_til_this_absolute_time -now;
cond_relative_timed_wait(c, m, &reltime);

If the thread is preempted between the first statement and the last statement, the thread blocks for too long. Blocking, however, is irrelevant if an absolute timeout is used. An absolute timeout also need not be recomputed if it is used multiple times in a loop, such as that enclosing a condition wait.

For cases when the system clock is advanced discontinuously by an operator, it is expected that implementations process any timed wait expiring at an intervening time as if that time had actually occurred.

Cancellation and Condition Wait

A condition wait, whether timed or not, is a cancellation point. That is, the functions pthread_cond_wait() or pthread_cond_timedwait() are points where a pending (or concurrent) cancellation request is noticed. The reason for this is that an indefinite wait is possible at these points-whatever event is being waited for, even if the program is totally correct, might never occur; for example, some input data being awaited might never be sent. By making condition wait a cancellation point, the thread can be canceled and perform its cancellation cleanup handler even though it may be stuck in some indefinite wait.

A side effect of acting on a cancellation request while a thread is blocked on a condition variable is to re-acquire the mutex before calling any of the cancellation cleanup handlers. This is done in order to ensure that the cancellation cleanup handler is executed in the same state as the critical code that lies both before and after the call to the condition wait function. This rule is also required when interfacing to POSIX threads from languages, such as Ada or C++, which may choose to map cancellation onto a language exception; this rule ensures that each exception handler guarding a critical section can always safely depend upon the fact that the associated mutex has already been locked regardless of exactly where within the critical section the exception was raised. Without this rule, there would not be a uniform rule that exception handlers could follow regarding the lock, and so coding would become very cumbersome.

Therefore, since some statement has to be made regarding the state of the lock when a cancellation is delivered during a wait, a definition has been chosen that makes application coding most convenient and error free.

When acting on a cancellation request while a thread is blocked on a condition variable, the implementation is required to ensure that the thread does not consume any condition signals directed at that condition variable if there are any other threads waiting on that condition variable. This rule is specified in order to avoid deadlock conditions that could occur if these two independent requests (one acting on a thread and the other acting on the condition variable) were not processed independently.

Performance of Mutexes and Condition Variables

Mutexes are expected to be locked only for a few instructions. This practice is almost automatically enforced by the desire of programmers to avoid long serial regions of execution (which would reduce total effective parallelism).

When using mutexes and condition variables, one tries to ensure that the usual case is to lock the mutex, access shared data, and unlock the mutex. Waiting on a condition variable should be a relatively rare situation. For example, when implementing a read-write lock, code that acquires a read-lock typically needs only to increment the count of readers (under mutual-exclusion) and return. The calling thread would actually wait on the condition variable only when there is already an active writer. So the efficiency of a synchronization operation is bounded by the cost of mutex lock/unlock and not by condition wait. Note that in the usual case there is no context switch.

This is not to say that the efficiency of condition waiting is unimportant. Since there needs to be at least one context switch per Ada rendezvous, the efficiency of waiting on a condition variable is important. The cost of waiting on a condition variable should be little more than the minimal cost for a context switch plus the time to unlock and lock the mutex.

Features of Mutexes and Condition Variables

It had been suggested that the mutex acquisition and release be decoupled from condition wait. This was rejected because it is the combined nature of the operation that, in fact, facilitates realtime implementations. Those implementations can atomically move a high-priority thread between the condition variable and the mutex in a manner that is transparent to the caller. This can prevent extra context switches and provide more deterministic acquisition of a mutex when the waiting thread is signaled. Thus, fairness and priority issues can be dealt with directly by the scheduling discipline. Furthermore, the current condition wait operation matches existing practice.

Scheduling Behavior of Mutexes and Condition Variables

Synchronization primitives that attempt to interfere with scheduling policy by specifying an ordering rule are considered undesirable. Threads waiting on mutexes and condition variables are selected to proceed in an order dependent upon the scheduling policy rather than in some fixed order (for example, FIFO or priority). Thus, the scheduling policy determines which thread(s) are awakened and allowed to proceed.

Timed Condition Wait

The pthread_cond_timedwait() function allows an application to give up waiting for a particular condition after a given amount of time. An example of its use follows:

(void) pthread_mutex_lock(&t.mn);
        t.waiters++;
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_sec += 5;
    rc = 0;
    while (! mypredicate(&t) && rc == 0)
        rc = pthread_cond_timedwait(&t.cond, &t.mn, &ts);
    t.waiters--;
    if (rc == 0) setmystate(&t);
(void) pthread_mutex_unlock(&t.mn);

By making the timeout parameter absolute, it does not need to be recomputed each time the program checks its blocking predicate. If the timeout was relative, it would have to be recomputed before each call. This would be especially difficult since such code would need to take into account the possibility of extra wakeups that result from extra broadcasts or signals on the condition variable that occur before either the predicate is true or the timeout is due.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_signal() , pthread_cond_broadcast() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tmpfile(3p)

TMPFILE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tmpfile - create a temporary file

SYNOPSIS

#include <stdio.h>

FILE *tmpfile(void);

DESCRIPTION

The tmpfile() function shall create a temporary file and open a corresponding stream. The file shall be automatically deleted when all references to the file are closed. The file is opened as in fopen() for update (w+).

In some implementations, a permanent file may be left behind if the process calling tmpfile() is killed while it is processing a call to tmpfile().

An error message may be written to standard error if the stream cannot be opened.

RETURN VALUE

Upon successful completion, tmpfile() shall return a pointer to the stream of the file that is created. Otherwise, it shall return a null pointer and set errno to indicate the error.

ERRORS

The tmpfile() function shall fail if:

EINTR
A signal was caught during tmpfile().
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.
ENOSPC
The directory or file system which would contain the new file cannot be expanded.
EOVERFLOW
The file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.

The tmpfile() function may fail if:

EMFILE
{FOPEN_MAX} streams are currently open in the calling process.
ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

Creating a Temporary File

The following example creates a temporary file for update, and returns a pointer to a stream for the created file in the fp variable.

#include <stdio.h>
...
FILE *fp;

fp = tmpfile ();

APPLICATION USAGE

It should be possible to open at least {TMP_MAX} temporary files during the lifetime of the program (this limit may be shared with tmpnam()) and there should be no limit on the number simultaneously open other than this limit and any limit on the number of open files ( {FOPEN_MAX}).

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , tmpnam() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


isblank(3p)

ISBLANK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isblank - test for a blank character

SYNOPSIS

#include <ctype.h>

int isblank(int c);

DESCRIPTION

The isblank() function shall test whether c is a character of class blank in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The c argument is a type int, the value of which the application shall ensure is a character representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The isblank() function shall return non-zero if c is a <blank>; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for character classification.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

isalnum() , isalpha() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isspace() , isupper() , isxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_openpt(3p)

POSIX_OPENPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_openpt - open a pseudo-terminal device

SYNOPSIS

#include <stdlib.h>
#include <fcntl.h>

int posix_openpt(int oflag);

DESCRIPTION

The posix_openpt() function shall establish a connection between a master device for a pseudo-terminal and a file descriptor. The file descriptor is used by other I/O functions that refer to that pseudo-terminal.

The file status flags and file access modes of the open file description shall be set according to the value of oflag.

Values for oflag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h>:

O_RDWR
Open for reading and writing.
O_NOCTTY
If set posix_openpt() shall not cause the terminal device to become the controlling terminal for the process.

The behavior of other values for the oflag argument is unspecified.

RETURN VALUE

Upon successful completion, the posix_openpt() function shall open a master pseudo-terminal device and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The posix_openpt() function shall fail if:

EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.

The posix_openpt() function may fail if:

EINVAL
The value of oflag is not valid.
EAGAIN
Out of pseudo-terminal resources.
ENOSR
Out of STREAMS resources.

The following sections are informative.

EXAMPLES

Opening a Pseudo-Terminal and Returning the Name of the Slave

Device and a File Descriptor

#include <fcntl.h>
#include <stdio.h>

int masterfd, slavefd;
char *slavedevice;

masterfd = posix_openpt(O_RDWR|O_NOCTTY);

if (masterfd == -1
    || grantpt (masterfd) == -1
    || unlockpt (masterfd) == -1
    || (slavedevice = ptsname (masterfd)) == NULL)
    return -1;

printf("slave device is: %s\n", slavedevice);

slavefd = open(slave, O_RDWR|O_NOCTTY);
if (slavefd < 0)
    return -1;

APPLICATION USAGE

This function is a method for portably obtaining a file descriptor of a master terminal device for a pseudo-terminal. The grantpt() and ptsname() functions can be used to manipulate mode and ownership permissions, and to obtain the name of the slave device, respectively.

RATIONALE

The standard developers considered the matter of adding a special device for cloning master pseudo-terminals: the /dev/ptmx device. However, consensus could not be reached, and it was felt that adding a new function would permit other implementations. The posix_openpt() function is designed to complement the grantpt(), ptsname(), and unlockpt() functions.

On implementations supporting the /dev/ptmx clone device, opening the master device of a pseudo-terminal is simply:

mfdp = open("/dev/ptmx", oflag );
if (mfdp < 0)
    return -1;

FUTURE DIRECTIONS

None.

SEE ALSO

grantpt() , open() , ptsname() , unlockpt() , the Base Definitions volume of IEEE Std 1003.1-2001, <fcntl.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tcsendbreak(3p)

TCSENDBREAK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tcsendbreak - send a break for a specific duration

SYNOPSIS

#include <termios.h>

int tcsendbreak(int fildes, int duration);

DESCRIPTION

If the terminal is using asynchronous serial data transmission, tcsendbreak() shall cause transmission of a continuous stream of zero-valued bits for a specific duration. If duration is 0, it shall cause transmission of zero-valued bits for at least 0.25 seconds, and not more than 0.5 seconds. If duration is not 0, it shall send zero-valued bits for an implementation-defined period of time.

The fildes argument is an open file descriptor associated with a terminal.

If the terminal is not using asynchronous serial data transmission, it is implementation-defined whether tcsendbreak() sends data to generate a break condition or returns without taking any action.

Attempts to use tcsendbreak() from a process which is a member of a background process group on a fildes associated with its controlling terminal shall cause the process group to be sent a SIGTTOU signal. If the calling process is blocking or ignoring SIGTTOU signals, the process shall be allowed to perform the operation, and no signal is sent.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The tcsendbreak() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
ENOTTY
The file associated with fildes is not a terminal.

The tcsendbreak() function may fail if:

EIO
The process group of the writing process is orphaned, and the writing process is not ignoring or blocking SIGTTOU.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, Chapter 11, General Terminal Interface, <termios.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


vprintf(3p)

VFPRINTF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

vfprintf, vprintf, vsnprintf, vsprintf - format output of a stdarg argument list

SYNOPSIS

#include <stdarg.h>
#include <stdio.h>

int vfprintf(FILE *restrict stream, const char *restrict format,
va_list ap);
int vprintf(const char *restrict format, va_list ap);
int vsnprintf(char *restrict s, size_t n, const char *restrict format,
va_list ap);
int vsprintf(char *restrict s, const char *restrict format, va_list ap);

DESCRIPTION

The vprintf(), vfprintf(), vsnprintf(), and vsprintf() functions shall be equivalent to printf(), fprintf(), snprintf(), and sprintf() respectively, except that instead of being called with a variable number of arguments, they are called with an argument list as defined by <stdarg.h>.

These functions shall not invoke the va_end macro. As these functions invoke the va_arg macro, the value of ap after the return is unspecified.

RETURN VALUE

Refer to fprintf() .

ERRORS

Refer to fprintf() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions should call va_end(ap) afterwards to clean up.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fprintf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdarg.h>, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutexattr_gettype(3p)

PTHREAD_MUTEXATTR_GETTYPE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutexattr_gettype, pthread_mutexattr_settype - get and set the mutex type attribute

SYNOPSIS

#include <pthread.h>

int pthread_mutexattr_gettype(const pthread_mutexattr_t *restrict attr,
int *restrict type);
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);

DESCRIPTION

The pthread_mutexattr_gettype() and pthread_mutexattr_settype() functions, respectively, shall get and set the mutex type attribute. This attribute is set in the type parameter to these functions. The default value of the type attribute is PTHREAD_MUTEX_DEFAULT.

The type of mutex is contained in the type attribute of the mutex attributes. Valid mutex types include:

PTHREAD_MUTEX_NORMAL

This type of mutex does not detect deadlock. A thread attempting to relock this mutex without first unlocking it shall deadlock. Attempting to unlock a mutex locked by a different thread results in undefined behavior. Attempting to unlock an unlocked mutex results in undefined behavior.

PTHREAD_MUTEX_ERRORCHECK

This type of mutex provides error checking. A thread attempting to relock this mutex without first unlocking it shall return with an error. A thread attempting to unlock a mutex which another thread has locked shall return with an error. A thread attempting to unlock an unlocked mutex shall return with an error.

PTHREAD_MUTEX_RECURSIVE

A thread attempting to relock this mutex without first unlocking it shall succeed in locking the mutex. The relocking deadlock which can occur with mutexes of type PTHREAD_MUTEX_NORMAL cannot occur with this type of mutex. Multiple locks of this mutex shall require the same number of unlocks to release the mutex before another thread can acquire the mutex. A thread attempting to unlock a mutex which another thread has locked shall return with an error. A thread attempting to unlock an unlocked mutex shall return with an error.

PTHREAD_MUTEX_DEFAULT

Attempting to recursively lock a mutex of this type results in undefined behavior. Attempting to unlock a mutex of this type which was not locked by the calling thread results in undefined behavior. Attempting to unlock a mutex of this type which is not locked results in undefined behavior. An implementation may map this mutex to one of the other mutex types.

RETURN VALUE

Upon successful completion, the pthread_mutexattr_gettype() function shall return zero and store the value of the type attribute of attr into the object referenced by the type parameter. Otherwise, an error shall be returned to indicate the error.

If successful, the pthread_mutexattr_settype() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_mutexattr_settype() function shall fail if:

EINVAL
The value type is invalid.

The pthread_mutexattr_gettype() and pthread_mutexattr_settype() functions may fail if:

EINVAL
The value specified by attr is invalid.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

It is advised that an application should not use a PTHREAD_MUTEX_RECURSIVE mutex with condition variables because the implicit unlock performed for a pthread_cond_timedwait() or pthread_cond_wait() may not actually release the mutex (if it had been locked multiple times). If this happens, no other thread can satisfy the condition of the predicate.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_timedwait() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


signal(3p)

SIGNAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

signal - signal management

SYNOPSIS

#include <signal.h>

void (*signal(int sig, void (*func)(int)))(int);

DESCRIPTION

Use of this function is unspecified in a multi-threaded process.

The signal() function chooses one of three ways in which receipt of the signal number sig is to be subsequently handled. If the value of func is SIG_DFL, default handling for that signal shall occur. If the value of func is SIG_IGN, the signal shall be ignored. Otherwise, the application shall ensure that func points to a function to be called when that signal occurs. An invocation of such a function because of a signal, or (recursively) of any further functions called by that invocation (other than functions in the standard library), is called a "signal handler".

When a signal occurs, and func points to a function, it is implementation-defined whether the equivalent of a:

signal(sig, SIG_DFL);

is executed or the implementation prevents some implementation-defined set of signals (at least including sig) from occurring until the current signal handling has completed. (If the value of sig is SIGILL, the implementation may alternatively define that no action is taken.) Next the equivalent of:

(*func)(sig);

is executed. If and when the function returns, if the value of sig was SIGFPE, SIGILL, or SIGSEGV or any other implementation-defined value corresponding to a computational exception, the behavior is undefined. Otherwise, the program shall resume execution at the point it was interrupted. If the signal occurs as the result of calling the abort(), raise(), kill(), pthread_kill(), or sigqueue() function, the signal handler shall not call the raise() function.

If the signal occurs other than as the result of calling abort(), raise(), kill(), pthread_kill(), or sigqueue(), the behavior is undefined if the signal handler refers to any object with static storage duration other than by assigning a value to an object declared as volatile sig_atomic_t, or if the signal handler calls any function in the standard library other than one of the functions listed in Signal Concepts . Furthermore, if such a call fails, the value of errno is unspecified.

At program start-up, the equivalent of:

signal(sig, SIG_IGN);

is executed for some signals, and the equivalent of:

signal(sig, SIG_DFL);

is executed for all other signals (see exec).

RETURN VALUE

If the request can be honored, signal() shall return the value of func for the most recent call to signal() for the specified signal sig. Otherwise, SIG_ERR shall be returned and a positive value shall be stored in errno.

ERRORS

The signal() function shall fail if:

EINVAL
The sig argument is not a valid signal number or an attempt is made to catch a signal that cannot be caught or ignore a signal that cannot be ignored.

The signal() function may fail if:

EINVAL
An attempt was made to set the action to SIG_DFL for a signal that cannot be caught or ignored (or both).

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sigaction() function provides a more comprehensive and reliable mechanism for controlling signals; new applications should use sigaction() rather than signal().

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , exec() , pause() , sigaction() , sigsuspend() , waitid() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ceil(3p)

CEIL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ceil, ceilf, ceill - ceiling value function

SYNOPSIS

#include <math.h>

double ceil(double x);
float ceilf(float x);
long double ceill(long double x);

DESCRIPTION

These functions shall compute the smallest integral value not less than x.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, ceil(), ceilf(), and ceill() shall return the smallest integral value not less than x, expressed as a type double, float, or long double, respectively.

If x is NaN, a NaN shall be returned.

If x is ±0 or ±Inf, x shall be returned.

If the correct value would cause overflow, a range error shall occur and ceil(), ceilf(), and ceill() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.

ERRORS

These functions shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The integral value returned by these functions need not be expressible as an int or long. The return value should be tested before assigning it to an integer type to avoid the undefined results of an integer overflow.

The ceil() function can only overflow when the floating-point representation has DBL_MANT_DIG > DBL_MAX_EXP.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , floor() , isnan() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getsubopt(3p)

GETSUBOPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getsubopt - parse suboption arguments from a string

SYNOPSIS

#include <stdlib.h>

int getsubopt(char **optionp, char * const *keylistp, char **valuep);

DESCRIPTION

The getsubopt() function shall parse suboption arguments in a flag argument. Such options often result from the use of getopt().

The getsubopt() argument optionp is a pointer to a pointer to the option argument string. The suboption arguments shall be separated by commas and each may consist of either a single token, or a token-value pair separated by an equal sign.

The keylistp argument shall be a pointer to a vector of strings. The end of the vector is identified by a null pointer. Each entry in the vector is one of the possible tokens that might be found in *optionp. Since commas delimit suboption arguments in optionp, they should not appear in any of the strings pointed to by keylistp. Similarly, because an equal sign separates a token from its value, the application should not include an equal sign in any of the strings pointed to by keylistp.

The valuep argument is the address of a value string pointer.

If a comma appears in optionp, it shall be interpreted as a suboption separator. After commas have been processed, if there are one or more equal signs in a suboption string, the first equal sign in any suboption string shall be interpreted as a separator between a token and a value. Subsequent equal signs in a suboption string shall be interpreted as part of the value.

If the string at *optionp contains only one suboption argument (equivalently, no commas), getsubopt() shall update *optionp to point to the null character at the end of the string. Otherwise, it shall isolate the suboption argument by replacing the comma separator with a null character, and shall update *optionp to point to the start of the next suboption argument. If the suboption argument has an associated value (equivalently, contains an equal sign), getsubopt() shall update *valuep to point to the value's first character. Otherwise, it shall set *valuep to a null pointer. The calling application may use this information to determine whether the presence or absence of a value for the suboption is an error.

Additionally, when getsubopt() fails to match the suboption argument with a token in the keylistp array, the calling application should decide if this is an error, or if the unrecognized option should be processed in another way.

RETURN VALUE

The getsubopt() function shall return the index of the matched token string, or -1 if no token strings were matched.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

#include <stdio.h>
#include <stdlib.h>

int do_all;
const char *type;
int read_size;
int write_size;
int read_only;

enum
{
    RO_OPTION = 0,
    RW_OPTION,
    READ_SIZE_OPTION,
    WRITE_SIZE_OPTION
};

const char *mount_opts[] =
{
    [RO_OPTION] = "ro",
    [RW_OPTION] = "rw",
    [READ_SIZE_OPTION] = "rsize",
    [WRITE_SIZE_OPTION] = "wsize",
    NULL
};

int
main(int argc, char *argv[])
{
    char *subopts, *value;
    int opt;

    while ((opt = getopt(argc, argv, "at:o:")) != -1)
        switch(opt)
            {
            case 'a':
                do_all = 1;
                break;
            case 't':
                type = optarg;
                break;
            case 'o':
                subopts = optarg;
                while (*subopts != '\0')
                    switch(getsubopt(&subopts, mount_opts, &value))
                {
                case RO_OPTION:
                    read_only = 1;
                    break;
                case RW_OPTION:
                    read_only = 0;
                    break;
                case READ_SIZE_OPTION:
                    if (value == NULL)
                        abort();
                    read_size = atoi(value);
                    break;
                case WRITE_SIZE_OPTION:
                    if (value == NULL)
                        abort();
                    write_size = atoi(value);
                    break;
                default:
                    /* Unknown suboption. */
                    printf("Unknown suboption `%s'\n", value);
                    break;
                }
            break;
        default:
            abort();
        }

    /* Do the real work. */

    return 0;
}

Parsing Suboptions

The following example uses the getsubopt() function to parse a value argument in the optarg external variable returned by a call to getopt().

#include <stdlib.h>
...
char *tokens[] = {"HOME", "PATH", "LOGNAME", (char *) NULL };
char *value;
int opt, index;

while ((opt = getopt(argc, argv, "e:")) != -1) {
    switch(opt)  {
    case 'e' :
        while ((index = getsubopt(&optarg, tokens, &value)) != -1) {
            switch(index) {
...
        }
        break;
...
    }
}
...

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getopt() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


readv(3p)

READV

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

readv - read a vector

SYNOPSIS

#include <sys/uio.h>

ssize_t readv(int fildes, const struct iovec *iov, int iovcnt);

DESCRIPTION

The readv() function shall be equivalent to read(), except as described below. The readv() function shall place the input data into the iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[ iovcnt-1]. The iovcnt argument is valid if greater than 0 and less than or equal to {IOV_MAX}.

Each iovec entry specifies the base address and length of an area in memory where data should be placed. The readv() function shall always fill an area completely before proceeding to the next.

Upon successful completion, readv() shall mark for update the st_atime field of the file.

RETURN VALUE

Refer to read() .

ERRORS

Refer to read() .

In addition, the readv() function shall fail if:

EINVAL
The sum of the iov_len values in the iov array overflowed an ssize_t.

The readv() function may fail if:

EINVAL
The iovcnt argument was less than or equal to 0, or greater than {IOV_MAX}.

The following sections are informative.

EXAMPLES

Reading Data into an Array

The following example reads data from the file associated with the file descriptor fd into the buffers specified by members of the iov array.

#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
...
ssize_t bytes_read;
int fd;
char buf0[20];
char buf1[30];
char buf2[40];
int iovcnt;
struct iovec iov[3];

iov[0].iov_base = buf0;
iov[0].iov_len = sizeof(buf0);
iov[1].iov_base = buf1;
iov[1].iov_len = sizeof(buf1);
iov[2].iov_base = buf2;
iov[2].iov_len = sizeof(buf2);
...
iovcnt = sizeof(iov) / sizeof(struct iovec);

bytes_read = readv(fd, iov, iovcnt);
...

APPLICATION USAGE

None.

RATIONALE

Refer to read() .

FUTURE DIRECTIONS

None.

SEE ALSO

read() , writev() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/uio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wmemchr(3p)

WMEMCHR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wmemchr - find a wide character in memory

SYNOPSIS

#include <wchar.h>

wchar_t *wmemchr(const wchar_t *ws, wchar_t wc, size_t n);

DESCRIPTION

The wmemchr() function shall locate the first occurrence of wc in the initial n wide characters of the object pointed to by ws. This function shall not be affected by locale and all wchar_t values shall be treated identically. The null wide character and wchar_t values not corresponding to valid characters shall not be treated specially.

If n is zero, the application shall ensure that ws is a valid pointer and the function behaves as if no valid occurrence of wc is found.

RETURN VALUE

The wmemchr() function shall return a pointer to the located wide character, or a null pointer if the wide character does not occur in the object.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wmemcmp() , wmemcpy() , wmemmove() , wmemset() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_barrierattr_setpshared (3p)

 Continue to this page.


posix_trace_attr_getmaxusereventsize (3p)

 Continue to this page.


isnormal(3p)

ISNORMAL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

isnormal - test for a normal value

SYNOPSIS

#include <math.h>

int isnormal(real-floating x);

DESCRIPTION

The isnormal() macro shall determine whether its argument value is normal (neither zero, subnormal, infinite, nor NaN). First, an argument represented in a format wider than its semantic type is converted to its semantic type. Then determination is based on the type of the argument.

RETURN VALUE

The isnormal() macro shall return a non-zero value if and only if its argument has a normal value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fpclassify() , isfinite() , isinf() , isnan() , signbit() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strerror_r (3p)

 Continue to this page.


setlocale(3p)

SETLOCALE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setlocale - set program locale

SYNOPSIS

#include <locale.h>

char *setlocale(int category, const char *locale);

DESCRIPTION

The setlocale() function selects the appropriate piece of the program's locale, as specified by the category and locale arguments, and may be used to change or query the program's entire locale or portions thereof. The value LC_ALL for category names the program's entire locale; other values for category name only a part of the program's locale:

LC_COLLATE
Affects the behavior of regular expressions and the collation functions.
LC_CTYPE
Affects the behavior of regular expressions, character classification, character conversion functions, and wide-character functions.
LC_MESSAGES
Affects what strings are expected by commands and utilities as affirmative or negative responses.

It also affects what strings are given by commands and utilities as affirmative or negative responses, and the content of messages.

LC_MONETARY
Affects the behavior of functions that handle monetary values.
LC_NUMERIC
Affects the behavior of functions that handle numeric values.
LC_TIME
Affects the behavior of the time conversion functions.

The locale argument is a pointer to a character string containing the required setting of category. The contents of this string are implementation-defined. In addition, the following preset values of locale are defined for all settings of category:

"POSIX"
Specifies the minimal environment for C-language translation called the POSIX locale. If setlocale() is not invoked, the POSIX locale is the default at entry to main().
"C"
Equivalent to "POSIX" .
""
Specifies an implementation-defined native environment. This corresponds to the value of the associated environment variables, LC_* and LANG ; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale and the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables.
A null pointer
Used to direct setlocale() to query the current internationalized environment and return the name of the locale.

The locale state is common to all threads within a process.

RETURN VALUE

Upon successful completion, setlocale() shall return the string associated with the specified category for the new locale. Otherwise, setlocale() shall return a null pointer and the program's locale is not changed.

A null pointer for locale causes setlocale() to return a pointer to the string associated with the category for the program's current locale. The program's locale shall not be changed.

The string returned by setlocale() is such that a subsequent call with that string and its associated category shall restore that part of the program's locale. The application shall not modify the string returned which may be overwritten by a subsequent call to setlocale().

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The following code illustrates how a program can initialize the international environment for one language, while selectively modifying the program's locale such that regular expressions and string operations can be applied to text recorded in a different language:

setlocale(LC_ALL, "De");
setlocale(LC_COLLATE, "Fr@dict");

Internationalized programs must call setlocale() to initiate a specific language operation. This can be done by calling setlocale() as follows:

setlocale(LC_ALL, "");

Changing the setting of LC_MESSAGES has no effect on catalogs that have already been opened by calls to catopen().

RATIONALE

The ISO C standard defines a collection of functions to support internationalization. One of the most significant aspects of these functions is a facility to set and query the international environment. The international environment is a repository of information that affects the behavior of certain functionality, namely:

1.
Character handling

2.
Collating

3.
Date/time formatting

4.
Numeric editing

5.
Monetary formatting

6.
Messaging

The setlocale() function provides the application developer with the ability to set all or portions, called categories, of the international environment. These categories correspond to the areas of functionality mentioned above. The syntax for setlocale() is as follows:

char *setlocale(int category, const char *locale);

where category is the name of one of following categories, namely:

LC_COLLATE

LC_CTYPE

LC_MESSAGES

LC_MONETARY

LC_NUMERIC

LC_TIME

In addition, a special value called LC_ALL directs setlocale() to set all categories.

There are two primary uses of setlocale():

1.
Querying the international environment to find out what it is set to

2.
Setting the international environment, or locale, to a specific value

The behavior of setlocale() in these two areas is described below. Since it is difficult to describe the behavior in words, examples are used to illustrate the behavior of specific uses.

To query the international environment, setlocale() is invoked with a specific category and the NULL pointer as the locale. The NULL pointer is a special directive to setlocale() that tells it to query rather than set the international environment. The following syntax is used to query the name of the international environment:

setlocale({LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, \
    LC_NUMERIC, LC_TIME},(char *) NULL);

The setlocale() function shall return the string corresponding to the current international environment. This value may be used by a subsequent call to setlocale() to reset the international environment to this value. However, it should be noted that the return value from setlocale() may be a pointer to a static area within the function and is not guaranteed to remain unchanged (that is, it may be modified by a subsequent call to setlocale()). Therefore, if the purpose of calling setlocale() is to save the value of the current international environment so it can be changed and reset later, the return value should be copied to an array of char in the calling program.

There are three ways to set the international environment with setlocale():

setlocale(category, string)

This usage sets a specific category in the international environment to a specific value corresponding to the value of the string. A specific example is provided below:

setlocale(LC_ALL, "fr_FR.ISO-8859-1");

In this example, all categories of the international environment are set to the locale corresponding to the string "fr_FR.ISO-8859-1" , or to the French language as spoken in France using the ISO/IEC 8859-1:1998 standard codeset.

If the string does not correspond to a valid locale, setlocale() shall return a NULL pointer and the international environment is not changed. Otherwise, setlocale() shall return the name of the locale just set.

setlocale(category, "C")

The ISO C standard states that one locale must exist on all conforming implementations. The name of the locale is C and corresponds to a minimal international environment needed to support the C programming language.

setlocale(category, "")

This sets a specific category to an implementation-defined default. This corresponds to the value of the environment variables.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , isalnum() , isalpha() , isblank() , iscntrl() , isdigit() , isgraph() , islower() , isprint() , ispunct() , isspace() , isupper() , iswalnum() , iswalpha() , iswblank() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , isxdigit() , localeconv() , mblen() , mbstowcs() , mbtowc() , nl_langinfo() , printf() , scanf() , setlocale , strcoll() , strerror() , strfmon() , strtod() , strxfrm() , tolower() , toupper() , towlower() , towupper() , wcscoll() , wcstod() , wcstombs() , wcsxfrm() , wctomb() , the Base Definitions volume of IEEE Std 1003.1-2001, <langinfo.h>, <locale.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


write(3p)

WRITE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pwrite, write - write on a file

SYNOPSIS

#include <unistd.h>

ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
off_t offset);
ssize_t write(int fildes, const void *buf, size_t nbyte);

DESCRIPTION

The write() function shall attempt to write nbyte bytes from the buffer pointed to by buf to the file associated with the open file descriptor, fildes.

Before any action described below is taken, and if nbyte is zero and the file is a regular file, the write() function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, the write() function shall return zero and have no other results. If nbyte is zero and the file is not a regular file, the results are unspecified.

On a regular file or other file capable of seeking, the actual writing of data shall proceed from the position in the file indicated by the file offset associated with fildes. Before successful return from write(), the file offset shall be incremented by the number of bytes actually written. On a regular file, if this incremented file offset is greater than the length of the file, the length of the file shall be set to this file offset.

On a file not capable of seeking, writing shall always take place starting at the current position. The value of a file offset associated with such a device is undefined.

If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.

If a write() requests that more bytes be written than there is room for (for example, the process' file size limit or the physical end of a medium), only as many bytes as there is room for shall be written. For example, suppose there is space for 20 bytes more in a file before reaching a limit. A write of 512 bytes will return 20. The next write of a non-zero number of bytes would give a failure return (except as noted below).

If the request would cause the file size to exceed the soft file size limit for the process and there is no room for any bytes to be written, the request shall fail and the implementation shall generate the SIGXFSZ signal for the thread.

If write() is interrupted by a signal before it writes any data, it shall return -1 with errno set to [EINTR].

If write() is interrupted by a signal after it successfully writes some data, it shall return the number of bytes written.

If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined.

After a write() to a regular file has successfully returned:

*
Any successful read() from each byte position in the file that was modified by that write shall return the data specified by the write() for that position until such byte positions are again modified.

*
Any subsequent successful write() to the same byte position in the file shall overwrite that file data.

Write requests to a pipe or FIFO shall be handled in the same way as a regular file with the following exceptions:

*
There is no file offset associated with a pipe, hence each write request shall append to the end of the pipe.

*
Write requests of {PIPE_BUF} bytes or less shall not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set.

*
If the O_NONBLOCK flag is clear, a write request may cause the thread to block, but on normal completion it shall return nbyte.

*
If the O_NONBLOCK flag is set, write() requests shall be handled differently, in the following ways:
*
The write() function shall not block the thread.

*
A write request for {PIPE_BUF} or fewer bytes shall have the following effect: if there is sufficient space available in the pipe, write() shall transfer all the data and return the number of bytes requested. Otherwise, write() shall transfer no data and return -1 with errno set to [EAGAIN].

*
A write request for more than {PIPE_BUF} bytes shall cause one of the following:
*
When at least one byte can be written, transfer what it can and return the number of bytes written. When all data previously written to the pipe is read, it shall transfer at least {PIPE_BUF} bytes.

*
When no data can be written, transfer no data, and return -1 with errno set to [EAGAIN].

When attempting to write to a file descriptor (other than a pipe or FIFO) that supports non-blocking writes and cannot accept the data immediately:

*
If the O_NONBLOCK flag is clear, write() shall block the calling thread until the data can be accepted.

*
If the O_NONBLOCK flag is set, write() shall not block the thread. If some data can be written without blocking the thread, write() shall write what it can and return the number of bytes written. Otherwise, it shall return -1 and set errno to [EAGAIN].

Upon successful completion, where nbyte is greater than 0, write() shall mark for update the st_ctime and st_mtime fields of the file, and if the file is a regular file, the S_ISUID and S_ISGID bits of the file mode may be cleared.

For regular files, no data transfer shall occur past the offset maximum established in the open file description associated with fildes.

If fildes refers to a socket, write() shall be equivalent to send() with no flags set.

If the O_DSYNC bit has been set, write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.

If the O_SYNC bit has been set, write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.

If fildes refers to a shared memory object, the result of the write() function is unspecified.

If fildes refers to a typed memory object, the result of the write() function is unspecified.

If fildes refers to a STREAM, the operation of write() shall be determined by the values of the minimum and maximum nbyte range (packet size) accepted by the STREAM. These values are determined by the topmost STREAM module. If nbyte falls within the packet size range, nbyte bytes shall be written. If nbyte does not fall within the range and the minimum packet size value is 0, write() shall break the buffer into maximum packet size segments prior to sending the data downstream (the last segment may contain less than the maximum packet size). If nbyte does not fall within the range and the minimum value is non-zero, write() shall fail with errno set to [ERANGE]. Writing a zero-length buffer ( nbyte is 0) to a STREAMS device sends 0 bytes with 0 returned. However, writing a zero-length buffer to a STREAMS-based pipe or FIFO sends no message and 0 is returned. The process may issue I_SWROPT ioctl() to enable zero-length messages to be sent across the pipe or FIFO.

When writing to a STREAM, data messages are created with a priority band of 0. When writing to a STREAM that is not a pipe or FIFO:

*
If O_NONBLOCK is clear, and the STREAM cannot accept data (the STREAM write queue is full due to internal flow control conditions), write() shall block until data can be accepted.

*
If O_NONBLOCK is set and the STREAM cannot accept data, write() shall return -1 and set errno to [EAGAIN].

*
If O_NONBLOCK is set and part of the buffer has been written while a condition in which the STREAM cannot accept additional data occurs, write() shall terminate and return the number of bytes written.

In addition, write() shall fail if the STREAM head has processed an asynchronous error before the call. In this case, the value of errno does not reflect the result of write(), but reflects the prior error.

The pwrite() function shall be equivalent to write(), except that it writes into a given position without changing the file pointer. The first three arguments to pwrite() are the same as write() with the addition of a fourth argument offset for the desired position inside the file.

RETURN VALUE

Upon successful completion, write() and pwrite() shall return the number of bytes actually written to the file associated with fildes. This number shall never be greater than nbyte. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The write() and pwrite() functions shall fail if:

EAGAIN
The O_NONBLOCK flag is set for the file descriptor and the thread would be delayed in the write() operation.
EBADF
The fildes argument is not a valid file descriptor open for writing.
EFBIG
An attempt was made to write a file that exceeds the implementation-defined maximum file size or the process' file size limit, and there was no room for any bytes to be written.
EFBIG
The file is a regular file, nbyte is greater than 0, and the starting position is greater than or equal to the offset maximum established in the open file description associated with fildes.
EINTR
The write operation was terminated due to the receipt of a signal, and no data was transferred.
EIO
The process is a member of a background process group attempting to write to its controlling terminal, TOSTOP is set, the process is neither ignoring nor blocking SIGTTOU, and the process group of the process is orphaned. This error may also be returned under implementation-defined conditions.
ENOSPC
There was no free space remaining on the device containing the file.
EPIPE
An attempt is made to write to a pipe or FIFO that is not open for reading by any process, or that only has one end open. A SIGPIPE signal shall also be sent to the thread.
ERANGE
The transfer request size was outside the range supported by the STREAMS file associated with fildes.

The write() function shall fail if:

EAGAIN or EWOULDBLOCK

The file descriptor is for a socket, is marked O_NONBLOCK, and write would block.

ECONNRESET
A write was attempted on a socket that is not connected.
EPIPE
A write was attempted on a socket that is shut down for writing, or is no longer connected. In the latter case, if the socket is of type SOCK_STREAM, the SIGPIPE signal is generated to the calling process.

The write() and pwrite() functions may fail if:

EINVAL
The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer.
EIO
A physical I/O error has occurred.
ENOBUFS
Insufficient resources were available in the system to perform the operation.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.
ENXIO
A hangup occurred on the STREAM being written to.

A write to a STREAMS file may fail if an error message has been received at the STREAM head. In this case, errno is set to the value included in the error message.

The write() function may fail if:

EACCES
A write was attempted on a socket and the calling process does not have appropriate privileges.
ENETDOWN
A write was attempted on a socket and the local network interface used to reach the destination is down.
ENETUNREACH

A write was attempted on a socket and no route to the network is present.

The pwrite() function shall fail and the file pointer remain unchanged if:

EINVAL
The offset argument is invalid. The value is negative.
ESPIPE
fildes is associated with a pipe or FIFO.

The following sections are informative.

EXAMPLES

Writing from a Buffer

The following example writes data from the buffer pointed to by buf to the file associated with the file descriptor fd.

#include <sys/types.h>
#include <string.h>
...
char buf[20];
size_t nbytes;
ssize_t bytes_written;
int fd;
...
strcpy(buf, "This is a test\n");
nbytes = strlen(buf);

bytes_written = write(fd, buf, nbytes);
...

APPLICATION USAGE

None.

RATIONALE

See also the RATIONALE section in read() .

An attempt to write to a pipe or FIFO has several major characteristics:

*
Atomic/non-atomic: A write is atomic if the whole amount written in one operation is not interleaved with data from any other process. This is useful when there are multiple writers sending data to a single reader. Applications need to know how large a write request can be expected to be performed atomically. This maximum is called {PIPE_BUF}. This volume of IEEE Std 1003.1-2001 does not say whether write requests for more than {PIPE_BUF} bytes are atomic, but requires that writes of {PIPE_BUF} or fewer bytes shall be atomic.

*
Blocking/immediate: Blocking is only possible with O_NONBLOCK clear. If there is enough space for all the data requested to be written immediately, the implementation should do so. Otherwise, the process may block; that is, pause until enough space is available for writing. The effective size of a pipe or FIFO (the maximum amount that can be written in one operation without blocking) may vary dynamically, depending on the implementation, so it is not possible to specify a fixed value for it.

*
Complete/partial/deferred: A write request:

int fildes;
size_t nbyte;
ssize_t ret;
char *buf;

ret = write(fildes, buf, nbyte);

may return:

Complete
ret=nbyte
Partial
ret<nbyte

This shall never happen if nbyte<= {PIPE_BUF}. If it does happen (with nbyte> {PIPE_BUF}), this volume of IEEE Std 1003.1-2001 does not guarantee atomicity, even if ret<= {PIPE_BUF}, because atomicity is guaranteed according to the amount requested, not the amount written.

Deferred:
ret=-1, errno=[EAGAIN]

This error indicates that a later request may succeed. It does not indicate that it shall succeed, even if nbyte<= {PIPE_BUF}, because if no process reads from the pipe or FIFO, the write never succeeds. An application could usefully count the number of times [EAGAIN] is caused by a particular value of nbyte> {PIPE_BUF} and perhaps do later writes with a smaller value, on the assumption that the effective size of the pipe may have decreased.

Partial and deferred writes are only possible with O_NONBLOCK set.

The relations of these properties are shown in the following tables:
Write to a Pipe or FIFO with O_NONBLOCK clear |  |  |
Immediately Writable: | None | Some | nbyte
nbyte<={PIPE_BUF} | Atomic blocking | Atomic blocking | Atomic immediate
 | nbyte | nbyte | nbyte
nbyte>{PIPE_BUF} | Blocking nbyte | Blocking nbyte | Blocking nbyte

If the O_NONBLOCK flag is clear, a write request shall block if the amount writable immediately is less than that requested. If the flag is set (by fcntl()), a write request shall never block.
Write to a Pipe or FIFO with O_NONBLOCK set |  |  |
Immediately Writable: | None | Some | nbyte
nbyte<={PIPE_BUF} | -1, [EAGAIN] | -1, [EAGAIN] | Atomic nbyte
nbyte>{PIPE_BUF} | -1, [EAGAIN] | <nbyte or -1, | <=nbyte or -1,
 |  | [EAGAIN] | [EAGAIN]

There is no exception regarding partial writes when O_NONBLOCK is set. With the exception of writing to an empty pipe, this volume of IEEE Std 1003.1-2001 does not specify exactly when a partial write is performed since that would require specifying internal details of the implementation. Every application should be prepared to handle partial writes when O_NONBLOCK is set and the requested amount is greater than {PIPE_BUF}, just as every application should be prepared to handle partial writes on other kinds of file descriptors.

The intent of forcing writing at least one byte if any can be written is to assure that each write makes progress if there is any room in the pipe. If the pipe is empty, {PIPE_BUF} bytes must be written; if not, at least some progress must have been made.

Where this volume of IEEE Std 1003.1-2001 requires -1 to be returned and errno set to [EAGAIN], most historical implementations return zero (with the O_NDELAY flag set, which is the historical predecessor of O_NONBLOCK, but is not itself in this volume of IEEE Std 1003.1-2001). The error indications in this volume of IEEE Std 1003.1-2001 were chosen so that an application can distinguish these cases from end-of-file. While write() cannot receive an indication of end-of-file, read() can, and the two functions have similar return values. Also, some existing systems (for example, Eighth Edition) permit a write of zero bytes to mean that the reader should get an end-of-file indication; for those systems, a return value of zero from write() indicates a successful write of an end-of-file indication.

Implementations are allowed, but not required, to perform error checking for write() requests of zero bytes.

The concept of a {PIPE_MAX} limit (indicating the maximum number of bytes that can be written to a pipe in a single operation) was considered, but rejected, because this concept would unnecessarily limit application writing.

See also the discussion of O_NONBLOCK in read() .

Writes can be serialized with respect to other reads and writes. If a read() of file data can be proven (by any means) to occur after a write() of the data, it must reflect that write(), even if the calls are made by different processes. A similar requirement applies to multiple write operations to the same file position. This is needed to guarantee the propagation of data from write() calls to subsequent read() calls. This requirement is particularly significant for networked file systems, where some caching schemes violate these semantics.

Note that this is specified in terms of read() and write(). The XSI extensions readv() and writev() also obey these semantics. A new "high-performance" write analog that did not follow these serialization requirements would also be permitted by this wording. This volume of IEEE Std 1003.1-2001 is also silent about any effects of application-level caching (such as that done by stdio).

This volume of IEEE Std 1003.1-2001 does not specify the value of the file offset after an error is returned; there are too many cases. For programming errors, such as [EBADF], the concept is meaningless since no file is involved. For errors that are detected immediately, such as [EAGAIN], clearly the pointer should not change. After an interrupt or hardware error, however, an updated value would be very useful and is the behavior of many implementations.

This volume of IEEE Std 1003.1-2001 does not specify behavior of concurrent writes to a file from multiple processes. Applications should use some form of concurrency control.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , creat() , dup() , fcntl() , getrlimit() , lseek() , open() , pipe() , ulimit() , writev() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <stropts.h>, <sys/uio.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawn_file_actions_addclose (3p)

 Continue to this page.


openlog (3p)

 Continue to this page.


pthread_cleanup_pop (3p)

 Continue to this page.


wmemcmp(3p)

WMEMCMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wmemcmp - compare wide characters in memory

SYNOPSIS

#include <wchar.h>

int wmemcmp(const wchar_t *ws1, const wchar_t *ws2, size_t n);

DESCRIPTION

The wmemcmp() function shall compare the first n wide characters of the object pointed to by ws1 to the first n wide characters of the object pointed to by ws2. This function shall not be affected by locale and all wchar_t values shall be treated identically. The null wide character and wchar_t values not corresponding to valid characters shall not be treated specially.

If n is zero, the application shall ensure that ws1 and ws2 are valid pointers, and the function shall behave as if the two objects compare equal.

RETURN VALUE

The wmemcmp() function shall return an integer greater than, equal to, or less than zero, respectively, as the object pointed to by ws1 is greater than, equal to, or less than the object pointed to by ws2.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wmemchr() , wmemcpy() , wmemmove() , wmemset() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_condattr_getpshared(3p)

PTHREAD_CONDATTR_GETPSHARED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_condattr_getpshared, pthread_condattr_setpshared - get and set the process-shared condition variable attributes

SYNOPSIS

#include <pthread.h>

int pthread_condattr_getpshared(const pthread_condattr_t *restrict attr,
int *restrict pshared);
int pthread_condattr_setpshared(pthread_condattr_t *attr,
int pshared);

DESCRIPTION

The pthread_condattr_getpshared() function shall obtain the value of the process-shared attribute from the attributes object referenced by attr. The pthread_condattr_setpshared() function shall set the process-shared attribute in an initialized attributes object referenced by attr.

The process-shared attribute is set to PTHREAD_PROCESS_SHARED to permit a condition variable to be operated upon by any thread that has access to the memory where the condition variable is allocated, even if the condition variable is allocated in memory that is shared by multiple processes. If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the condition variable shall only be operated upon by threads created within the same process as the thread that initialized the condition variable; if threads of differing processes attempt to operate on such a condition variable, the behavior is undefined. The default value of the attribute is PTHREAD_PROCESS_PRIVATE.

RETURN VALUE

If successful, the pthread_condattr_setpshared() function shall return zero; otherwise, an error number shall be returned to indicate the error.

If successful, the pthread_condattr_getpshared() function shall return zero and store the value of the process-shared attribute of attr into the object referenced by the pshared parameter. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_condattr_getpshared() and pthread_condattr_setpshared() functions may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_condattr_setpshared() function may fail if:

EINVAL
The new value specified for the attribute is outside the range of legal values for that attribute.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_create() , pthread_cond_destroy() , pthread_condattr_destroy() , pthread_mutex_destroy() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getpwuid(3p)

GETPWUID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getpwuid, getpwuid_r - search user database for a user ID

SYNOPSIS

#include <pwd.h>

struct passwd *getpwuid(uid_t uid);

int getpwuid_r(uid_t uid, struct passwd *pwd, char *buffer,
size_t bufsize, struct passwd **result);

DESCRIPTION

The getpwuid() function shall search the user database for an entry with a matching uid.

The getpwuid() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

Applications wishing to check for error situations should set errno to 0 before calling getpwuid(). If getpwuid() returns a null pointer and errno is set to non-zero, an error occurred.

The getpwuid_r() function shall update the passwd structure pointed to by pwd and store a pointer to that structure at the location pointed to by result. The structure shall contain an entry from the user database with a matching uid. Storage referenced by the structure is allocated from the memory provided with the buffer parameter, which is bufsize bytes in size. The maximum size needed for this buffer can be determined with the {_SC_GETPW_R_SIZE_MAX} sysconf() parameter. A NULL pointer shall be returned at the location pointed to by result on error or if the requested entry is not found.

RETURN VALUE

The getpwuid() function shall return a pointer to a struct passwd with the structure as defined in <pwd.h> with a matching entry if found. A null pointer shall be returned if the requested entry is not found, or an error occurs. On error, errno shall be set to indicate the error.

The return value may point to a static area which is overwritten by a subsequent call to getpwent(), getpwnam(), or getpwuid().

If successful, the getpwuid_r() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The getpwuid() and getpwuid_r() functions may fail if:

EIO
An I/O error has occurred.
EINTR
A signal was caught during getpwuid().
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.

The getpwuid_r() function may fail if:

ERANGE
Insufficient storage was supplied via buffer and bufsize to contain the data to be referenced by the resulting passwd structure.

The following sections are informative.

EXAMPLES

Getting an Entry for the Root User

The following example gets the user database entry for the user with user ID 0 (root).

#include <sys/types.h>
#include <pwd.h>
...
uid_t id = 0;
struct passwd *pwd;

pwd = getpwuid(id);

Finding the Name for the Effective User ID

The following example defines pws as a pointer to a structure of type passwd, which is used to store the structure pointer returned by the call to the getpwuid() function. The geteuid() function shall return the effective user ID of the calling process; this is used as the search criteria for the getpwuid() function. The call to getpwuid() shall return a pointer to the structure containing that user ID value.

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
...
struct passwd *pws;
pws = getpwuid(geteuid());

Finding an Entry in the User Database

The following example uses getpwuid() to search the user database for a user ID that was previously stored in a stat structure, then prints out the user name if it is found. If the user is not found, the program prints the numeric value of the user ID for the entry.

#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
...
struct stat statbuf;
struct passwd *pwd;
...
if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
    printf(" %-8.8s", pwd->pw_name);
else
    printf(" %-8d", statbuf.st_uid);

APPLICATION USAGE

Three names associated with the current process can be determined: getpwuid( geteuid()) returns the name associated with the effective user ID of the process; getlogin() returns the name associated with the current login activity; and getpwuid( getuid()) returns the name associated with the real user ID of the process.

The getpwuid_r() function is thread-safe and returns values in a user-supplied buffer instead of possibly using a static data area that may be overwritten by each call.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getpwnam() , geteuid() , getuid() , getlogin() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <pwd.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_barrier_destroy (3p)

 Continue to this page.


iswalnum(3p)

ISWALNUM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswalnum - test for an alphanumeric wide-character code

SYNOPSIS

#include <wctype.h>

int iswalnum(wint_t wc);

DESCRIPTION

The iswalnum() function shall test whether wc is a wide-character code representing a character of class alpha or digit in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswalnum() function shall return non-zero if wc is an alphanumeric wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalpha() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <stdio.h>, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wmemcpy(3p)

WMEMCPY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wmemcpy - copy wide characters in memory

SYNOPSIS

#include <wchar.h>

wchar_t *wmemcpy(wchar_t *restrict ws1, const wchar_t *restrict ws2,
size_t n);

DESCRIPTION

The wmemcpy() function shall copy n wide characters from the object pointed to by ws2 to the object pointed to by ws1. This function shall not be affected by locale and all wchar_t values shall be treated identically. The null wide character and wchar_t values not corresponding to valid characters shall not be treated specially.

If n is zero, the application shall ensure that ws1 and ws2 are valid pointers, and the function shall copy zero wide characters.

RETURN VALUE

The wmemcpy() function shall return the value of ws1.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

wmemchr() , wmemcmp() , wmemmove() , wmemset() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fminf (3p)

 Continue to this page.


pthread_condattr_init(3p)

PTHREAD_CONDATTR_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_condattr_destroy, pthread_condattr_init - destroy and initialize the condition variable attributes object

SYNOPSIS

#include <pthread.h>

int pthread_condattr_destroy(pthread_condattr_t *attr);
int pthread_condattr_init(pthread_condattr_t *attr);

DESCRIPTION

The pthread_condattr_destroy() function shall destroy a condition variable attributes object; the object becomes, in effect, uninitialized. An implementation may cause pthread_condattr_destroy() to set the object referenced by attr to an invalid value. A destroyed attr attributes object can be reinitialized using pthread_condattr_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

The pthread_condattr_init() function shall initialize a condition variable attributes object attr with the default value for all of the attributes defined by the implementation.

Results are undefined if pthread_condattr_init() is called specifying an already initialized attr attributes object.

After a condition variable attributes object has been used to initialize one or more condition variables, any function affecting the attributes object (including destruction) shall not affect any previously initialized condition variables.

This volume of IEEE Std 1003.1-2001 requires two attributes, the clock attribute and the process-shared attribute.

Additional attributes, their default values, and the names of the associated functions to get and set those attribute values are implementation-defined.

RETURN VALUE

If successful, the pthread_condattr_destroy() and pthread_condattr_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_condattr_destroy() function may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_condattr_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the condition variable attributes object.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

See pthread_attr_init() and pthread_mutex_init() .

A process-shared attribute has been defined for condition variables for the same reason it has been defined for mutexes.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_destroy() , pthread_cond_destroy() , pthread_condattr_getpshared() , pthread_create() , pthread_mutex_destroy() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fminl (3p)

 Continue to this page.


towlower(3p)

TOWLOWER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

towlower - transliterate uppercase wide-character code to lowercase

SYNOPSIS

#include <wctype.h>

wint_t towlower(wint_t wc);

DESCRIPTION

The towlower() function has as a domain a type wint_t, the value of which the application shall ensure is a character representable as a wchar_t, and a wide-character code corresponding to a valid character in the current locale or the value of WEOF. If the argument has any other value, the behavior is undefined. If the argument of towlower() represents an uppercase wide-character code, and there exists a corresponding lowercase wide-character code (as defined by character type information in the program locale category LC_CTYPE ), the result shall be the corresponding lowercase wide-character code. All other arguments in the domain are returned unchanged.

RETURN VALUE

Upon successful completion, towlower() shall return the lowercase letter corresponding to the argument passed; otherwise, it shall return the argument unchanged.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <wctype.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


munlockall (3p)

 Continue to this page.


llround(3p)

LLROUND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

llround, llroundf, llroundl - round to nearest integer value

SYNOPSIS

#include <math.h>

long long llround(double x);
long long llroundf(float x);
long long llroundl(long double x);

DESCRIPTION

These functions shall round their argument to the nearest integer value, rounding halfway cases away from zero, regardless of the current rounding direction.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the rounded integer value.

If x is NaN, a domain error shall occur, and an unspecified value is returned.

If x is +Inf, a domain error shall occur and an unspecified value is returned.

If x is -Inf, a domain error shall occur and an unspecified value is returned.

If the correct value is positive and too large to represent as a long long, a domain error shall occur and an unspecified value is returned.

If the correct value is negative and too large to represent as a long long, a domain error shall occur and an unspecified value is returned.

ERRORS

These functions shall fail if:

Domain Error
The x argument is NaN or ±Inf, or the correct value is not representable as an integer.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [EDOM]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the invalid floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

These functions differ from the llrint() functions in that the default rounding direction for the llround() functions round halfway cases away from zero and need not raise the inexact floating-point exception for non-integer arguments that round to within the range of the return type.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , lround() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setpgid(3p)

SETPGID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setpgid - set process group ID for job control

SYNOPSIS

#include <unistd.h>

int setpgid(pid_t pid, pid_t pgid);

DESCRIPTION

The setpgid() function shall either join an existing process group or create a new process group within the session of the calling process. The process group ID of a session leader shall not change. Upon successful completion, the process group ID of the process with a process ID that matches pid shall be set to pgid. As a special case, if pid is 0, the process ID of the calling process shall be used. Also, if pgid is 0, the process ID of the indicated process shall be used.

RETURN VALUE

Upon successful completion, setpgid() shall return 0; otherwise, -1 shall be returned and errno shall be set to indicate the error.

ERRORS

The setpgid() function shall fail if:

EACCES
The value of the pid argument matches the process ID of a child process of the calling process and the child process has successfully executed one of the exec functions.
EINVAL
The value of the pgid argument is less than 0, or is not a value supported by the implementation.
EPERM
The process indicated by the pid argument is a session leader.
EPERM
The value of the pid argument matches the process ID of a child process of the calling process and the child process is not in the same session as the calling process.
EPERM
The value of the pgid argument is valid but does not match the process ID of the process indicated by the pid argument and there is no process with a process group ID that matches the value of the pgid argument in the same session as the calling process.
ESRCH
The value of the pid argument does not match the process ID of the calling process or of a child process of the calling process.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The setpgid() function shall group processes together for the purpose of signaling, placement in foreground or background, and other job control actions.

The setpgid() function is similar to the setpgrp() function of 4.2 BSD, except that 4.2 BSD allowed the specified new process group to assume any value. This presents certain security problems and is more flexible than necessary to support job control.

To provide tighter security, setpgid() only allows the calling process to join a process group already in use inside its session or create a new process group whose process group ID was equal to its process ID.

When a job control shell spawns a new job, the processes in the job must be placed into a new process group via setpgid(). There are two timing constraints involved in this action:

1.
The new process must be placed in the new process group before the appropriate program is launched via one of the exec functions.

2.
The new process must be placed in the new process group before the shell can correctly send signals to the new process group.

To address these constraints, the following actions are performed. The new processes call setpgid() to alter their own process groups after fork() but before exec. This satisfies the first constraint. Under 4.3 BSD, the second constraint is satisfied by the synchronization property of vfork(); that is, the shell is suspended until the child has completed the exec, thus ensuring that the child has completed the setpgid(). A new version of fork() with this same synchronization property was considered, but it was decided instead to merely allow the parent shell process to adjust the process group of its child processes via setpgid(). Both timing constraints are now satisfied by having both the parent shell and the child attempt to adjust the process group of the child process; it does not matter which succeeds first.

Since it would be confusing to an application to have its process group change after it began executing (that is, after exec), and because the child process would already have adjusted its process group before this, the [EACCES] error was added to disallow this.

One non-obvious use of setpgid() is to allow a job control shell to return itself to its original process group (the one in effect when the job control shell was executed). A job control shell does this before returning control back to its parent when it is terminating or suspending itself as a way of restoring its job control "state" back to what its parent would expect. (Note that the original process group of the job control shell typically matches the process group of its parent, but this is not necessarily always the case.)

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , getpgrp() , setsid() , tcsetpgrp() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


nanosleep(3p)

NANOSLEEP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

nanosleep - high resolution sleep (REALTIME)

SYNOPSIS

#include <time.h>

int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

DESCRIPTION

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

RETURN VALUE

If the nanosleep() function returns because the requested time has elapsed, its return value shall be zero.

If the nanosleep() function returns because it has been interrupted by a signal, it shall return a value of -1 and set errno to indicate the interruption. If the rmtp argument is non-NULL, the timespec structure referenced by it is updated to contain the amount of time remaining in the interval (the requested time minus the time actually slept). If the rmtp argument is NULL, the remaining time is not returned.

If nanosleep() fails, it shall return a value of -1 and set errno to indicate the error.

ERRORS

The nanosleep() function shall fail if:

EINTR
The nanosleep() function was interrupted by a signal.
EINVAL
The rqtp argument specified a nanosecond value less than zero or greater than or equal to 1000 million.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

It is common to suspend execution of a process for an interval in order to poll the status of a non-interrupting function. A large number of actual needs can be met with a simple extension to sleep() that provides finer resolution.

In the POSIX.1-1990 standard and SVR4, it is possible to implement such a routine, but the frequency of wakeup is limited by the resolution of the alarm() and sleep() functions. In 4.3 BSD, it is possible to write such a routine using no static storage and reserving no system facilities. Although it is possible to write a function with similar functionality to sleep() using the remainder of the timer_*() functions, such a function requires the use of signals and the reservation of some signal number. This volume of IEEE Std 1003.1-2001 requires that nanosleep() be non-intrusive of the signals function.

The nanosleep() function shall return a value of 0 on success and -1 on failure or if interrupted. This latter case is different from sleep(). This was done because the remaining time is returned via an argument structure pointer, rmtp, instead of as the return value.

FUTURE DIRECTIONS

None.

SEE ALSO

sleep() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawn_file_actions_destroy (3p)

 Continue to this page.


posix_trace_attr_getcreatetime (3p)

 Continue to this page.


cexp(3p)

CEXP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

cexp, cexpf, cexpl - complex exponential functions

SYNOPSIS

#include <complex.h>

double complex cexp(double complex z);
float complex cexpf(float complex z);
long double complex cexpl(long double complex z);

DESCRIPTION

These functions shall compute the complex exponent of z, defined as e**z.

RETURN VALUE

These functions shall return the complex exponential value of z.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

clog() , the Base Definitions volume of IEEE Std 1003.1-2001, <complex.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


insque(3p)

INSQUE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

insque, remque - insert or remove an element in a queue

SYNOPSIS

#include <search.h>

void insque(void *element, void *pred);
void remque(void *element);

DESCRIPTION

The insque() and remque() functions shall manipulate queues built from doubly-linked lists. The queue can be either circular or linear. An application using insque() or remque() shall ensure it defines a structure in which the first two members of the structure are pointers to the same type of structure, and any further members are application-specific. The first member of the structure is a forward pointer to the next entry in the queue. The second member is a backward pointer to the previous entry in the queue. If the queue is linear, the queue is terminated with null pointers. The names of the structure and of the pointer members are not subject to any special restriction.

The insque() function shall insert the element pointed to by element into a queue immediately after the element pointed to by pred.

The remque() function shall remove the element pointed to by element from a queue.

If the queue is to be used as a linear list, invoking insque(&element, NULL), where element is the initial element of the queue, shall initialize the forward and backward pointers of element to null pointers.

If the queue is to be used as a circular list, the application shall ensure it initializes the forward pointer and the backward pointer of the initial element of the queue to the element's own address.

RETURN VALUE

The insque() and remque() functions do not return a value.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Creating a Linear Linked List

The following example creates a linear linked list.

#include <search.h>
...
struct myque element1;
struct myque element2;

char *data1 = "DATA1";
char *data2 = "DATA2";
...
element1.data = data1;
element2.data = data2;

insque (&element1, NULL);
insque (&element2, &element1);

Creating a Circular Linked List

The following example creates a circular linked list.

#include <search.h>
...
struct myque element1;
struct myque element2;

char *data1 = "DATA1";
char *data2 = "DATA2";
...
element1.data = data1;
element2.data = data2;

element1.fwd = &element1;
element1.bck = &element1;

insque (&element2, &element1);

Removing an Element

The following example removes the element pointed to by element1.

#include <search.h>
...
struct myque element1;
...
remque (&element1);

APPLICATION USAGE

The historical implementations of these functions described the arguments as being of type struct qelem * rather than as being of type void * as defined here. In those implementations, struct qelem was commonly defined in <search.h> as:

struct qelem {
    struct qelem  *q_forw;
    struct qelem  *q_back;
};

Applications using these functions, however, were never able to use this structure directly since it provided no room for the actual data contained in the elements. Most applications defined structures that contained the two pointers as the initial elements and also provided space for, or pointers to, the object's data. Applications that used these functions to update more than one type of table also had the problem of specifying two or more different structures with the same name, if they literally used struct qelem as specified.

As described here, the implementations were actually expecting a structure type where the first two members were forward and backward pointers to structures. With C compilers that didn't provide function prototypes, applications used structures as specified in the DESCRIPTION above and the compiler did what the application expected.

If this method had been carried forward with an ISO C standard compiler and the historical function prototype, most applications would have to be modified to cast pointers to the structures actually used to be pointers to struct qelem to avoid compilation warnings. By specifying void * as the argument type, applications do not need to change (unless they specifically referenced struct qelem and depended on it being defined in <search.h>).

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <search.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


iswalpha(3p)

ISWALPHA

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

iswalpha - test for an alphabetic wide-character code

SYNOPSIS

#include <wctype.h>

int iswalpha(wint_t wc);

DESCRIPTION

The iswalpha() function shall test whether wc is a wide-character code representing a character of class alpha in the program's current locale; see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale.

The wc argument is a wint_t, the value of which the application shall ensure is a wide-character code corresponding to a valid character in the current locale, or equal to the value of the macro WEOF. If the argument has any other value, the behavior is undefined.

RETURN VALUE

The iswalpha() function shall return non-zero if wc is an alphabetic wide-character code; otherwise, it shall return 0.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

To ensure applications portability, especially across natural languages, only this function and those listed in the SEE ALSO section should be used for classification of wide-character codes.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

iswalnum() , iswcntrl() , iswctype() , iswdigit() , iswgraph() , iswlower() , iswprint() , iswpunct() , iswspace() , iswupper() , iswxdigit() , setlocale() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <stdio.h>, <wchar.h>, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


_toupper(3p)

_TOUPPER

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

_toupper - transliterate lowercase characters to uppercase

SYNOPSIS

#include <ctype.h>

int _toupper(int c);

DESCRIPTION

The _toupper() macro shall be equivalent to toupper() except that the application shall ensure that the argument c is a lowercase letter.

RETURN VALUE

Upon successful completion, _toupper() shall return the uppercase letter corresponding to the argument passed.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

islower() , toupper() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <ctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


a64l(3p)

A64L

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

a64l, l64a - convert between a 32-bit integer and a radix-64 ASCII string

SYNOPSIS

#include <stdlib.h>

long a64l(const char *s);
char *l64a(long value);

DESCRIPTION

These functions maintain numbers stored in radix-64 ASCII characters. This is a notation by which 32-bit integers can be represented by up to six characters; each character represents a digit in radix-64 notation. If the type long contains more than 32 bits, only the low-order 32 bits shall be used for these operations.

The characters used to represent digits are '.' (dot) for 0, '/' for 1, '0' through '9' for [2,11], 'A' through 'Z' for [12,37], and 'a' through 'z' for [38,63].

The a64l() function shall take a pointer to a radix-64 representation, in which the first digit is the least significant, and return the corresponding long value. If the string pointed to by s contains more than six characters, a64l() shall use the first six. If the first six characters of the string contain a null terminator, a64l() shall use only characters preceding the null terminator. The a64l() function shall scan the character string from left to right with the least significant digit on the left, decoding each character as a 6-bit radix-64 number. If the type long contains more than 32 bits, the resulting value is sign-extended. The behavior of a64l() is unspecified if s is a null pointer or the string pointed to by s was not generated by a previous call to l64a().

The l64a() function shall take a long argument and return a pointer to the corresponding radix-64 representation. The behavior of l64a() is unspecified if value is negative.

The value returned by l64a() may be a pointer into a static buffer. Subsequent calls to l64a() may overwrite the buffer.

The l64a() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

RETURN VALUE

Upon successful completion, a64l() shall return the long value resulting from conversion of the input string. If a string pointed to by s is an empty string, a64l() shall return 0L.

The l64a() function shall return a pointer to the radix-64 representation. If value is 0L, l64a() shall return a pointer to an empty string.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the type long contains more than 32 bits, the result of a64l(l64a(x)) is x in the low-order 32 bits.

RATIONALE

This is not the same encoding as used by either encoding variant of the uuencode utility.

FUTURE DIRECTIONS

None.

SEE ALSO

strtoul() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, uuencode

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ioctl(3p)

IOCTL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ioctl - control a STREAMS device (STREAMS)

SYNOPSIS

#include <stropts.h>

int ioctl(int fildes, int request, ... /* arg */);

DESCRIPTION

The ioctl() function shall perform a variety of control functions on STREAMS devices. For non-STREAMS devices, the functions performed by this call are unspecified. The request argument and an optional third argument (with varying type) shall be passed to and interpreted by the appropriate part of the STREAM associated with fildes.

The fildes argument is an open file descriptor that refers to a device.

The request argument selects the control function to be performed and shall depend on the STREAMS device being addressed.

The arg argument represents additional information that is needed by this specific STREAMS device to perform the requested function. The type of arg depends upon the particular control request, but it shall be either an integer or a pointer to a device-specific data structure.

The ioctl() commands applicable to STREAMS, their arguments, and error conditions that apply to each individual command are described below.

The following ioctl() commands, with error values indicated, are applicable to all STREAMS files:

I_PUSH
Pushes the module whose name is pointed to by arg onto the top of the current STREAM, just below the STREAM head. It then calls the open() function of the newly-pushed module.

The ioctl() function with the I_PUSH command shall fail if:

EINVAL
Invalid module name.
ENXIO
Open function of new module failed.
ENXIO
Hangup received on fildes.

I_POP
Removes the module just below the STREAM head of the STREAM pointed to by fildes. The arg argument should be 0 in an I_POP request.

The ioctl() function with the I_POP command shall fail if:

EINVAL
No module present in the STREAM.
ENXIO
Hangup received on fildes.

I_LOOK
Retrieves the name of the module just below the STREAM head of the STREAM pointed to by fildes, and places it in a character string pointed to by arg. The buffer pointed to by arg should be at least FMNAMESZ+1 bytes long, where FMNAMESZ is defined in <stropts.h>.

The ioctl() function with the I_LOOK command shall fail if:

EINVAL
No module present in the STREAM.

I_FLUSH
Flushes read and/or write queues, depending on the value of arg. Valid arg values are:
FLUSHR
Flush all read queues.
FLUSHW
Flush all write queues.
FLUSHRW
Flush all read and all write queues.

The ioctl() function with the I_FLUSH command shall fail if:

EINVAL
Invalid arg value.
EAGAIN or ENOSR

Unable to allocate buffers for flush message.

ENXIO
Hangup received on fildes.

I_FLUSHBAND
Flushes a particular band of messages. The arg argument points to a bandinfo structure. The bi_flag member may be one of FLUSHR, FLUSHW, or FLUSHRW as described above. The bi_pri member determines the priority band to be flushed.
I_SETSIG
Requests that the STREAMS implementation send the SIGPOLL signal to the calling process when a particular event has occurred on the STREAM associated with fildes. I_SETSIG supports an asynchronous processing capability in STREAMS. The value of arg is a bitmask that specifies the events for which the process should be signaled. It is the bitwise-inclusive OR of any combination of the following constants:
S_RDNORM
A normal (priority band set to 0) message has arrived at the head of a STREAM head read queue. A signal shall be generated even if the message is of zero length.
S_RDBAND
A message with a non-zero priority band has arrived at the head of a STREAM head read queue. A signal shall be generated even if the message is of zero length.
S_INPUT
A message, other than a high-priority message, has arrived at the head of a STREAM head read queue. A signal shall be generated even if the message is of zero length.
S_HIPRI
A high-priority message is present on a STREAM head read queue. A signal shall be generated even if the message is of zero length.
S_OUTPUT
The write queue for normal data (priority band 0) just below the STREAM head is no longer full. This notifies the process that there is room on the queue for sending (or writing) normal data downstream.
S_WRNORM
Equivalent to S_OUTPUT.
S_WRBAND
The write queue for a non-zero priority band just below the STREAM head is no longer full. This notifies the process that there is room on the queue for sending (or writing) priority data downstream.
S_MSG
A STREAMS signal message that contains the SIGPOLL signal has reached the front of the STREAM head read queue.
S_ERROR
Notification of an error condition has reached the STREAM head.
S_HANGUP
Notification of a hangup has reached the STREAM head.
S_BANDURG
When used in conjunction with S_RDBAND, SIGURG is generated instead of SIGPOLL when a priority message reaches the front of the STREAM head read queue.

If arg is 0, the calling process shall be unregistered and shall not receive further SIGPOLL signals for the stream associated with fildes.

Processes that wish to receive SIGPOLL signals shall ensure that they explicitly register to receive them using I_SETSIG. If several processes register to receive this signal for the same event on the same STREAM, each process shall be signaled when the event occurs.

The ioctl() function with the I_SETSIG command shall fail if:

EINVAL
The value of arg is invalid.
EINVAL
The value of arg is 0 and the calling process is not registered to receive the SIGPOLL signal.
EAGAIN
There were insufficient resources to store the signal request.

I_GETSIG
Returns the events for which the calling process is currently registered to be sent a SIGPOLL signal. The events are returned as a bitmask in an int pointed to by arg, where the events are those specified in the description of I_SETSIG above.

The ioctl() function with the I_GETSIG command shall fail if:

EINVAL
Process is not registered to receive the SIGPOLL signal.

I_FIND
Compares the names of all modules currently present in the STREAM to the name pointed to by arg, and returns 1 if the named module is present in the STREAM, or returns 0 if the named module is not present.

The ioctl() function with the I_FIND command shall fail if:

EINVAL
arg does not contain a valid module name.

I_PEEK
Retrieves the information in the first message on the STREAM head read queue without taking the message off the queue. It is analogous to getmsg() except that this command does not remove the message from the queue. The arg argument points to a strpeek structure.

The application shall ensure that the maxlen member in the ctlbuf and databuf strbuf structures is set to the number of bytes of control information and/or data information, respectively, to retrieve. The flags member may be marked RS_HIPRI or 0, as described by getmsg(). If the process sets flags to RS_HIPRI, for example, I_PEEK shall only look for a high-priority message on the STREAM head read queue.

I_PEEK returns 1 if a message was retrieved, and returns 0 if no message was found on the STREAM head read queue, or if the RS_HIPRI flag was set in flags and a high-priority message was not present on the STREAM head read queue. It does not wait for a message to arrive. On return, ctlbuf specifies information in the control buffer, databuf specifies information in the data buffer, and flags contains the value RS_HIPRI or 0.

I_SRDOPT
Sets the read mode using the value of the argument arg. Read modes are described in read() . Valid arg flags are:
RNORM
Byte-stream mode, the default.
RMSGD
Message-discard mode.
RMSGN
Message-nondiscard mode.

The bitwise-inclusive OR of RMSGD and RMSGN shall return [EINVAL]. The bitwise-inclusive OR of RNORM and either RMSGD or RMSGN shall result in the other flag overriding RNORM which is the default.

In addition, treatment of control messages by the STREAM head may be changed by setting any of the following flags in arg:

RPROTNORM
Fail read() with [EBADMSG] if a message containing a control part is at the front of the STREAM head read queue.
RPROTDAT
Deliver the control part of a message as data when a process issues a read().
RPROTDIS
Discard the control part of a message, delivering any data portion, when a process issues a read().

The ioctl() function with the I_SRDOPT command shall fail if:

EINVAL
The arg argument is not valid.

I_GRDOPT
Returns the current read mode setting, as described above, in an int pointed to by the argument arg. Read modes are described in read() .
I_NREAD
Counts the number of data bytes in the data part of the first message on the STREAM head read queue and places this value in the int pointed to by arg. The return value for the command shall be the number of messages on the STREAM head read queue. For example, if 0 is returned in arg, but the ioctl() return value is greater than 0, this indicates that a zero-length message is next on the queue.
I_FDINSERT
Creates a message from specified buffer(s), adds information about another STREAM, and sends the message downstream. The message contains a control part and an optional data part. The data and control parts to be sent are distinguished by placement in separate buffers, as described below. The arg argument points to a strfdinsert structure.

The application shall ensure that the len member in the ctlbuf strbuf structure is set to the size of a t_uscalar_t plus the number of bytes of control information to be sent with the message. The fildes member specifies the file descriptor of the other STREAM, and the offset member, which must be suitably aligned for use as a t_uscalar_t, specifies the offset from the start of the control buffer where I_FDINSERT shall store a t_uscalar_t whose interpretation is specific to the STREAM end. The application shall ensure that the len member in the databuf strbuf structure is set to the number of bytes of data information to be sent with the message, or to 0 if no data part is to be sent.

The flags member specifies the type of message to be created. A normal message is created if flags is set to 0, and a high-priority message is created if flags is set to RS_HIPRI. For non-priority messages, I_FDINSERT shall block if the STREAM write queue is full due to internal flow control conditions. For priority messages, I_FDINSERT does not block on this condition. For non-priority messages, I_FDINSERT does not block when the write queue is full and O_NONBLOCK is set. Instead, it fails and sets errno to [EAGAIN].

I_FDINSERT also blocks, unless prevented by lack of internal resources, waiting for the availability of message blocks in the STREAM, regardless of priority or whether O_NONBLOCK has been specified. No partial message is sent.

The ioctl() function with the I_FDINSERT command shall fail if:

EAGAIN
A non-priority message is specified, the O_NONBLOCK flag is set, and the STREAM write queue is full due to internal flow control conditions.
EAGAIN or ENOSR

Buffers cannot be allocated for the message that is to be created.

EINVAL
One of the following:
*
The fildes member of the strfdinsert structure is not a valid, open STREAM file descriptor.

*
The size of a t_uscalar_t plus offset is greater than the len member for the buffer specified through ctlbuf.

*
The offset member does not specify a properly-aligned location in the data buffer.

*
An undefined value is stored in flags.

ENXIO
Hangup received on the STREAM identified by either the fildes argument or the fildes member of the strfdinsert structure.
ERANGE
The len member for the buffer specified through databuf does not fall within the range specified by the maximum and minimum packet sizes of the topmost STREAM module; or the len member for the buffer specified through databuf is larger than the maximum configured size of the data part of a message; or the len member for the buffer specified through ctlbuf is larger than the maximum configured size of the control part of a message.

I_STR
Constructs an internal STREAMS ioctl() message from the data pointed to by arg, and sends that message downstream.

This mechanism is provided to send ioctl() requests to downstream modules and drivers. It allows information to be sent with ioctl(), and returns to the process any information sent upstream by the downstream recipient. I_STR shall block until the system responds with either a positive or negative acknowledgement message, or until the request times out after some period of time. If the request times out, it shall fail with errno set to [ETIME].

At most, one I_STR can be active on a STREAM. Further I_STR calls shall block until the active I_STR completes at the STREAM head. The default timeout interval for these requests is 15 seconds. The O_NONBLOCK flag has no effect on this call.

To send requests downstream, the application shall ensure that arg points to a strioctl structure.

The ic_cmd member is the internal ioctl() command intended for a downstream module or driver and ic_timout is the number of seconds (-1=infinite, 0=use implementation-defined timeout interval, >0=as specified) an I_STR request shall wait for acknowledgement before timing out. ic_len is the number of bytes in the data argument, and ic_dp is a pointer to the data argument. The ic_len member has two uses: on input, it contains the length of the data argument passed in, and on return from the command, it contains the number of bytes being returned to the process (the buffer pointed to by ic_dp should be large enough to contain the maximum amount of data that any module or the driver in the STREAM can return).

The STREAM head shall convert the information pointed to by the strioctl structure to an internal ioctl() command message and send it downstream.

The ioctl() function with the I_STR command shall fail if:

EAGAIN or ENOSR

Unable to allocate buffers for the ioctl() message.

EINVAL
The ic_len member is less than 0 or larger than the maximum configured size of the data part of a message, or ic_timout is less than -1.
ENXIO
Hangup received on fildes.
ETIME
A downstream ioctl() timed out before acknowledgement was received.

An I_STR can also fail while waiting for an acknowledgement if a message indicating an error or a hangup is received at the STREAM head. In addition, an error code can be returned in the positive or negative acknowledgement message, in the event the ioctl() command sent downstream fails. For these cases, I_STR shall fail with errno set to the value in the message.

I_SWROPT
Sets the write mode using the value of the argument arg. Valid bit settings for arg are:
SNDZERO
Send a zero-length message downstream when a write() of 0 bytes occurs. To not send a zero-length message when a write() of 0 bytes occurs, the application shall ensure that this bit is not set in arg (for example, arg would be set to 0).

The ioctl() function with the I_SWROPT command shall fail if:

EINVAL
arg is not the above value.

I_GWROPT
Returns the current write mode setting, as described above, in the int that is pointed to by the argument arg.
I_SENDFD
Creates a new reference to the open file description associated with the file descriptor arg, and writes a message on the STREAMS-based pipe fildes containing this reference, together with the user ID and group ID of the calling process.

The ioctl() function with the I_SENDFD command shall fail if:

EAGAIN
The sending STREAM is unable to allocate a message block to contain the file pointer; or the read queue of the receiving STREAM head is full and cannot accept the message sent by I_SENDFD.
EBADF
The arg argument is not a valid, open file descriptor.
EINVAL
The fildes argument is not connected to a STREAM pipe.
ENXIO
Hangup received on fildes.

I_RECVFD
Retrieves the reference to an open file description from a message written to a STREAMS-based pipe using the I_SENDFD command, and allocates a new file descriptor in the calling process that refers to this open file description. The arg argument is a pointer to a strrecvfd data structure as defined in <stropts.h>.

The fd member is a file descriptor. The uid and gid members are the effective user ID and effective group ID, respectively, of the sending process.

If O_NONBLOCK is not set, I_RECVFD shall block until a message is present at the STREAM head. If O_NONBLOCK is set, I_RECVFD shall fail with errno set to [EAGAIN] if no message is present at the STREAM head.

If the message at the STREAM head is a message sent by an I_SENDFD, a new file descriptor shall be allocated for the open file descriptor referenced in the message. The new file descriptor is placed in the fd member of the strrecvfd structure pointed to by arg.

The ioctl() function with the I_RECVFD command shall fail if:

EAGAIN
A message is not present at the STREAM head read queue and the O_NONBLOCK flag is set.
EBADMSG
The message at the STREAM head read queue is not a message containing a passed file descriptor.
EMFILE
The process has the maximum number of file descriptors currently open that it is allowed.
ENXIO
Hangup received on fildes.

I_LIST
Allows the process to list all the module names on the STREAM, up to and including the topmost driver name. If arg is a null pointer, the return value shall be the number of modules, including the driver, that are on the STREAM pointed to by fildes. This lets the process allocate enough space for the module names. Otherwise, it should point to a str_list structure.

The sl_nmods member indicates the number of entries the process has allocated in the array. Upon return, the sl_modlist member of the str_list structure shall contain the list of module names, and the number of entries that have been filled into the sl_modlist array is found in the sl_nmods member (the number includes the number of modules including the driver). The return value from ioctl() shall be 0. The entries are filled in starting at the top of the STREAM and continuing downstream until either the end of the STREAM is reached, or the number of requested modules ( sl_nmods) is satisfied.

The ioctl() function with the I_LIST command shall fail if:

EINVAL
The sl_nmods member is less than 1.
EAGAIN or ENOSR

Unable to allocate buffers.

I_ATMARK
Allows the process to see if the message at the head of the STREAM head read queue is marked by some module downstream. The arg argument determines how the checking is done when there may be multiple marked messages on the STREAM head read queue. It may take on the following values:
ANYMARK
Check if the message is marked.
LASTMARK
Check if the message is the last one marked on the queue.

The bitwise-inclusive OR of the flags ANYMARK and LASTMARK is permitted.

The return value shall be 1 if the mark condition is satisfied; otherwise, the value shall be 0.

The ioctl() function with the I_ATMARK command shall fail if:

EINVAL
Invalid arg value.

I_CKBAND
Checks if the message of a given priority band exists on the STREAM head read queue. This shall return 1 if a message of the given priority exists, 0 if no such message exists, or -1 on error. arg should be of type int.

The ioctl() function with the I_CKBAND command shall fail if:

EINVAL
Invalid arg value.

I_GETBAND
Returns the priority band of the first message on the STREAM head read queue in the integer referenced by arg.

The ioctl() function with the I_GETBAND command shall fail if:

ENODATA
No message on the STREAM head read queue.

I_CANPUT
Checks if a certain band is writable. arg is set to the priority band in question. The return value shall be 0 if the band is flow-controlled, 1 if the band is writable, or -1 on error.

The ioctl() function with the I_CANPUT command shall fail if:

EINVAL
Invalid arg value.

I_SETCLTIME
This request allows the process to set the time the STREAM head shall delay when a STREAM is closing and there is data on the write queues. Before closing each module or driver, if there is data on its write queue, the STREAM head shall delay for the specified amount of time to allow the data to drain. If, after the delay, data is still present, it shall be flushed. The arg argument is a pointer to an integer specifying the number of milliseconds to delay, rounded up to the nearest valid value. If I_SETCLTIME is not performed on a STREAM, an implementation-defined default timeout interval is used.

The ioctl() function with the I_SETCLTIME command shall fail if:

EINVAL
Invalid arg value.

I_GETCLTIME
Returns the close time delay in the integer pointed to by arg.

Multiplexed STREAMS Configurations

The following commands are used for connecting and disconnecting multiplexed STREAMS configurations. These commands use an implementation-defined default timeout interval.

I_LINK
Connects two STREAMs, where fildes is the file descriptor of the STREAM connected to the multiplexing driver, and arg is the file descriptor of the STREAM connected to another driver. The STREAM designated by arg is connected below the multiplexing driver. I_LINK requires the multiplexing driver to send an acknowledgement message to the STREAM head regarding the connection. This call shall return a multiplexer ID number (an identifier used to disconnect the multiplexer; see I_UNLINK) on success, and -1 on failure.

The ioctl() function with the I_LINK command shall fail if:

ENXIO
Hangup received on fildes.
ETIME
Timeout before acknowledgement message was received at STREAM head.
EAGAIN or ENOSR

Unable to allocate STREAMS storage to perform the I_LINK.

EBADF
The arg argument is not a valid, open file descriptor.
EINVAL
The fildes argument does not support multiplexing; or arg is not a STREAM or is already connected downstream from a multiplexer; or the specified I_LINK operation would connect the STREAM head in more than one place in the multiplexed STREAM.

An I_LINK can also fail while waiting for the multiplexing driver to acknowledge the request, if a message indicating an error or a hangup is received at the STREAM head of fildes. In addition, an error code can be returned in the positive or negative acknowledgement message. For these cases, I_LINK fails with errno set to the value in the message.

I_UNLINK
Disconnects the two STREAMs specified by fildes and arg. fildes is the file descriptor of the STREAM connected to the multiplexing driver. The arg argument is the multiplexer ID number that was returned by the I_LINK ioctl() command when a STREAM was connected downstream from the multiplexing driver. If arg is MUXID_ALL, then all STREAMs that were connected to fildes shall be disconnected. As in I_LINK, this command requires acknowledgement.

The ioctl() function with the I_UNLINK command shall fail if:

ENXIO
Hangup received on fildes.
ETIME
Timeout before acknowledgement message was received at STREAM head.
EAGAIN or ENOSR

Unable to allocate buffers for the acknowledgement message.

EINVAL
Invalid multiplexer ID number.

An I_UNLINK can also fail while waiting for the multiplexing driver to acknowledge the request if a message indicating an error or a hangup is received at the STREAM head of fildes. In addition, an error code can be returned in the positive or negative acknowledgement message. For these cases, I_UNLINK shall fail with errno set to the value in the message.

I_PLINK
Creates a persistent connection between two STREAMs, where fildes is the file descriptor of the STREAM connected to the multiplexing driver, and arg is the file descriptor of the STREAM connected to another driver. This call shall create a persistent connection which can exist even if the file descriptor fildes associated with the upper STREAM to the multiplexing driver is closed. The STREAM designated by arg gets connected via a persistent connection below the multiplexing driver. I_PLINK requires the multiplexing driver to send an acknowledgement message to the STREAM head. This call shall return a multiplexer ID number (an identifier that may be used to disconnect the multiplexer; see I_PUNLINK) on success, and -1 on failure.

The ioctl() function with the I_PLINK command shall fail if:

ENXIO
Hangup received on fildes.
ETIME
Timeout before acknowledgement message was received at STREAM head.
EAGAIN or ENOSR

Unable to allocate STREAMS storage to perform the I_PLINK.

EBADF
The arg argument is not a valid, open file descriptor.
EINVAL
The fildes argument does not support multiplexing; or arg is not a STREAM or is already connected downstream from a multiplexer; or the specified I_PLINK operation would connect the STREAM head in more than one place in the multiplexed STREAM.

An I_PLINK can also fail while waiting for the multiplexing driver to acknowledge the request, if a message indicating an error or a hangup is received at the STREAM head of fildes. In addition, an error code can be returned in the positive or negative acknowledgement message. For these cases, I_PLINK shall fail with errno set to the value in the message.

I_PUNLINK
Disconnects the two STREAMs specified by fildes and arg from a persistent connection. The fildes argument is the file descriptor of the STREAM connected to the multiplexing driver. The arg argument is the multiplexer ID number that was returned by the I_PLINK ioctl() command when a STREAM was connected downstream from the multiplexing driver. If arg is MUXID_ALL, then all STREAMs which are persistent connections to fildes shall be disconnected. As in I_PLINK, this command requires the multiplexing driver to acknowledge the request.

The ioctl() function with the I_PUNLINK command shall fail if:

ENXIO
Hangup received on fildes.
ETIME
Timeout before acknowledgement message was received at STREAM head.
EAGAIN or ENOSR

Unable to allocate buffers for the acknowledgement message.

EINVAL
Invalid multiplexer ID number.

An I_PUNLINK can also fail while waiting for the multiplexing driver to acknowledge the request if a message indicating an error or a hangup is received at the STREAM head of fildes. In addition, an error code can be returned in the positive or negative acknowledgement message. For these cases, I_PUNLINK shall fail with errno set to the value in the message.

RETURN VALUE

Upon successful completion, ioctl() shall return a value other than -1 that depends upon the STREAMS device control function. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

Under the following general conditions, ioctl() shall fail if:

EBADF
The fildes argument is not a valid open file descriptor.
EINTR
A signal was caught during the ioctl() operation.
EINVAL
The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer.

If an underlying device driver detects an error, then ioctl() shall fail if:

EINVAL
The request or arg argument is not valid for this device.
EIO
Some physical I/O error has occurred.
ENOTTY
The fildes argument is not associated with a STREAMS device that accepts control functions.
ENXIO
The request and arg arguments are valid for this device driver, but the service requested cannot be performed on this particular sub-device.
ENODEV
The fildes argument refers to a valid STREAMS device, but the corresponding device driver does not support the ioctl() function.

If a STREAM is connected downstream from a multiplexer, any ioctl() command except I_UNLINK and I_PUNLINK shall set errno to [EINVAL].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The implementation-defined timeout interval for STREAMS has historically been 15 seconds.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

STREAMS , close() , fcntl() , getmsg() , open() , pipe() , poll() , putmsg() , read() , sigaction() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <stropts.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ungetc(3p)

UNGETC

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ungetc - push byte back into input stream

SYNOPSIS

#include <stdio.h>

int ungetc(int c, FILE *stream);

DESCRIPTION

The ungetc() function shall push the byte specified by c (converted to an unsigned char) back onto the input stream pointed to by stream. The pushed-back bytes shall be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to by stream) to a file-positioning function ( fseek(), fsetpos(), or rewind()) shall discard any pushed-back bytes for the stream. The external storage corresponding to the stream shall be unchanged.

One byte of push-back shall be provided. If ungetc() is called too many times on the same stream without an intervening read or file-positioning operation on that stream, the operation may fail.

If the value of c equals that of the macro EOF, the operation shall fail and the input stream shall be left unchanged.

A successful call to ungetc() shall clear the end-of-file indicator for the stream. The value of the file-position indicator for the stream after reading or discarding all pushed-back bytes shall be the same as it was before the bytes were pushed back. The file-position indicator is decremented by each successful call to ungetc(); if its value was 0 before a call, its value is unspecified after the call.

RETURN VALUE

Upon successful completion, ungetc() shall return the byte pushed back after conversion. Otherwise, it shall return EOF.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fseek() , getc() , fsetpos() , read() , rewind() , setbuf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fstat(3p)

FSTAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fstat - get file status

SYNOPSIS

#include <sys/stat.h>

int fstat(int fildes, struct stat *buf);

DESCRIPTION

The fstat() function shall obtain information about an open file associated with the file descriptor fildes, and shall write it to the area pointed to by buf.

If fildes references a shared memory object, the implementation shall update in the stat structure pointed to by the buf argument only the st_uid, st_gid, st_size, and st_mode fields, and only the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits need be valid. The implementation may update other fields and flags.

If fildes references a typed memory object, the implementation shall update in the stat structure pointed to by the buf argument only the st_uid, st_gid, st_size, and st_mode fields, and only the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits need be valid. The implementation may update other fields and flags.

The buf argument is a pointer to a stat structure, as defined in <sys/stat.h>, into which information is placed concerning the file.

The structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime shall have meaningful values for all other file types defined in this volume of IEEE Std 1003.1-2001. The value of the member st_nlink shall be set to the number of links to the file.

An implementation that provides additional or alternative file access control mechanisms may, under implementation-defined conditions, cause fstat() to fail.

The fstat() function shall update any time-related fields as described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.7, File Times Update, before writing into the stat structure.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The fstat() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.
EIO
An I/O error occurred while reading from the file system.
EOVERFLOW
The file size in bytes or the number of blocks allocated to the file or the file serial number cannot be represented correctly in the structure pointed to by buf.

The fstat() function may fail if:

EOVERFLOW
One of the values is too large to store into the structure pointed to by the buf argument.

The following sections are informative.

EXAMPLES

Obtaining File Status Information

The following example shows how to obtain file status information for a file named /home/cnd/mod1. The structure variable buffer is defined for the stat structure. The /home/cnd/mod1 file is opened with read/write privileges and is passed to the open file descriptor fildes.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

struct stat buffer;
int         status;
...
fildes = open("/home/cnd/mod1", O_RDWR);
status = fstat(fildes, &buffer);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

lstat() , stat() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>, <sys/types.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_key_delete(3p)

PTHREAD_KEY_DELETE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_key_delete - thread-specific data key deletion

SYNOPSIS

#include <pthread.h>

int pthread_key_delete(pthread_key_t key);

DESCRIPTION

The pthread_key_delete() function shall delete a thread-specific data key previously returned by pthread_key_create(). The thread-specific data values associated with key need not be NULL at the time pthread_key_delete() is called. It is the responsibility of the application to free any application storage or perform any cleanup actions for data structures related to the deleted key or associated thread-specific data in any threads; this cleanup can be done either before or after pthread_key_delete() is called. Any attempt to use key following the call to pthread_key_delete() results in undefined behavior.

The pthread_key_delete() function shall be callable from within destructor functions. No destructor functions shall be invoked by pthread_key_delete(). Any destructor function that may have been associated with key shall no longer be called upon thread exit.

RETURN VALUE

If successful, the pthread_key_delete() function shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_key_delete() function may fail if:

EINVAL
The key value is invalid.

The pthread_key_delete() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

A thread-specific data key deletion function has been included in order to allow the resources associated with an unused thread-specific data key to be freed. Unused thread-specific data keys can arise, among other scenarios, when a dynamically loaded module that allocated a key is unloaded.

Conforming applications are responsible for performing any cleanup actions needed for data structures associated with the key to be deleted, including data referenced by thread-specific data values. No such cleanup is done by pthread_key_delete(). In particular, destructor functions are not called. There are several reasons for this division of responsibility:

1.
The associated destructor functions used to free thread-specific data at thread exit time are only guaranteed to work correctly when called in the thread that allocated the thread-specific data. (Destructors themselves may utilize thread-specific data.) Thus, they cannot be used to free thread-specific data in other threads at key deletion time. Attempting to have them called by other threads at key deletion time would require other threads to be asynchronously interrupted. But since interrupted threads could be in an arbitrary state, including holding locks necessary for the destructor to run, this approach would fail. In general, there is no safe mechanism whereby an implementation could free thread-specific data at key deletion time.

2.
Even if there were a means of safely freeing thread-specific data associated with keys to be deleted, doing so would require that implementations be able to enumerate the threads with non-NULL data and potentially keep them from creating more thread-specific data while the key deletion is occurring. This special case could cause extra synchronization in the normal case, which would otherwise be unnecessary.

For an application to know that it is safe to delete a key, it has to know that all the threads that might potentially ever use the key do not attempt to use it again. For example, it could know this if all the client threads have called a cleanup procedure declaring that they are through with the module that is being shut down, perhaps by setting a reference count to zero.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_key_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


setpgrp(3p)

SETPGRP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

setpgrp - set the process group ID

SYNOPSIS

#include <unistd.h>

pid_t setpgrp(void);

DESCRIPTION

If the calling process is not already a session leader, setpgrp() sets the process group ID of the calling process to the process ID of the calling process. If setpgrp() creates a new session, then the new session has no controlling terminal.

The setpgrp() function has no effect when the calling process is a session leader.

RETURN VALUE

Upon completion, setpgrp() shall return the process group ID.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fork() , getpid() , getsid() , kill() , setpgid() , setsid() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_setcancelstate (3p)

 Continue to this page.


posix_trace_set_filter (3p)

 Continue to this page.


sem_wait(3p)

SEM_TRYWAIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_trywait, sem_wait - lock a semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

int sem_trywait(sem_t *sem);
int sem_wait(sem_t *sem);

DESCRIPTION

The sem_trywait() function shall lock the semaphore referenced by sem only if the semaphore is currently not locked; that is, if the semaphore value is currently positive. Otherwise, it shall not lock the semaphore.

The sem_wait() function shall lock the semaphore referenced by sem by performing a semaphore lock operation on that semaphore. If the semaphore value is currently zero, then the calling thread shall not return from the call to sem_wait() until it either locks the semaphore or the call is interrupted by a signal.

Upon successful return, the state of the semaphore shall be locked and shall remain locked until the sem_post() function is executed and returns successfully.

The sem_wait() function is interruptible by the delivery of a signal.

RETURN VALUE

The sem_trywait() and sem_wait() functions shall return zero if the calling process successfully performed the semaphore lock operation on the semaphore designated by sem. If the call was unsuccessful, the state of the semaphore shall be unchanged, and the function shall return a value of -1 and set errno to indicate the error.

ERRORS

The sem_trywait() and sem_wait() functions shall fail if:

EAGAIN
The semaphore was already locked, so it cannot be immediately locked by the sem_trywait() operation ( sem_trywait() only).
EINVAL
The sem argument does not refer to a valid semaphore.

The sem_trywait() and sem_wait() functions may fail if:

EDEADLK
A deadlock condition was detected.
EINTR
A signal interrupted this function.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions may be subject to priority inversion, as discussed in the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.285, Priority Inversion.

The sem_trywait() and sem_wait() functions are part of the Semaphores option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

semctl() , semget() , semop() , sem_post() , sem_timedwait() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


poll(3p)

POLL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

poll - input/output multiplexing

SYNOPSIS

#include <poll.h>

int poll(struct pollfd fds[], nfds_t nfds, int timeout);

DESCRIPTION

The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors. For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events. The number of pollfd structures in the fds array is specified by nfds. The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.

The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor. It is a pointer to an array with one member for each open file descriptor of interest. The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by OR'ing a combination of the following event flags:

POLLIN
Data other than high-priority data may be read without blocking.

For STREAMS, this flag is set in revents even if the message is of zero length. This flag shall be equivalent to POLLRDNORM | POLLRDBAND.

POLLRDNORM
Normal data may be read without blocking.

For STREAMS, data on priority band 0 may be read without blocking. This flag is set in revents even if the message is of zero length.

POLLRDBAND
Priority data may be read without blocking.

For STREAMS, data on priority bands greater than 0 may be read without blocking. This flag is set in revents even if the message is of zero length.

POLLPRI
High-priority data may be read without blocking.

For STREAMS, this flag is set in revents even if the message is of zero length.

POLLOUT
Normal data may be written without blocking.

For STREAMS, data on priority band 0 may be written without blocking.

POLLWRNORM
Equivalent to POLLOUT.
POLLWRBAND
Priority data may be written.

For STREAMS, data on priority bands greater than 0 may be written without blocking. If any priority band has been written to on this STREAM, this event only examines bands that have been written to at least once.

POLLERR
An error has occurred on the device or stream. This flag is only valid in the revents bitmask; it shall be ignored in the events member.
POLLHUP
The device has been disconnected. This event and POLLOUT are mutually-exclusive; a stream can never be writable if a hangup has occurred. However, this event and POLLIN, POLLRDNORM, POLLRDBAND, or POLLPRI are not mutually-exclusive. This flag is only valid in the revents bitmask; it shall be ignored in the events member.
POLLNVAL
The specified fd value is invalid. This flag is only valid in the revents member; it shall ignored in the events member.

The significance and semantics of normal, priority, and high-priority data are file and device-specific.

If the value of fd is less than 0, events shall be ignored, and revents shall be set to 0 in that entry on return from poll().

In each pollfd structure, poll() shall clear the revents member, except that where the application requested a report on a condition by setting one of the bits of events listed above, poll() shall set the corresponding bit in revents if the requested condition is true. In addition, poll() shall set the POLLHUP, POLLERR, and POLLNVAL flag in revents if the condition is true, even if the application did not set the corresponding bit in events.

If none of the defined events have occurred on any selected file descriptor, poll() shall wait at least timeout milliseconds for an event to occur on any of the selected file descriptors. If the value of timeout is 0, poll() shall return immediately. If the value of timeout is -1, poll() shall block until a requested event occurs or until the call is interrupted.

Implementations may place limitations on the granularity of timeout intervals. If the requested timeout interval requires a finer granularity than the implementation supports, the actual timeout interval shall be rounded up to the next supported value.

The poll() function shall not be affected by the O_NONBLOCK flag.

The poll() function shall support regular files, terminal and pseudo-terminal devices, FIFOs, pipes, sockets and STREAMS-based files. The behavior of poll() on elements of fds that refer to other types of file is unspecified.

Regular files shall always poll TRUE for reading and writing.

A file descriptor for a socket that is listening for connections shall indicate that it is ready for reading, once connections are available. A file descriptor for a socket that is connecting asynchronously shall indicate that it is ready for writing, once a connection has been established.

RETURN VALUE

Upon successful completion, poll() shall return a non-negative value. A positive value indicates the total number of file descriptors that have been selected (that is, file descriptors for which the revents member is non-zero). A value of 0 indicates that the call timed out and no file descriptors have been selected. Upon failure, poll() shall return -1 and set errno to indicate the error.

ERRORS

The poll() function shall fail if:

EAGAIN
The allocation of internal data structures failed but a subsequent request may succeed.
EINTR
A signal was caught during poll().
EINVAL
The nfds argument is greater than {OPEN_MAX}, or one of the fd members refers to a STREAM or multiplexer that is linked (directly or indirectly) downstream from a multiplexer.

The following sections are informative.

EXAMPLES

Checking for Events on a Stream

The following example opens a pair of STREAMS devices and then waits for either one to become writable. This example proceeds as follows:

1.
Sets the timeout parameter to 500 milliseconds.

2.
Opens the STREAMS devices /dev/dev0 and /dev/dev1, and then polls them, specifying POLLOUT and POLLWRBAND as the events of interest.

The STREAMS device names /dev/dev0 and /dev/dev1 are only examples of how STREAMS devices can be named; STREAMS naming conventions may vary among systems conforming to the IEEE Std 1003.1-2001.

3.
Uses the ret variable to determine whether an event has occurred on either of the two STREAMS. The poll() function is given 500 milliseconds to wait for an event to occur (if it has not occurred prior to the poll() call).

4.
Checks the returned value of ret. If a positive value is returned, one of the following can be done:
a.
Priority data can be written to the open STREAM on priority bands greater than 0, because the POLLWRBAND event occurred on the open STREAM ( fds[0] or fds[1]).

b.
Data can be written to the open STREAM on priority-band 0, because the POLLOUT event occurred on the open STREAM ( fds[0] or fds[1]).

5.
If the returned value is not a positive value, permission to write data to the open STREAM (on any priority band) is denied.

6.
If the POLLHUP event occurs on the open STREAM ( fds[0] or fds[1]), the device on the open STREAM has disconnected.

#include <stropts.h>
#include <poll.h>
...
struct pollfd fds[2];
int timeout_msecs = 500;
int ret;
    int i;

/* Open STREAMS device. */
fds[0].fd = open("/dev/dev0", ...);
fds[1].fd = open("/dev/dev1", ...);
    fds[0].events = POLLOUT | POLLWRBAND;
    fds[1].events = POLLOUT | POLLWRBAND;

ret = poll(fds, 2, timeout_msecs);

if (ret > 0) {
    /* An event on one of the fds has occurred. */
    for (i=0; i<2; i++) {
        if (fds[i].revents & POLLWRBAND) {
        /* Priority data may be written on device number i. */
...
        }
        if (fds[i].revents & POLLOUT) {
        /* Data may be written on device number i. */
...
        }
        if (fds[i].revents & POLLHUP) {
        /* A hangup has occurred on device number i. */
...
        }
    }
}

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

STREAMS , getmsg() , putmsg() , read() , select() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <poll.h>, <stropts.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mbsrtowcs(3p)

MBSRTOWCS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mbsrtowcs - convert a character string to a wide-character string (restartable)

SYNOPSIS

#include <wchar.h>

size_t mbsrtowcs(wchar_t *restrict dst, const char **restrict src,
size_t len, mbstate_t *restrict ps);

DESCRIPTION

The mbsrtowcs() function shall convert a sequence of characters, beginning in the conversion state described by the object pointed to by ps, from the array indirectly pointed to by src into a sequence of corresponding wide characters. If dst is not a null pointer, the converted characters shall be stored into the array pointed to by dst. Conversion continues up to and including a terminating null character, which shall also be stored. Conversion shall stop early in either of the following cases:

*
A sequence of bytes is encountered that does not form a valid character.

*
len codes have been stored into the array pointed to by dst (and dst is not a null pointer).

Each conversion shall take place as if by a call to the mbrtowc() function.

If dst is not a null pointer, the pointer object pointed to by src shall be assigned either a null pointer (if conversion stopped due to reaching a terminating null character) or the address just past the last character converted (if any). If conversion stopped due to reaching a terminating null character, and if dst is not a null pointer, the resulting state described shall be the initial conversion state.

If ps is a null pointer, the mbsrtowcs() function shall use its own internal mbstate_t object, which is initialized at program start-up to the initial conversion state. Otherwise, the mbstate_t object pointed to by ps shall be used to completely describe the current conversion state of the associated character sequence. The implementation behaves as if no function defined in this volume of IEEE Std 1003.1-2001 calls mbsrtowcs().

The behavior of this function shall be affected by the LC_CTYPE category of the current locale.

RETURN VALUE

If the input conversion encounters a sequence of bytes that do not form a valid character, an encoding error occurs. In this case, the mbsrtowcs() function stores the value of the macro [EILSEQ] in errno and shall return (size_t)-1; the conversion state is undefined. Otherwise, it shall return the number of characters successfully converted, not including the terminating null (if any).

ERRORS

The mbsrtowcs() function may fail if:

EINVAL
ps points to an object that contains an invalid conversion state.
EILSEQ
Invalid character sequence is detected.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mbsinit() , mbrtowc() , the Base Definitions volume of IEEE Std 1003.1-2001, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


mq_send(3p)

MQ_SEND

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

mq_send, mq_timedsend - send a message to a message queue (REALTIME)

SYNOPSIS

#include <mqueue.h>

int mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len,
unsigned msg_prio);

#include <mqueue.h>
#include <time.h>
int mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len,
unsigned msg_prio, const struct timespec *abs_timeout);

DESCRIPTION

The mq_send() function shall add the message pointed to by the argument msg_ptr to the message queue specified by mqdes. The msg_len argument specifies the length of the message, in bytes, pointed to by msg_ptr. The value of msg_len shall be less than or equal to the mq_msgsize attribute of the message queue, or mq_send() shall fail.

If the specified message queue is not full, mq_send() shall behave as if the message is inserted into the message queue at the position indicated by the msg_prio argument. A message with a larger numeric value of msg_prio shall be inserted before messages with lower values of msg_prio. A message shall be inserted after other messages in the queue, if any, with equal msg_prio. The value of msg_prio shall be less than {MQ_PRIO_MAX}.

If the specified message queue is full and O_NONBLOCK is not set in the message queue description associated with mqdes, mq_send() shall block until space becomes available to enqueue the message, or until mq_send() is interrupted by a signal. If more than one thread is waiting to send when space becomes available in the message queue and the Priority Scheduling option is supported, then the thread of the highest priority that has been waiting the longest shall be unblocked to send its message. Otherwise, it is unspecified which waiting thread is unblocked. If the specified message queue is full and O_NONBLOCK is set in the message queue description associated with mqdes, the message shall not be queued and mq_send() shall return an error.

The mq_timedsend() function shall add a message to the message queue specified by mqdes in the manner defined for the mq_send() function. However, if the specified message queue is full and O_NONBLOCK is not set in the message queue description associated with mqdes, the wait for sufficient room in the queue shall be terminated when the specified timeout expires. If O_NONBLOCK is set in the message queue description, this function shall be equivalent to mq_send().

The timeout shall expire when the absolute time specified by abs_timeout passes, as measured by the clock on which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout), or if the absolute time specified by abs_timeout has already been passed at the time of the call.

If the Timers option is supported, the timeout shall be based on the CLOCK_REALTIME clock; if the Timers option is not supported, the timeout shall be based on the system clock as returned by the time() function.

The resolution of the timeout shall be the resolution of the clock on which it is based. The timespec argument is defined in the <time.h> header.

Under no circumstance shall the operation fail with a timeout if there is sufficient room in the queue to add the message immediately. The validity of the abs_timeout parameter need not be checked when there is sufficient room in the queue.

RETURN VALUE

Upon successful completion, the mq_send() and mq_timedsend() functions shall return a value of zero. Otherwise, no message shall be enqueued, the functions shall return -1, and errno shall be set to indicate the error.

ERRORS

The mq_send() and mq_timedsend() functions shall fail if:

EAGAIN
The O_NONBLOCK flag is set in the message queue description associated with mqdes, and the specified message queue is full.
EBADF
The mqdes argument is not a valid message queue descriptor open for writing.
EINTR
A signal interrupted the call to mq_send() or mq_timedsend().
EINVAL
The value of msg_prio was outside the valid range.
EINVAL
The process or thread would have blocked, and the abs_timeout parameter specified a nanoseconds field value less than zero or greater than or equal to 1000 million.
EMSGSIZE
The specified message length, msg_len, exceeds the message size attribute of the message queue.
ETIMEDOUT
The O_NONBLOCK flag was not set when the message queue was opened, but the timeout expired before the message could be added to the queue.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The value of the symbol {MQ_PRIO_MAX} limits the number of priority levels supported by the application. Message priorities range from 0 to {MQ_PRIO_MAX}-1.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

mq_open() , mq_receive() , mq_setattr() , mq_timedreceive() , time() , the Base Definitions volume of IEEE Std 1003.1-2001, <mqueue.h>, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sem_close(3p)

SEM_CLOSE

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_close - close a named semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

int sem_close(sem_t *sem);

DESCRIPTION

The sem_close() function shall indicate that the calling process is finished using the named semaphore indicated by sem. The effects of calling sem_close() for an unnamed semaphore (one created by sem_init()) are undefined. The sem_close() function shall deallocate (that is, make available for reuse by a subsequent sem_open() by this process) any system resources allocated by the system for use by this process for this semaphore. The effect of subsequent use of the semaphore indicated by sem by this process is undefined. If the semaphore has not been removed with a successful call to sem_unlink(), then sem_close() has no effect on the state of the semaphore. If the sem_unlink() function has been successfully invoked for name after the most recent call to sem_open() with O_CREAT for this semaphore, then when all processes that have opened the semaphore close it, the semaphore is no longer accessible.

RETURN VALUE

Upon successful completion, a value of zero shall be returned. Otherwise, a value of -1 shall be returned and errno set to indicate the error.

ERRORS

The sem_close() function shall fail if:

EINVAL
The sem argument is not a valid semaphore descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sem_close() function is part of the Semaphores option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

semctl() , semget() , semop() , sem_init() , sem_open() , sem_unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


tdelete (3p)

 Continue to this page.


vscanf(3p)

VFSCANF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

vfscanf, vscanf, vsscanf - format input of a stdarg argument list

SYNOPSIS

#include <stdarg.h>
#include <stdio.h>

int vfscanf(FILE *restrict stream, const char *restrict format,
va_list arg);
int vscanf(const char *restrict format, va_list arg);
int vsscanf(const char *restrict s, const char *restrict format,
va_list arg);

DESCRIPTION

The vscanf(), vfscanf(), and vsscanf() functions shall be equivalent to the scanf(), fscanf(), and sscanf() functions, respectively, except that instead of being called with a variable number of arguments, they are called with an argument list as defined in the <stdarg.h> header. These functions shall not invoke the va_end macro. As these functions invoke the va_arg macro, the value of ap after the return is unspecified.

RETURN VALUE

Refer to fscanf() .

ERRORS

Refer to fscanf() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications using these functions should call va_end( ap) afterwards to clean up.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fscanf() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdarg.h>, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ftime(3p)

FTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

ftime - get date and time (LEGACY)

SYNOPSIS

#include <sys/timeb.h>

int ftime(struct timeb *tp);

DESCRIPTION

The ftime() function shall set the time and millitm members of the timeb structure pointed to by tp to contain the seconds and milliseconds portions, respectively, of the current time in seconds since the Epoch. The contents of the timezone and dstflag members of tp after a call to ftime() are unspecified.

The system clock need not have millisecond granularity. Depending on any granularity (particularly a granularity of one) renders code non-portable.

RETURN VALUE

Upon successful completion, the ftime() function shall return 0; otherwise, -1 shall be returned.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

Getting the Current Time and Date

The following example shows how to get the current system time values using the ftime() function. The timeb structure pointed to by tp is filled with the current system time values for time and millitm.

#include <sys/timeb.h>

struct timeb tp;
int          status;
...
status = ftime(&tp);

APPLICATION USAGE

For applications portability, the time() function should be used to determine the current time instead of ftime(). Realtime applications should use clock_gettime() to determine the current time instead of ftime().

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

clock_getres() , ctime() , gettimeofday() , time() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/timeb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


exp2f (3p)

 Continue to this page.


gmtime_r (3p)

 Continue to this page.


pthread_mutexattr_getpshared(3p)

PTHREAD_MUTEXATTR_GETPSHARED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_mutexattr_getpshared, pthread_mutexattr_setpshared - get and set the process-shared attribute

SYNOPSIS

#include <pthread.h>

int pthread_mutexattr_getpshared(const pthread_mutexattr_t *
restrict attr, int *restrict pshared);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr,
int pshared);

DESCRIPTION

The pthread_mutexattr_getpshared() function shall obtain the value of the process-shared attribute from the attributes object referenced by attr. The pthread_mutexattr_setpshared() function shall set the process-shared attribute in an initialized attributes object referenced by attr.

The process-shared attribute is set to PTHREAD_PROCESS_SHARED to permit a mutex to be operated upon by any thread that has access to the memory where the mutex is allocated, even if the mutex is allocated in memory that is shared by multiple processes. If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the mutex shall only be operated upon by threads created within the same process as the thread that initialized the mutex; if threads of differing processes attempt to operate on such a mutex, the behavior is undefined. The default value of the attribute shall be PTHREAD_PROCESS_PRIVATE.

RETURN VALUE

Upon successful completion, pthread_mutexattr_setpshared() shall return zero; otherwise, an error number shall be returned to indicate the error.

Upon successful completion, pthread_mutexattr_getpshared() shall return zero and store the value of the process-shared attribute of attr into the object referenced by the pshared parameter. Otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_mutexattr_getpshared() and pthread_mutexattr_setpshared() functions may fail if:

EINVAL
The value specified by attr is invalid.

The pthread_mutexattr_setpshared() function may fail if:

EINVAL
The new value specified for the attribute is outside the range of legal values for that attribute.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_cond_destroy() , pthread_create() , pthread_mutex_destroy() , pthread_mutexattr_destroy() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigpause (3p)

 Continue to this page.


getpmsg (3p)

 Continue to this page.


exp2l (3p)

 Continue to this page.


powf (3p)

 Continue to this page.


asinhf (3p)

 Continue to this page.


powl (3p)

 Continue to this page.


asinhl (3p)

 Continue to this page.


copysignf (3p)

 Continue to this page.


copysignl (3p)

 Continue to this page.


memset(3p)

MEMSET

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

memset - set bytes in memory

SYNOPSIS

#include <string.h>

void *memset(void *s, int c, size_t n);

DESCRIPTION

The memset() function shall copy c (converted to an unsigned char) into each of the first n bytes of the object pointed to by s.

RETURN VALUE

The memset() function shall return s; no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_spawnattr_setschedparam (3p)

 Continue to this page.


readdir_r (3p)

 Continue to this page.


sem_open(3p)

SEM_OPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sem_open - initialize and open a named semaphore (REALTIME)

SYNOPSIS

#include <semaphore.h>

sem_t *sem_open(const char *name, int oflag, ...);

DESCRIPTION

The sem_open() function shall establish a connection between a named semaphore and a process. Following a call to sem_open() with semaphore name name, the process may reference the semaphore associated with name using the address returned from the call. This semaphore may be used in subsequent calls to sem_wait(), sem_trywait(), sem_post(), and sem_close(). The semaphore remains usable by this process until the semaphore is closed by a successful call to sem_close(), _exit(), or one of the exec functions.

The oflag argument controls whether the semaphore is created or merely accessed by the call to sem_open(). The following flag bits may be set in oflag:

O_CREAT
This flag is used to create a semaphore if it does not already exist. If O_CREAT is set and the semaphore already exists, then O_CREAT has no effect, except as noted under O_EXCL. Otherwise, sem_open() creates a named semaphore. The O_CREAT flag requires a third and a fourth argument: mode, which is of type mode_t, and value, which is of type unsigned. The semaphore is created with an initial value of value. Valid initial values for semaphores are less than or equal to {SEM_VALUE_MAX}.

The user ID of the semaphore is set to the effective user ID of the process; the group ID of the semaphore is set to a system default group ID or to the effective group ID of the process. The permission bits of the semaphore are set to the value of the mode argument except those set in the file mode creation mask of the process. When bits in mode other than the file permission bits are specified, the effect is unspecified.

After the semaphore named name has been created by sem_open() with the O_CREAT flag, other processes can connect to the semaphore by calling sem_open() with the same value of name.

O_EXCL
If O_EXCL and O_CREAT are set, sem_open() fails if the semaphore name exists. The check for the existence of the semaphore and the creation of the semaphore if it does not exist are atomic with respect to other processes executing sem_open() with O_EXCL and O_CREAT set. If O_EXCL is set and O_CREAT is not set, the effect is undefined.

If flags other than O_CREAT and O_EXCL are specified in the oflag parameter, the effect is unspecified.

The name argument points to a string naming a semaphore object. It is unspecified whether the name appears in the file system and is visible to functions that take pathnames as arguments. The name argument conforms to the construction rules for a pathname. If name begins with the slash character, then processes calling sem_open() with the same value of name shall refer to the same semaphore object, as long as that name has not been removed. If name does not begin with the slash character, the effect is implementation-defined. The interpretation of slash characters other than the leading slash character in name is implementation-defined.

If a process makes multiple successful calls to sem_open() with the same value for name, the same semaphore address shall be returned for each such successful call, provided that there have been no calls to sem_unlink() for this semaphore.

References to copies of the semaphore produce undefined results.

RETURN VALUE

Upon successful completion, the sem_open() function shall return the address of the semaphore. Otherwise, it shall return a value of SEM_FAILED and set errno to indicate the error. The symbol SEM_FAILED is defined in the <semaphore.h> header. No successful return from sem_open() shall return the value SEM_FAILED.

ERRORS

If any of the following conditions occur, the sem_open() function shall return SEM_FAILED and set errno to the corresponding value:

EACCES
The named semaphore exists and the permissions specified by oflag are denied, or the named semaphore does not exist and permission to create the named semaphore is denied.
EEXIST
O_CREAT and O_EXCL are set and the named semaphore already exists.
EINTR
The sem_open() operation was interrupted by a signal.
EINVAL
The sem_open() operation is not supported for the given name, or O_CREAT was specified in oflag and value was greater than {SEM_VALUE_MAX}.
EMFILE
Too many semaphore descriptors or file descriptors are currently in use by this process.
ENAMETOOLONG
The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
Too many semaphores are currently open in the system.
ENOENT
O_CREAT is not set and the named semaphore does not exist.
ENOSPC
There is insufficient space for the creation of the new named semaphore.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sem_open() function is part of the Semaphores option and need not be available on all implementations.

RATIONALE

Early drafts required an error return value of -1 with the type sem_t * for the sem_open() function, which is not guaranteed to be portable across implementations. The revised text provides the symbolic error code SEM_FAILED to eliminate the type conflict.

FUTURE DIRECTIONS

None.

SEE ALSO

semctl() , semget() , semop() , sem_close() , sem_post() , sem_timedwait() , sem_trywait() , sem_unlink() , sem_wait() , the Base Definitions volume of IEEE Std 1003.1-2001, <semaphore.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


hypot(3p)

HYPOT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

hypot, hypotf, hypotl - Euclidean distance function

SYNOPSIS

#include <math.h>

double hypot(double x, double y);
float hypotf(float x, float y);
long double hypotl(long double x, long double y);

DESCRIPTION

These functions shall compute the value of the square root of x**2+ y**2 without undue overflow or underflow.

An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.

RETURN VALUE

Upon successful completion, these functions shall return the length of the hypotenuse of a right-angled triangle with sides of length x and y.

If the correct value would cause overflow, a range error shall occur and hypot(), hypotf(), and hypotl() shall return the value of the macro HUGE_VAL, HUGE_VALF, and HUGE_VALL, respectively.

If x or y is ±Inf, +Inf shall be returned (even if one of x or y is NaN).

If x or y is NaN, and the other is not ±Inf, a NaN shall be returned.

If both arguments are subnormal and the correct result is subnormal, a range error may occur and the correct result is returned.

ERRORS

These functions shall fail if:

Range Error
The result overflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception shall be raised.

These functions may fail if:

Range Error
The result underflows.

If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno shall be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the underflow floating-point exception shall be raised.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

hypot(x,y), hypot(y,x), and hypot(x, -y) are equivalent.

hypot(x, ±0) is equivalent to fabs(x).

Underflow only happens when both x and y are subnormal and the (inexact) result is also subnormal.

These functions take precautions against overflow during intermediate steps of the computation.

On error, the expressions (math_errhandling & MATH_ERRNO) and (math_errhandling & MATH_ERREXCEPT) are independent of each other, but at least one of them must be non-zero.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

feclearexcept() , fetestexcept() , isnan() , sqrt() , the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


posix_trace_attr_getlogfullpolicy (3p)

 Continue to this page.


pthread_attr_init(3p)

PTHREAD_ATTR_DESTROY

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_attr_destroy, pthread_attr_init - destroy and initialize the thread attributes object

SYNOPSIS

#include <pthread.h>

int pthread_attr_destroy(pthread_attr_t *attr);
int pthread_attr_init(pthread_attr_t *attr);

DESCRIPTION

The pthread_attr_destroy() function shall destroy a thread attributes object. An implementation may cause pthread_attr_destroy() to set attr to an implementation-defined invalid value. A destroyed attr attributes object can be reinitialized using pthread_attr_init(); the results of otherwise referencing the object after it has been destroyed are undefined.

The pthread_attr_init() function shall initialize a thread attributes object attr with the default value for all of the individual attributes used by a given implementation.

The resulting attributes object (possibly modified by setting individual attribute values) when used by pthread_create() defines the attributes of the thread created. A single attributes object can be used in multiple simultaneous calls to pthread_create(). Results are undefined if pthread_attr_init() is called specifying an already initialized attr attributes object.

RETURN VALUE

Upon successful completion, pthread_attr_destroy() and pthread_attr_init() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.

ERRORS

The pthread_attr_init() function shall fail if:

ENOMEM
Insufficient memory exists to initialize the thread attributes object.

These functions shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

Attributes objects are provided for threads, mutexes, and condition variables as a mechanism to support probable future standardization in these areas without requiring that the function itself be changed.

Attributes objects provide clean isolation of the configurable aspects of threads. For example, "stack size" is an important attribute of a thread, but it cannot be expressed portably. When porting a threaded program, stack sizes often need to be adjusted. The use of attributes objects can help by allowing the changes to be isolated in a single place, rather than being spread across every instance of thread creation.

Attributes objects can be used to set up "classes' of threads with similar attributes; for example, "threads with large stacks and high priority" or "threads with minimal stacks". These classes can be defined in a single place and then referenced wherever threads need to be created. Changes to "class" decisions become straightforward, and detailed analysis of each pthread_create() call is not required.

The attributes objects are defined as opaque types as an aid to extensibility. If these objects had been specified as structures, adding new attributes would force recompilation of all multi-threaded programs when the attributes objects are extended; this might not be possible if different program components were supplied by different vendors.

Additionally, opaque attributes objects present opportunities for improving performance. Argument validity can be checked once when attributes are set, rather than each time a thread is created. Implementations often need to cache kernel objects that are expensive to create. Opaque attributes objects provide an efficient mechanism to detect when cached objects become invalid due to attribute changes.

Since assignment is not necessarily defined on a given opaque type, implementation-defined default values cannot be defined in a portable way. The solution to this problem is to allow attributes objects to be initialized dynamically by attributes object initialization functions, so that default values can be supplied automatically by the implementation.

The following proposal was provided as a suggested alternative to the supplied attributes:

1.
Maintain the style of passing a parameter formed by the bitwise-inclusive OR of flags to the initialization routines ( pthread_create(), pthread_mutex_init(), pthread_cond_init()). The parameter containing the flags should be an opaque type for extensibility. If no flags are set in the parameter, then the objects are created with default characteristics. An implementation may specify implementation-defined flag values and associated behavior.

2.
If further specialization of mutexes and condition variables is necessary, implementations may specify additional procedures that operate on the pthread_mutex_t and pthread_cond_t objects (instead of on attributes objects).

The difficulties with this solution are:

1.
A bitmask is not opaque if bits have to be set into bitvector attributes objects using explicitly-coded bitwise-inclusive OR operations. If the set of options exceeds an int, application programmers need to know the location of each bit. If bits are set or read by encapsulation (that is, get and set functions), then the bitmask is merely an implementation of attributes objects as currently defined and should not be exposed to the programmer.

2.
Many attributes are not Boolean or very small integral values. For example, scheduling policy may be placed in 3-bit or 4-bit, but priority requires 5-bit or more, thereby taking up at least 8 bits out of a possible 16 bits on machines with 16-bit integers. Because of this, the bitmask can only reasonably control whether particular attributes are set or not, and it cannot serve as the repository of the value itself. The value needs to be specified as a function parameter (which is non-extensible), or by setting a structure field (which is non-opaque), or by get and set functions (making the bitmask a redundant addition to the attributes objects).

Stack size is defined as an optional attribute because the very notion of a stack is inherently machine-dependent. Some implementations may not be able to change the size of the stack, for example, and others may not need to because stack pages may be discontiguous and can be allocated and released on demand.

The attribute mechanism has been designed in large measure for extensibility. Future extensions to the attribute mechanism or to any attributes object defined in this volume of IEEE Std 1003.1-2001 has to be done with care so as not to affect binary-compatibility.

Attributes objects, even if allocated by means of dynamic allocation functions such as malloc(), may have their size fixed at compile time. This means, for example, a pthread_create() in an implementation with extensions to pthread_attr_t cannot look beyond the area that the binary application assumes is valid. This suggests that implementations should maintain a size field in the attributes object, as well as possibly version information, if extensions in different directions (possibly by different vendors) are to be accommodated.

FUTURE DIRECTIONS

None.

SEE ALSO

pthread_attr_getstackaddr() , pthread_attr_getstacksize() , pthread_attr_getdetachstate() , pthread_create() , the Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_setspecific (3p)

 Continue to this page.


llrintf (3p)

 Continue to this page.


ceilf (3p)

 Continue to this page.


llrintl (3p)

 Continue to this page.


ceill (3p)

 Continue to this page.


roundf (3p)

 Continue to this page.


getchar(3p)

GETCHAR

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getchar - get a byte from a stdin stream

SYNOPSIS

#include <stdio.h>

int getchar(void);

DESCRIPTION

The getchar() function shall be equivalent to getc(stdin).

RETURN VALUE

Refer to fgetc() .

ERRORS

Refer to fgetc() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

If the integer value returned by getchar() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getc() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


roundl (3p)

 Continue to this page.


unlockpt(3p)

UNLOCKPT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

unlockpt - unlock a pseudo-terminal master/slave pair

SYNOPSIS

#include <stdlib.h>

int unlockpt(int fildes);

DESCRIPTION

The unlockpt() function shall unlock the slave pseudo-terminal device associated with the master to which fildes refers.

Conforming applications shall ensure that they call unlockpt() before opening the slave side of a pseudo-terminal device.

RETURN VALUE

Upon successful completion, unlockpt() shall return 0. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The unlockpt() function may fail if:

EBADF
The fildes argument is not a file descriptor open for writing.
EINVAL
The fildes argument is not associated with a master pseudo-terminal device.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

grantpt() , open() , ptsname() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdlib.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_mutexattr_settype (3p)

 Continue to this page.


posix_spawnattr_getflags(3p)

POSIX_SPAWNATTR_GETFLAGS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

posix_spawnattr_getflags, posix_spawnattr_setflags - get and set the spawn-flags attribute of a spawn attributes object (ADVANCED REALTIME)

SYNOPSIS

#include <spawn.h>

int posix_spawnattr_getflags(const posix_spawnattr_t *restrict attr,
short *restrict flags);
int posix_spawnattr_setflags(posix_spawnattr_t *attr, short flags);

DESCRIPTION

The posix_spawnattr_getflags() function shall obtain the value of the spawn-flags attribute from the attributes object referenced by attr.

The posix_spawnattr_setflags() function shall set the spawn-flags attribute in an initialized attributes object referenced by attr.

The spawn-flags attribute is used to indicate which process attributes are to be changed in the new process image when invoking posix_spawn() or posix_spawnp(). It is the bitwise-inclusive OR of zero or more of the following flags:

POSIX_SPAWN_RESETIDS
POSIX_SPAWN_SETPGROUP
POSIX_SPAWN_SETSIGDEF
POSIX_SPAWN_SETSIGMASK

POSIX_SPAWN_SETSCHEDPARAM
POSIX_SPAWN_SETSCHEDULER

These flags are defined in <spawn.h>. The default value of this attribute shall be as if no flags were set.

RETURN VALUE

Upon successful completion, posix_spawnattr_getflags() shall return zero and store the value of the spawn-flags attribute of attr into the object referenced by the flags parameter; otherwise, an error number shall be returned to indicate the error.

Upon successful completion, posix_spawnattr_setflags() shall return zero; otherwise, an error number shall be returned to indicate the error.

ERRORS

These functions may fail if:

EINVAL
The value specified by attr is invalid.

The posix_spawnattr_setflags() function may fail if:

EINVAL
The value of the attribute being set is not valid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

These functions are part of the Spawn option and need not be provided on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

posix_spawn() , posix_spawnattr_destroy() , posix_spawnattr_init()
, posix_spawnattr_getsigdefault() , posix_spawnattr_getpgroup()
, posix_spawnattr_getschedparam() , posix_spawnattr_getschedpolicy()
, posix_spawnattr_getsigmask() , posix_spawnattr_setsigdefault()
, posix_spawnattr_setpgroup() , posix_spawnattr_setschedparam()
, posix_spawnattr_setschedpolicy() , posix_spawnattr_setsigmask()
, posix_spawnp() ,
the Base Definitions volume of IEEE Std 1003.1-2001, <spawn.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


signbit(3p)

SIGNBIT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

signbit - test sign

SYNOPSIS

#include <math.h>

int signbit(real-floating x);

DESCRIPTION

The signbit() macro shall determine whether the sign of its argument value is negative. NaNs, zeros, and infinities have a sign bit.

RETURN VALUE

The signbit() macro shall return a non-zero value if and only if the sign of its argument value is negative.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fpclassify() , isfinite() , isinf() , isnan() , isnormal() , the Base Definitions volume of IEEE Std 1003.1-2001, <math.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


sigprocmask(3p)

PTHREAD_SIGMASK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

pthread_sigmask, sigprocmask - examine and change blocked signals

SYNOPSIS

#include <signal.h>

int pthread_sigmask(int how, const sigset_t *restrict set,
sigset_t *restrict oset);

int sigprocmask(int how, const sigset_t *restrict set,
sigset_t *restrict oset);

DESCRIPTION

The pthread_sigmask() function shall examine or change (or both) the calling thread's signal mask, regardless of the number of threads in the process. The function shall be equivalent to sigprocmask(), without the restriction that the call be made in a single-threaded process.

In a single-threaded process, the sigprocmask() function shall examine or change (or both) the signal mask of the calling thread.

If the argument set is not a null pointer, it points to a set of signals to be used to change the currently blocked set.

The argument how indicates the way in which the set is changed, and the application shall ensure it consists of one of the following values:

SIG_BLOCK
The resulting set shall be the union of the current set and the signal set pointed to by set.
SIG_SETMASK
The resulting set shall be the signal set pointed to by set.
SIG_UNBLOCK
The resulting set shall be the intersection of the current set and the complement of the signal set pointed to by set.

If the argument oset is not a null pointer, the previous mask shall be stored in the location pointed to by oset. If set is a null pointer, the value of the argument how is not significant and the process' signal mask shall be unchanged; thus the call can be used to enquire about currently blocked signals.

If there are any pending unblocked signals after the call to sigprocmask(), at least one of those signals shall be delivered before the call to sigprocmask() returns.

It is not possible to block those signals which cannot be ignored. This shall be enforced by the system without causing an error to be indicated.

If any of the SIGFPE, SIGILL, SIGSEGV, or SIGBUS signals are generated while they are blocked, the result is undefined, unless the signal was generated by the kill() function, the sigqueue() function, or the raise() function.

If sigprocmask() fails, the thread's signal mask shall not be changed.

The use of the sigprocmask() function is unspecified in a multi-threaded process.

RETURN VALUE

Upon successful completion pthread_sigmask() shall return 0; otherwise, it shall return the corresponding error number.

Upon successful completion, sigprocmask() shall return 0; otherwise, -1 shall be returned, errno shall be set to indicate the error, and the process' signal mask shall be unchanged.

ERRORS

The pthread_sigmask() and sigprocmask() functions shall fail if:

EINVAL
The value of the how argument is not equal to one of the defined values.

The pthread_sigmask() function shall not return an error code of [EINTR].

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

When a process' signal mask is changed in a signal-catching function that is installed by sigaction(), the restoration of the signal mask on return from the signal-catching function overrides that change (see sigaction()). If the signal-catching function was installed with signal(), it is unspecified whether this occurs.

See kill() for a discussion of the requirement on delivery of signals.

FUTURE DIRECTIONS

None.

SEE ALSO

sigaction() , sigaddset() , sigdelset() , sigemptyset() , sigfillset() , sigismember() , sigpending() , sigqueue() , sigsuspend() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strfmon(3p)

STRFMON

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strfmon - convert monetary value to a string

SYNOPSIS

#include <monetary.h>

ssize_t strfmon(char *restrict s, size_t maxsize,
const char *restrict format, ...);

DESCRIPTION

The strfmon() function shall place characters into the array pointed to by s as controlled by the string pointed to by format. No more than maxsize bytes are placed into the array.

The format is a character string, beginning and ending in its initial state, if any, that contains two types of objects: plain characters, which are simply copied to the output stream, and conversion specifications, each of which shall result in the fetching of zero or more arguments which are converted and formatted. The results are undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments are simply ignored.

The application shall ensure that a conversion specification consists of the following sequence:

*
A '%' character

*
Optional flags

*
Optional field width

*
Optional left precision

*
Optional right precision

*
A required conversion specifier character that determines the conversion to be performed

Flags

One or more of the following optional flags can be specified to control the conversion:

=f
An '=' followed by a single character f which is used as the numeric fill character. In order to work with precision or width counts, the fill character shall be a single byte character; if not, the behavior is undefined. The default numeric fill character is the <space>. This flag does not affect field width filling which always uses the <space>. This flag is ignored unless a left precision (see below) is specified.
^
Do not format the currency amount with grouping characters. The default is to insert the grouping characters if defined for the current locale.
+ or (
Specify the style of representing positive and negative currency amounts. Only one of '+' or '(' may be specified. If '+' is specified, the locale's equivalent of '+' and '-' are used (for example, in the U.S., the empty string if positive and '-' if negative). If '(' is specified, negative amounts are enclosed within parentheses. If neither flag is specified, the '+' style is used.
!
Suppress the currency symbol from the output conversion.
-
Specify the alignment. If this flag is present the result of the conversion is left-justified (padded to the right) rather than right-justified. This flag shall be ignored unless a field width (see below) is specified.

Field Width

w
A decimal digit string w specifying a minimum field width in bytes in which the result of the conversion is right-justified (or left-justified if the flag '-' is specified). The default is 0.

Left Precision

#n
A '#' followed by a decimal digit string n specifying a maximum number of digits expected to be formatted to the left of the radix character. This option can be used to keep the formatted output from multiple calls to the strfmon() function aligned in the same columns. It can also be used to fill unused positions with a special character as in "$***123.45" . This option causes an amount to be formatted as if it has the number of digits specified by n. If more than n digit positions are required, this conversion specification is ignored. Digit positions in excess of those actually required are filled with the numeric fill character (see the =f flag above).

If grouping has not been suppressed with the '^' flag, and it is defined for the current locale, grouping separators are inserted before the fill characters (if any) are added. Grouping separators are not applied to fill characters even if the fill character is a digit.

To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with <space>s to make their positive and negative formats an equal length.

Right Precision

.p
A period followed by a decimal digit string p specifying the number of digits after the radix character. If the value of the right precision p is 0, no radix character appears. If a right precision is not included, a default specified by the current locale is used. The amount being formatted is rounded to the specified number of digits prior to formatting.

Conversion Specifier Characters

The conversion specifier characters and their meanings are:

i
The double argument is formatted according to the locale's international currency format (for example, in the U.S.: USD 1,234.56). If the argument is ±Inf or NaN, the result of the conversion is unspecified.
n
The double argument is formatted according to the locale's national currency format (for example, in the U.S.: $1,234.56). If the argument is ±Inf or NaN, the result of the conversion is unspecified.
%
Convert to a '%' ; no argument is converted. The entire conversion specification shall be %% .

Locale Information

The LC_MONETARY category of the program's locale affects the behavior of this function including the monetary radix character (which may be different from the numeric radix character affected by the LC_NUMERIC category), the grouping separator, the currency symbols, and formats. The international currency symbol should be conformant with the ISO 4217:1995 standard.

If the value of maxsize is greater than {SSIZE_MAX}, the result is implementation-defined.

RETURN VALUE

If the total number of resulting bytes including the terminating null byte is not more than maxsize, strfmon() shall return the number of bytes placed into the array pointed to by s, not including the terminating null byte. Otherwise, -1 shall be returned, the contents of the array are unspecified, and errno shall be set to indicate the error.

ERRORS

The strfmon() function shall fail if:

E2BIG
Conversion stopped due to lack of space in the buffer.

The following sections are informative.

EXAMPLES

Given a locale for the U.S. and the values 123.45, -123.45, and 3456.781, the following output might be produced. Square brackets ( "[]" ) are used in this example to delimit the output.

%n         [$123.45]         Default formatting
           [-$123.45]
           [$3,456.78]

%11n       [    $123.45]     Right align within an 11-character field
           [   -$123.45]
           [  $3,456.78]

%#5n       [ $   123.45]     Aligned columns for values up to 99999
           [-$   123.45]
           [ $ 3,456.78]

%=*#5n     [ $***123.45]     Specify a fill character
           [-$***123.45]
           [ $*3,456.78]

%=0#5n     [ $000123.45]     Fill characters do not use grouping
           [-$000123.45]     even if the fill character is a digit
           [ $03,456.78]

%^#5n      [ $  123.45]      Disable the grouping separator
           [-$  123.45]
           [ $ 3456.78]

%^#5.0n    [ $  123]         Round off to whole units
           [-$  123]
           [ $ 3457]

%^#5.4n    [ $  123.4500]    Increase the precision
           [-$  123.4500]
           [ $ 3456.7810]

%(#5n      [$   123.45]      Use an alternative pos/neg style
           [($   123.45)]
           [$ 3,456.78]

%!(#5n     [   123.45]       Disable the currency symbol
           [(   123.45)]
           [ 3,456.78]

%-14#5.4n  [ $   123.4500 ]  Left-justify the output
           [-$   123.4500 ]
           [ $ 3,456.7810 ]

%14#5.4n   [  $   123.4500]  Corresponding right-justified output
           [ -$   123.4500]
           [  $ 3,456.7810]

See also the EXAMPLES section in fprintf().

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

Lowercase conversion characters are reserved for future standards use and uppercase for implementation-defined use.

SEE ALSO

fprintf() , localeconv() , the Base Definitions volume of IEEE Std 1003.1-2001, <monetary.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


readlink(3p)

READLINK

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

readlink - read the contents of a symbolic link

SYNOPSIS

#include <unistd.h>

ssize_t readlink(const char *restrict path, char *restrict buf,
size_t bufsize);

DESCRIPTION

The readlink() function shall place the contents of the symbolic link referred to by path in the buffer buf which has size bufsize. If the number of bytes in the symbolic link is less than bufsize, the contents of the remainder of buf are unspecified. If the buf argument is not large enough to contain the link content, the first bufsize bytes shall be placed in buf.

If the value of bufsize is greater than {SSIZE_MAX}, the result is implementation-defined.

RETURN VALUE

Upon successful completion, readlink() shall return the count of bytes placed in the buffer. Otherwise, it shall return a value of -1, leave the buffer unchanged, and set errno to indicate the error.

ERRORS

The readlink() function shall fail if:

EACCES
Search permission is denied for a component of the path prefix of path.
EINVAL
The path argument names a file that is not a symbolic link.
EIO
An I/O error occurred while reading from the file system.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.

The readlink() function may fail if:

EACCES
Read permission is denied for the directory.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

Reading the Name of a Symbolic Link

The following example shows how to read the name of a symbolic link named /modules/pass1.

#include <unistd.h>

char buf[1024];
ssizet_t len;
...
if ((len = readlink("/modules/pass1", buf, sizeof(buf)-1)) != -1)
    buf[len] = '\0';

APPLICATION USAGE

Conforming applications should not assume that the returned contents of the symbolic link are null-terminated.

RATIONALE

Since IEEE Std 1003.1-2001 does not require any association of file times with symbolic links, there is no requirement that file times be updated by readlink(). The type associated with bufsiz is a size_t in order to be consistent with both the ISO C standard and the definition of read(). The behavior specified for readlink() when bufsiz is zero represents historical practice. For this case, the standard developers considered a change whereby readlink() would return the number of non-null bytes contained in the symbolic link with the buffer buf remaining unchanged; however, since the stat structure member st_size value can be used to determine the size of buffer necessary to contain the contents of the symbolic link as returned by readlink(), this proposal was rejected, and the historical practice retained.

FUTURE DIRECTIONS

None.

SEE ALSO

lstat() , stat() , symlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getservbyname (3p)

 Continue to this page.


tempnam(3p)

TEMPNAM

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

tempnam - create a name for a temporary file

SYNOPSIS

#include <stdio.h>

char *tempnam(const char *dir, const char *pfx);

DESCRIPTION

The tempnam() function shall generate a pathname that may be used for a temporary file.

The tempnam() function allows the user to control the choice of a directory. The dir argument points to the name of the directory in which the file is to be created. If dir is a null pointer or points to a string which is not a name for an appropriate directory, the path prefix defined as P_tmpdir in the <stdio.h> header shall be used. If that directory is not accessible, an implementation-defined directory may be used.

Many applications prefer their temporary files to have certain initial letter sequences in their names. The pfx argument should be used for this. This argument may be a null pointer or point to a string of up to five bytes to be used as the beginning of the filename.

Some implementations of tempnam() may use tmpnam() internally. On such implementations, if called more than {TMP_MAX} times in a single process, the behavior is implementation-defined.

RETURN VALUE

Upon successful completion, tempnam() shall allocate space for a string, put the generated pathname in that space, and return a pointer to it. The pointer shall be suitable for use in a subsequent call to free(). Otherwise, it shall return a null pointer and set errno to indicate the error.

ERRORS

The tempnam() function shall fail if:

ENOMEM
Insufficient storage space is available.

The following sections are informative.

EXAMPLES

Generating a Pathname

The following example generates a pathname for a temporary file in directory /tmp, with the prefix file. After the filename has been created, the call to free() deallocates the space used to store the filename.

#include <stdio.h>
#include <stdlib.h>
...
char *directory = "/tmp";
char *fileprefix = "file";
char *file;

file = tempnam(directory, fileprefix);
free(file);

APPLICATION USAGE

This function only creates pathnames. It is the application's responsibility to create and remove the files. Between the time a pathname is created and the file is opened, it is possible for some other process to create a file with the same name. Applications may find tmpfile() more useful.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fopen() , free() , open() , tmpfile() , tmpnam() , unlink() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


getppid(3p)

GETPPID

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getppid - get the parent process ID

SYNOPSIS

#include <unistd.h>

pid_t getppid(void);

DESCRIPTION

The getppid() function shall return the parent process ID of the calling process.

RETURN VALUE

The getppid() function shall always be successful and no return value is reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

exec() , fork() , getpgid() , getpgrp() , getpid() , kill() , setpgid() , setsid() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/types.h>, <unistd.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


timezone (3p)

 Continue to this page.


sigset(3p)

SIGHOLD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sighold, sigignore, sigpause, sigrelse, sigset - signal management

SYNOPSIS

#include <signal.h>

int sighold(int sig);
int sigignore(int sig);
int sigpause(int sig);
int sigrelse(int sig);
void (*sigset(int sig, void (*disp)(int)))(int);

DESCRIPTION

Use of any of these functions is unspecified in a multi-threaded process.

The sighold(), sigignore(), sigpause(), sigrelse(), and sigset() functions provide simplified signal management.

The sigset() function shall modify signal dispositions. The sig argument specifies the signal, which may be any signal except SIGKILL and SIGSTOP. The disp argument specifies the signal's disposition, which may be SIG_DFL, SIG_IGN, or the address of a signal handler. If sigset() is used, and disp is the address of a signal handler, the system shall add sig to the calling process' signal mask before executing the signal handler; when the signal handler returns, the system shall restore the calling process' signal mask to its state prior to the delivery of the signal. In addition, if sigset() is used, and disp is equal to SIG_HOLD, sig shall be added to the calling process' signal mask and sig's disposition shall remain unchanged. If sigset() is used, and disp is not equal to SIG_HOLD, sig shall be removed from the calling process' signal mask.

The sighold() function shall add sig to the calling process' signal mask.

The sigrelse() function shall remove sig from the calling process' signal mask.

The sigignore() function shall set the disposition of sig to SIG_IGN.

The sigpause() function shall remove sig from the calling process' signal mask and suspend the calling process until a signal is received. The sigpause() function shall restore the process' signal mask to its original state before returning.

If the action for the SIGCHLD signal is set to SIG_IGN, child processes of the calling processes shall not be transformed into zombie processes when they terminate. If the calling process subsequently waits for its children, and the process has no unwaited-for children that were transformed into zombie processes, it shall block until all of its children terminate, and wait(), waitid(), and waitpid() shall fail and set errno to [ECHILD].

RETURN VALUE

Upon successful completion, sigset() shall return SIG_HOLD if the signal had been blocked and the signal's previous disposition if it had not been blocked. Otherwise, SIG_ERR shall be returned and errno set to indicate the error.

The sigpause() function shall suspend execution of the thread until a signal is received, whereupon it shall return -1 and set errno to [EINTR].

For all other functions, upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

These functions shall fail if:

EINVAL
The sig argument is an illegal signal number.

The sigset() and sigignore() functions shall fail if:

EINVAL
An attempt is made to catch a signal that cannot be caught, or to ignore a signal that cannot be ignored.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The sigaction() function provides a more comprehensive and reliable mechanism for controlling signals; new applications should use sigaction() rather than sigset().

The sighold() function, in conjunction with sigrelse() or sigpause(), may be used to establish critical regions of code that require the delivery of a signal to be temporarily deferred.

The sigsuspend() function should be used in preference to sigpause() for broader portability.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Signal Concepts , exec() , pause() , sigaction() , signal() , sigsuspend() , waitid() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


pthread_attr_setinheritsched (3p)

 Continue to this page.


killpg(3p)

KILLPG

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

killpg - send a signal to a process group

SYNOPSIS

#include <signal.h>

int killpg(pid_t pgrp, int sig);

DESCRIPTION

The killpg() function shall send the signal specified by sig to the process group specified by pgrp.

If pgrp is greater than 1, killpg(pgrp, sig) shall be equivalent to kill(-pgrp, sig). If pgrp is less than or equal to 1, the behavior of killpg() is undefined.

RETURN VALUE

Refer to kill() .

ERRORS

Refer to kill() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

getpgid() , getpid() , kill() , raise() , the Base Definitions volume of IEEE Std 1003.1-2001, <signal.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


regerror (3p)

 Continue to this page.


mrand48 (3p)

 Continue to this page.


swprintf (3p)

 Continue to this page.


strncat(3p)

STRNCAT

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strncat - concatenate a string with part of another

SYNOPSIS

#include <string.h>

char *strncat(char *restrict s1, const char *restrict s2, size_t n);

DESCRIPTION

The strncat() function shall append not more than n bytes (a null byte and bytes that follow it are not appended) from the array pointed to by s2 to the end of the string pointed to by s1. The initial byte of s2 overwrites the null byte at the end of s1. A terminating null byte is always appended to the result. If copying takes place between objects that overlap, the behavior is undefined.

RETURN VALUE

The strncat() function shall return s1; no return value shall be reserved to indicate an error.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strcat() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


h_errno(3p)

H_ERRNO

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

h_errno - error return value for network database operations

SYNOPSIS

#include <netdb.h>

DESCRIPTION

This method of returning errors is used only in connection with obsolescent functions.

The <netdb.h> header provides a declaration of h_errno as a modifiable lvalue of type int.

It is unspecified whether h_errno is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name h_errno, the behavior is undefined.

RETURN VALUE

None.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Applications should obtain the definition of h_errno by the inclusion of the <netdb.h> header.

RATIONALE

None.

FUTURE DIRECTIONS

h_errno may be withdrawn in a future version.

SEE ALSO

endhostent() , errno() , the Base Definitions volume of IEEE Std 1003.1-2001, <netdb.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmodf (3p)

 Continue to this page.


getchar_unlocked(3p)

GETC_UNLOCKED

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

getc_unlocked, getchar_unlocked, putc_unlocked, putchar_unlocked - stdio with explicit client locking

SYNOPSIS

#include <stdio.h>

int getc_unlocked(FILE *stream);
int getchar_unlocked(void);
int putc_unlocked(int c, FILE *stream);
int putchar_unlocked(int c);

DESCRIPTION

Versions of the functions getc(), getchar(), putc(), and putchar() respectively named getc_unlocked(), getchar_unlocked(), putc_unlocked(), and putchar_unlocked() shall be provided which are functionally equivalent to the original versions, with the exception that they are not required to be implemented in a thread-safe manner. They may only safely be used within a scope protected by flockfile() (or ftrylockfile()) and funlockfile(). These functions may safely be used in a multi-threaded program if and only if they are called while the invoking thread owns the ( FILE *) object, as is the case after a successful call to the flockfile() or ftrylockfile() functions.

RETURN VALUE

See getc() , getchar() , putc() , and putchar() .

ERRORS

See getc() , getchar() , putc() , and putchar() .

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

Since they may be implemented as macros, getc_unlocked() and putc_unlocked() may treat incorrectly a stream argument with side effects. In particular, getc_unlocked(*f++) and putc_unlocked(*f++) do not necessarily work as expected. Therefore, use of these functions in such situations should be preceded by the following statement as appropriate:

#undef getc_unlocked
#undef putc_unlocked

RATIONALE

Some I/O functions are typically implemented as macros for performance reasons (for example, putc() and getc()). For safety, they need to be synchronized, but it is often too expensive to synchronize on every character. Nevertheless, it was felt that the safety concerns were more important; consequently, the getc(), getchar(), putc(), and putchar() functions are required to be thread-safe. However, unlocked versions are also provided with names that clearly indicate the unsafe nature of their operation but can be used to exploit their higher performance. These unlocked versions can be safely used only within explicitly locked program regions, using exported locking primitives. In particular, a sequence such as:

flockfile(fileptr);
putc_unlocked('1', fileptr);
putc_unlocked('\n', fileptr);
fprintf(fileptr, "Line 2\n");
funlockfile(fileptr);

is permissible, and results in the text sequence:

1
Line 2

being printed without being interspersed with output from other threads.

It would be wrong to have the standard names such as getc(), putc(), and so on, map to the "faster, but unsafe" rather than the "slower, but safe'' versions. In either case, you would still want to inspect all uses of getc(), putc(), and so on, by hand when converting existing code. Choosing the safe bindings as the default, at least, results in correct code and maintains the "atomicity at the function" invariant. To do otherwise would introduce gratuitous synchronization errors into converted code. Other routines that modify the stdio ( FILE *) structures or buffers are also safely synchronized.

Note that there is no need for functions of the form getc_locked(), putc_locked(), and so on, since this is the functionality of getc(), putc(), et al. It would be inappropriate to use a feature test macro to switch a macro definition of getc() between getc_locked() and getc_unlocked(), since the ISO C standard requires an actual function to exist, a function whose behavior could not be changed by the feature test macro. Also, providing both the xxx_locked() and xxx_unlocked() forms leads to the confusion of whether the suffix describes the behavior of the function or the circumstances under which it should be used.

Three additional routines, flockfile(), ftrylockfile(), and funlockfile() (which may be macros), are provided to allow the user to delineate a sequence of I/O statements that are executed synchronously.

The ungetc() function is infrequently called relative to the other functions/macros so no unlocked variation is needed.

FUTURE DIRECTIONS

None.

SEE ALSO

getc() , getchar() , putc() , putchar() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


difftime(3p)

DIFFTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

difftime - compute the difference between two calendar time values

SYNOPSIS

#include <time.h>

double difftime(time_t time1, time_t time0);

DESCRIPTION

The difftime() function shall compute the difference between two calendar times (as returned by time()): time1- time0.

RETURN VALUE

The difftime() function shall return the difference expressed in seconds as a type double.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

asctime() , clock() , ctime() , gmtime() , localtime() , mktime() , strftime() , strptime() , time() , utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


fmodl (3p)

 Continue to this page.


printf(3p)

FPRINTF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fprintf, printf, snprintf, sprintf - print formatted output

SYNOPSIS

#include <stdio.h>

int fprintf(FILE *restrict stream, const char *restrict format, ...);
int printf(const char *restrict format, ...);
int snprintf(char *restrict s, size_t n,
const char *restrict format, ...);
int sprintf(char *restrict s, const char *restrict format, ...);

DESCRIPTION

The fprintf() function shall place output on the named output stream. The printf() function shall place output on the standard output stream stdout. The sprintf() function shall place output followed by the null byte, '\0' , in consecutive bytes starting at *s; it is the user's responsibility to ensure that enough space is available.

The snprintf() function shall be equivalent to sprintf(), with the addition of the n argument which states the size of the buffer referred to by s. If n is zero, nothing shall be written and s may be a null pointer. Otherwise, output bytes beyond the n-1st shall be discarded instead of being written to the array, and a null byte is written at the end of the bytes actually written into the array.

If copying takes place between objects that overlap as a result of a call to sprintf() or snprintf(), the results are undefined.

Each of these functions converts, formats, and prints its arguments under control of the format. The format is a character string, beginning and ending in its initial shift state, if any. The format is composed of zero or more directives: ordinary characters, which are simply copied to the output stream, and conversion specifications, each of which shall result in the fetching of zero or more arguments. The results are undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments shall be evaluated but are otherwise ignored.

Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier character % (see below) is replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}], giving the position of the argument in the argument list. This feature provides for the definition of format strings that select arguments in an order appropriate to specific languages (see the EXAMPLES section).

The format can contain either numbered argument conversion specifications (that is, "%n$" and "*m$"), or unnumbered argument conversion specifications (that is, % and * ), but not both. The only exception to this is that %% can be mixed with the "%n$" form. The results of mixing numbered and unnumbered argument specifications in a format string are undefined. When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the (N-1)th, are specified in the format string.

In format strings containing the "%n$" form of conversion specification, numbered arguments in the argument list can be referenced from the format string as many times as required.

In format strings containing the % form of conversion specification, each conversion specification uses the first unused argument in the argument list.

All forms of the fprintf() functions allow for the insertion of a language-dependent radix character in the output string. The radix character is defined in the program's locale (category LC_NUMERIC ). In the POSIX locale, or in a locale where the radix character is not defined, the radix character shall default to a period ( '.' ).

Each conversion specification is introduced by the '%' character or by the character sequence "%n$", after which the following appear in sequence:

*
Zero or more flags (in any order), which modify the meaning of the conversion specification.

*
An optional minimum field width. If the converted value has fewer bytes than the field width, it shall be padded with spaces by default on the left; it shall be padded on the right if the left-adjustment flag ( '-' ), described below, is given to the field width. The field width takes the form of an asterisk ( '*' ), described below, or a decimal integer.

*
An optional precision that gives the minimum number of digits to appear for the d , i , o , u , x , and X conversion specifiers; the number of digits to appear after the radix character for the a , A , e , E , f , and F conversion specifiers; the maximum number of significant digits for the g and G conversion specifiers; or the maximum number of bytes to be printed from a string in the s and S conversion specifiers. The precision takes the form of a period ( '.' ) followed either by an asterisk ( '*' ), described below, or an optional decimal digit string, where a null digit string is treated as zero. If a precision appears with any other conversion specifier, the behavior is undefined.

*
An optional length modifier that specifies the size of the argument.

*
A conversion specifier character that indicates the type of conversion to be applied.

A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision. Applications shall ensure that arguments specifying field width, or precision, or both appear in that order before the argument, if any, to be converted. A negative field width is taken as a '-' flag followed by a positive field width. A negative precision is taken as if the precision were omitted. In format strings containing the "%n$" form of a conversion specification, a field width or precision may be indicated by the sequence "*m$", where m is a decimal integer in the range [1,{NL_ARGMAX}] giving the position in the argument list (after the format argument) of an integer argument containing the field width or precision, for example:

printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);

The flag characters and their meanings are:

'
The integer portion of the result of a decimal conversion ( %i , %d , %u , %f , %F , %g , or %G ) shall be formatted with thousands' grouping characters. For other conversions the behavior is undefined. The non-monetary grouping character is used.
-
The result of the conversion shall be left-justified within the field. The conversion is right-justified if this flag is not specified.
+
The result of a signed conversion shall always begin with a sign ( '+' or '-' ). The conversion shall begin with a sign only when a negative value is converted if this flag is not specified.
<space>
If the first character of a signed conversion is not a sign or if a signed conversion results in no characters, a <space> shall be prefixed to the result. This means that if the <space> and '+' flags both appear, the <space> flag shall be ignored.
#
Specifies that the value is to be converted to an alternative form. For o conversion, it increases the precision (if necessary) to force the first digit of the result to be zero. For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a , A , e , E , f , F , g , and G conversion specifiers, the result shall always contain a radix character, even if no digits follow the radix character. Without this flag, a radix character appears in the result of these conversions only if a digit follows it. For g and G conversion specifiers, trailing zeros shall not be removed from the result as they normally are. For other conversion specifiers, the behavior is undefined.
0
For d , i , o , u , x , X , a , A , e , E , f , F , g , and G conversion specifiers, leading zeros (following any indication of sign or base) are used to pad to the field width; no space padding is performed. If the '0' and '-' flags both appear, the '0' flag is ignored. For d , i , o , u , x , and X conversion specifiers, if a precision is specified, the '0' flag is ignored. If the '0' and '" flags both appear, the grouping characters are inserted before zero padding. For other conversions, the behavior is undefined.

The length modifiers and their meanings are:

hh
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.
h
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a short or unsigned short argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to short or unsigned short before printing); or that a following n conversion specifier applies to a pointer to a short argument.
l (ell)
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a long or unsigned long argument; that a following n conversion specifier applies to a pointer to a long argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a , A , e , E , f , F , g , or G conversion specifier.
ll (ell-ell)

Specifies that a following d , i , o , u , x , or X conversion specifier applies to a long long or unsigned long long argument; or that a following n conversion specifier applies to a pointer to a long long argument.

j
Specifies that a following d , i , o , u , x , or X conversion specifier applies to an intmax_t or uintmax_t argument; or that a following n conversion specifier applies to a pointer to an intmax_t argument.
z
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a size_t or the corresponding signed integer type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to a size_t argument.
t
Specifies that a following d , i , o , u , x , or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.
L
Specifies that a following a , A , e , E , f , F , g , or G conversion specifier applies to a long double argument.

If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.

The conversion specifiers and their meanings are:

d, i
The int argument shall be converted to a signed decimal in the style "[-]dddd". The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision is 1. The result of converting zero with an explicit precision of zero shall be no characters.
o
The unsigned argument shall be converted to unsigned octal format in the style "dddd". The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision is 1. The result of converting zero with an explicit precision of zero shall be no characters.
u
The unsigned argument shall be converted to unsigned decimal format in the style "dddd". The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision is 1. The result of converting zero with an explicit precision of zero shall be no characters.
x
The unsigned argument shall be converted to unsigned hexadecimal format in the style "dddd"; the letters "abcdef" are used. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision is 1. The result of converting zero with an explicit precision of zero shall be no characters.
X
Equivalent to the x conversion specifier, except that letters "ABCDEF" are used instead of "abcdef" .
f, F
The double argument shall be converted to decimal notation in the style "[-]ddd.ddd", where the number of digits after the radix character is equal to the precision specification. If the precision is missing, it shall be taken as 6; if the precision is explicitly zero and no '#' flag is present, no radix character shall appear. If a radix character appears, at least one digit appears before it. The low-order digit shall be rounded in an implementation-defined manner.

A double argument representing an infinity shall be converted in one of the styles "[-]inf" or "[-]infinity" ; which style is implementation-defined. A double argument representing a NaN shall be converted in one of the styles "[-]nan(n-char-sequence)" or "[-]nan" ; which style, and the meaning of any n-char-sequence, is implementation-defined. The F conversion specifier produces "INF" , "INFINITY" , or "NAN" instead of "inf" , "infinity" , or "nan" , respectively.

e, E
The double argument shall be converted in the style "[-]d.ddd e±dd", where there is one digit before the radix character (which is non-zero if the argument is non-zero) and the number of digits after it is equal to the precision; if the precision is missing, it shall be taken as 6; if the precision is zero and no '#' flag is present, no radix character shall appear. The low-order digit shall be rounded in an implementation-defined manner. The E conversion specifier shall produce a number with 'E' instead of 'e' introducing the exponent. The exponent shall always contain at least two digits. If the value is zero, the exponent shall be zero.

A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier.

g, G
The double argument shall be converted in the style f or e (or in the style F or E in the case of a G conversion specifier), with the precision specifying the number of significant digits. If an explicit precision is zero, it shall be taken as 1. The style used depends on the value converted; style e (or E ) shall be used only if the exponent resulting from such a conversion is less than -4 or greater than or equal to the precision. Trailing zeros shall be removed from the fractional portion of the result; a radix character shall appear only if it is followed by a digit or a '#' flag is present.

A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier.

a, A
A double argument representing a floating-point number shall be converted in the style "[-]0x h.hhhh p±d", where there is one hexadecimal digit (which shall be non-zero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point character and the number of hexadecimal digits after it is equal to the precision; if the precision is missing and FLT_RADIX is a power of 2, then the precision shall be sufficient for an exact representation of the value; if the precision is missing and FLT_RADIX is not a power of 2, then the precision shall be sufficient to distinguish values of type double, except that trailing zeros may be omitted; if the precision is zero and the '#' flag is not specified, no decimal-point character shall appear. The letters "abcdef" shall be used for a conversion and the letters "ABCDEF" for A conversion. The A conversion specifier produces a number with 'X' and 'P' instead of 'x' and 'p' . The exponent shall always contain at least one digit, and only as many more digits as necessary to represent the decimal exponent of 2. If the value is zero, the exponent shall be zero.

A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier.

c
The int argument shall be converted to an unsigned char, and the resulting byte shall be written.

If an l (ell) qualifier is present, the wint_t argument shall be converted as if by an ls conversion specification with no precision and an argument that points to a two-element array of type wchar_t, the first element of which contains the wint_t argument to the ls conversion specification and the second element contains a null wide character.

s
The argument shall be a pointer to an array of char. Bytes from the array shall be written up to (but not including) any terminating null byte. If the precision is specified, no more than that many bytes shall be written. If the precision is not specified or is greater than the size of the array, the application shall ensure that the array contains a null byte.

If an l (ell) qualifier is present, the argument shall be a pointer to an array of type wchar_t. Wide characters from the array shall be converted to characters (each as if by a call to the wcrtomb() function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted) up to and including a terminating null wide character. The resulting characters shall be written up to (but not including) the terminating null character (byte). If no precision is specified, the application shall ensure that the array contains a null wide character. If a precision is specified, no more than that many characters (bytes) shall be written (including shift sequences, if any), and the array shall contain a null wide character if, to equal the character sequence length given by the precision, the function would need to access a wide character one past the end of the array. In no case shall a partial character be written.

p
The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printable characters, in an implementation-defined manner.
n
The argument shall be a pointer to an integer into which is written the number of bytes written to the output so far by this call to one of the fprintf() functions. No argument is converted.
C
Equivalent to lc .
S
Equivalent to ls .
%
Print a '%' character; no argument is converted. The complete conversion specification shall be %% .

If a conversion specification does not match one of the above forms, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

In no case shall a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field shall be expanded to contain the conversion result. Characters generated by fprintf() and printf() are printed as if fputc() had been called.

For the a and A conversion specifiers, if FLT_RADIX is a power of 2, the value shall be correctly rounded to a hexadecimal floating number with the given precision.

For a and A conversions, if FLT_RADIX is not a power of 2 and the result is not exactly representable in the given precision, the result should be one of the two adjacent numbers in hexadecimal floating style with the given precision, with the extra stipulation that the error should have a correct sign for the current rounding direction.

For the e , E , f , F , g , and G conversion specifiers, if the number of significant decimal digits is at most DECIMAL_DIG, then the result should be correctly rounded. If the number of significant decimal digits is more than DECIMAL_DIG but the source value is exactly representable with DECIMAL_DIG digits, then the result should be an exact representation with trailing zeros. Otherwise, the source value is bounded by two adjacent decimal strings L < U, both having DECIMAL_DIG significant digits; the value of the resultant decimal string D should satisfy L <= D <= U, with the extra stipulation that the error should have a correct sign for the current rounding direction.

The st_ctime and st_mtime fields of the file shall be marked for update between the call to a successful execution of fprintf() or printf() and the next successful completion of a call to fflush() or fclose() on the same stream or a call to exit() or abort().

RETURN VALUE

Upon successful completion, the fprintf() and printf() functions shall return the number of bytes transmitted.

Upon successful completion, the sprintf() function shall return the number of bytes written to s, excluding the terminating null byte.

Upon successful completion, the snprintf() function shall return the number of bytes that would be written to s had n been sufficiently large excluding the terminating null byte.

If an output error was encountered, these functions shall return a negative value.

If the value of n is zero on a call to snprintf(), nothing shall be written, the number of bytes that would have been written had n been sufficiently large excluding the terminating null shall be returned, and s may be a null pointer.

ERRORS

For the conditions under which fprintf() and printf() fail and may fail, refer to fputc() or fputwc() .

In addition, all forms of fprintf() may fail if:

EILSEQ
A wide-character code that does not correspond to a valid character has been detected.
EINVAL
There are insufficient arguments.

The printf() and fprintf() functions may fail if:

ENOMEM
Insufficient storage space is available.

The snprintf() function shall fail if:

EOVERFLOW
The value of n is greater than {INT_MAX} or the number of bytes needed to hold the output excluding the terminating null is greater than {INT_MAX}.

The following sections are informative.

EXAMPLES

Printing Language-Independent Date and Time

The following statement can be used to print date and time using a language-independent format:

printf(format, weekday, month, day, hour, min);

For American usage, format could be a pointer to the following string:

"%s, %s %d, %d:%.2d\n"

This example would produce the following message:

Sunday, July 3, 10:02

For German usage, format could be a pointer to the following string:

"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"

This definition of format would produce the following message:

Sonntag, 3. Juli, 10:02

Printing File Information

The following example prints information about the type, permissions, and number of links of a specific file in a directory.

The first two calls to printf() use data decoded from a previous stat() call. The user-defined strperm() function shall return a string similar to the one at the beginning of the output for the following command:

ls -l

The next call to printf() outputs the owner's name if it is found using getpwuid(); the getpwuid() function shall return a passwd structure from which the name of the user is extracted. If the user name is not found, the program instead prints out the numeric value of the user ID.

The next call prints out the group name if it is found using getgrgid(); getgrgid() is very similar to getpwuid() except that it shall return group information based on the group number. Once again, if the group is not found, the program prints the numeric value of the group for the entry.

The final call to printf() prints the size of the file.

#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>

char *strperm (mode_t);
...
struct stat statbuf;
struct passwd *pwd;
struct group *grp;
...
printf("%10.10s", strperm (statbuf.st_mode));
printf("%4d", statbuf.st_nlink);

if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
    printf(" %-8.8s", pwd->pw_name);
else
    printf(" %-8ld", (long) statbuf.st_uid);

if ((grp = getgrgid(statbuf.st_gid)) != NULL)
    printf(" %-8.8s", grp->gr_name);
else
    printf(" %-8ld", (long) statbuf.st_gid);

printf("%9jd", (intmax_t) statbuf.st_size);
...

Printing a Localized Date String

The following example gets a localized date string. The nl_langinfo() function shall return the localized date string, which specifies the order and layout of the date. The strftime() function takes this information and, using the tm structure for values, places the date and time information into datestring. The printf() function then outputs datestring and the name of the entry.

#include <stdio.h>
#include <time.h>
#include <langinfo.h>
...
struct dirent *dp;
struct tm *tm;
char datestring[256];
...
strftime(datestring, sizeof(datestring), nl_langinfo (D_T_FMT), tm);

printf(" %s %s\n", datestring, dp->d_name);
...

Printing Error Information

The following example uses fprintf() to write error information to standard error.

In the first group of calls, the program tries to open the password lock file named LOCKFILE. If the file already exists, this is an error, as indicated by the O_EXCL flag on the open() function. If the call fails, the program assumes that someone else is updating the password file, and the program exits.

The next group of calls saves a new password file as the current password file by creating a link between LOCKFILE and the new password file PASSWDFILE.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#define LOCKFILE "/etc/ptmp"
#define PASSWDFILE "/etc/passwd"
...
int pfd;
...
if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
    fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
    exit(1);
}
...
if (link(LOCKFILE,PASSWDFILE) == -1) {
    fprintf(stderr, "Link error: %s\n", strerror(errno));
    exit(1);
}
...

Printing Usage Information

The following example checks to make sure the program has the necessary arguments, and uses fprintf() to print usage information if the expected number of arguments is not present.

#include <stdio.h>
#include <stdlib.h>
...
char *Options = "hdbtl";
...
if (argc < 2) {
    fprintf(stderr, "Usage: %s -%s <file\n", argv[0], Options); exit(1);
}
...

Formatting a Decimal String

The following example prints a key and data pair on stdout. Note use of the '*' (asterisk) in the format string; this ensures the correct number of decimal places for the element based on the number of elements requested.

#include <stdio.h>
...
long i;
char *keystr;
int elementlen, len;
...
while (len < elementlen) {
...
    printf("%s Element%0*ld\n", keystr, elementlen, i);
...
}

Creating a Filename

The following example creates a filename using information from a previous getpwnam() function that returned the HOME directory of the user.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
...
char filename[PATH_MAX+1];
struct passwd *pw;
...
sprintf(filename, "%s/%d.out", pw->pw_dir, getpid());
...

Reporting an Event

The following example loops until an event has timed out. The pause() function waits forever unless it receives a signal. The fprintf() statement should never occur due to the possible return values of pause().

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
...
while (!event_complete) {
...
    if (pause() != -1 || errno != EINTR)
        fprintf(stderr, "pause: unknown error: %s\n", strerror(errno));
}
...

Printing Monetary Information

The following example uses strfmon() to convert a number and store it as a formatted monetary string named convbuf. If the first number is printed, the program prints the format and the description; otherwise, it just prints the number.

#include <monetary.h>
#include <stdio.h>
...
struct tblfmt {
    char *format;
    char *description;
};

struct tblfmt table[] = {
    { "%n", "default formatting" },
    { "%11n", "right align within an 11 character field" },
    { "%#5n", "aligned columns for values up to 99999" },
    { "%=*#5n", "specify a fill character" },
    { "%=0#5n", "fill characters do not use grouping" },
    { "%^#5n", "disable the grouping separator" },
    { "%^#5.0n", "round off to whole units" },
    { "%^#5.4n", "increase the precision" },
    { "%(#5n", "use an alternative pos/neg style" },
    { "%!(#5n", "disable the currency symbol" },
};
...
float input[3];
int i, j;
char convbuf[100];
...
strfmon(convbuf, sizeof(convbuf), table[i].format, input[j]);

if (j == 0) {
    printf("%s  %s  %s\n", table[i].format,
        convbuf, table[i].description);
}
else {
    printf("    %s\n", convbuf);
}
...

Printing Wide Characters

The following example prints a series of wide characters. Suppose that "L`@`" expands to three bytes:

wchar_t wz [3] = L"@@";       // Zero-terminated
wchar_t wn [3] = L"@@@";      // Unterminated

fprintf (stdout,"%ls", wz);   // Outputs 6 bytes
fprintf (stdout,"%ls", wn);   // Undefined because wn has no terminator
fprintf (stdout,"%4ls", wz);  // Outputs 3 bytes
fprintf (stdout,"%4ls", wn);  // Outputs 3 bytes; no terminator needed
fprintf (stdout,"%9ls", wz);  // Outputs 6 bytes
fprintf (stdout,"%9ls", wn);  // Outputs 9 bytes; no terminator needed
fprintf (stdout,"%10ls", wz); // Outputs 6 bytes
fprintf (stdout,"%10ls", wn); // Undefined because wn has no terminator

In the last line of the example, after processing three characters, nine bytes have been output. The fourth character must then be examined to determine whether it converts to one byte or more. If it converts to more than one byte, the output is only nine bytes. Since there is no fourth character in the array, the behavior is undefined.

APPLICATION USAGE

If the application calling fprintf() has any objects of type wint_t or wchar_t, it must also include the <wchar.h> header to have these objects defined.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fputc() , fscanf() , setlocale() , strfmon() , wcrtomb() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <stdio.h>, <wchar.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


FD_CLR (3p)

 Continue to this page.


ilogbf (3p)

 Continue to this page.


fchmod(3p)

FCHMOD

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

fchmod - change mode of a file

SYNOPSIS

#include <sys/stat.h>

int fchmod(int fildes, mode_t mode);

DESCRIPTION

The fchmod() function shall be equivalent to chmod() except that the file whose permissions are changed is specified by the file descriptor fildes.

If fildes references a shared memory object, the fchmod() function need only affect the S_IRUSR, S_IWUSR, S_IRGRP, S_IWGRP, S_IROTH, and S_IWOTH file permission bits.

If fildes references a typed memory object, the behavior of fchmod() is unspecified.

If fildes refers to a socket, the behavior of fchmod() is unspecified.

If fildes refers to a STREAM (which is fattach()-ed into the file system name space) the call returns successfully, doing nothing.

RETURN VALUE

Upon successful completion, fchmod() shall return 0. Otherwise, it shall return -1 and set errno to indicate the error.

ERRORS

The fchmod() function shall fail if:

EBADF
The fildes argument is not an open file descriptor.
EPERM
The effective user ID does not match the owner of the file and the process does not have appropriate privilege.
EROFS
The file referred to by fildes resides on a read-only file system.

The fchmod() function may fail if:

EINTR
The fchmod() function was interrupted by a signal.
EINVAL
The value of the mode argument is invalid.
EINVAL
The fildes argument refers to a pipe and the implementation disallows execution of fchmod() on a pipe.

The following sections are informative.

EXAMPLES

Changing the Current Permissions for a File

The following example shows how to change the permissions for a file named /home/cnd/mod1 so that the owner and group have read/write/execute permissions, but the world only has read/write permissions.

#include <sys/stat.h>
#include <fcntl.h>

mode_t mode;
int    fildes;
...
fildes = open("/home/cnd/mod1", O_RDWR);
fchmod(fildes, S_IRWXU | S_IRWXG | S_IROTH | S_IWOTH);

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

chmod() , chown() , creat() , fcntl() , fstatvfs() , mknod() , open() , read() , stat() , write() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


ilogbl (3p)

 Continue to this page.


aio_cancel(3p)

AIO_CANCEL

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

aio_cancel - cancel an asynchronous I/O request (REALTIME)

SYNOPSIS

#include <aio.h>

int aio_cancel(int fildes, struct aiocb *aiocbp);

DESCRIPTION

The aio_cancel() function shall attempt to cancel one or more asynchronous I/O requests currently outstanding against file descriptor fildes. The aiocbp argument points to the asynchronous I/O control block for a particular request to be canceled. If aiocbp is NULL, then all outstanding cancelable asynchronous I/O requests against fildes shall be canceled.

Normal asynchronous notification shall occur for asynchronous I/O operations that are successfully canceled. If there are requests that cannot be canceled, then the normal asynchronous completion process shall take place for those requests when they are completed.

For requested operations that are successfully canceled, the associated error status shall be set to [ECANCELED] and the return status shall be -1. For requested operations that are not successfully canceled, the aiocbp shall not be modified by aio_cancel().

If aiocbp is not NULL, then if fildes does not have the same value as the file descriptor with which the asynchronous operation was initiated, unspecified results occur.

Which operations are cancelable is implementation-defined.

RETURN VALUE

The aio_cancel() function shall return the value AIO_CANCELED to the calling process if the requested operation(s) were canceled. The value AIO_NOTCANCELED shall be returned if at least one of the requested operation(s) cannot be canceled because it is in progress. In this case, the state of the other operations, if any, referenced in the call to aio_cancel() is not indicated by the return value of aio_cancel(). The application may determine the state of affairs for these operations by using aio_error(). The value AIO_ALLDONE is returned if all of the operations have already completed. Otherwise, the function shall return -1 and set errno to indicate the error.

ERRORS

The aio_cancel() function shall fail if:

EBADF
The fildes argument is not a valid file descriptor.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

The aio_cancel() function is part of the Asynchronous Input and Output option and need not be available on all implementations.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

aio_read() , aio_write() , the Base Definitions volume of IEEE Std 1003.1-2001, <aio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


erand48 (3p)

 Continue to this page.


putchar_unlocked (3p)

 Continue to this page.


pututxline (3p)

 Continue to this page.


truncf (3p)

 Continue to this page.


truncl (3p)

 Continue to this page.


utimes(3p)

UTIMES

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

utimes - set file access and modification times (LEGACY)

SYNOPSIS

#include <sys/time.h>

int utimes(const char *path, const struct timeval times[2]);

DESCRIPTION

The utimes() function shall set the access and modification times of the file pointed to by the path argument to the value of the times argument. The utimes() function allows time specifications accurate to the microsecond.

For utimes(), the times argument is an array of timeval structures. The first array member represents the date and time of last access, and the second member represents the date and time of last modification. The times in the timeval structure are measured in seconds and microseconds since the Epoch, although rounding toward the nearest second may occur.

If the times argument is a null pointer, the access and modification times of the file shall be set to the current time. The effective user ID of the process shall match the owner of the file, or has write access to the file or appropriate privileges to use this call in this manner. Upon completion, utimes() shall mark the time of the last file status change, st_ctime, for update.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno shall be set to indicate the error, and the file times shall not be affected.

ERRORS

The utimes() function shall fail if:

EACCES
Search permission is denied by a component of the path prefix; or the times argument is a null pointer and the effective user ID of the process does not match the owner of the file and write access is denied.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The times argument is not a null pointer and the calling process' effective user ID has write access to the file but does not match the owner of the file and the calling process does not have the appropriate privileges.
EROFS
The file system containing the file is read-only.

The utimes() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

For applications portability, the utime() function should be used to set file access and modification times instead of utimes().

RATIONALE

None.

FUTURE DIRECTIONS

This function may be withdrawn in a future version.

SEE ALSO

utime() , the Base Definitions volume of IEEE Std 1003.1-2001, <sys/time.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


freopen(3p)

FREOPEN

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

freopen - open a stream

SYNOPSIS

#include <stdio.h>

FILE *freopen(const char *restrict filename, const char *restrict mode,
FILE *restrict stream);

DESCRIPTION

The freopen() function shall first attempt to flush the stream and close any file descriptor associated with stream. Failure to flush or close the file descriptor successfully shall be ignored. The error and end-of-file indicators for the stream shall be cleared.

The freopen() function shall open the file whose pathname is the string pointed to by filename and associate the stream pointed to by stream with it. The mode argument shall be used just as in fopen().

The original stream shall be closed regardless of whether the subsequent open succeeds.

If filename is a null pointer, the freopen() function shall attempt to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances.

After a successful call to the freopen() function, the orientation of the stream shall be cleared, the encoding rule shall be cleared, and the associated mbstate_t object shall be set to describe an initial conversion state.

The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description.

RETURN VALUE

Upon successful completion, freopen() shall return the value of stream. Otherwise, a null pointer shall be returned, and errno shall be set to indicate the error.

ERRORS

The freopen() function shall fail if:

EACCES
Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created.
EINTR
A signal was caught during freopen().
EISDIR
The named file is a directory and mode requires write access.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG

The length of the filename argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.

ENFILE
The maximum allowable number of files is currently open in the system.
ENOENT
A component of filename does not name an existing file or filename is an empty string.
ENOSPC
The directory or file system that would contain the new file cannot be expanded, the file does not exist, and it was to be created.
ENOTDIR
A component of the path prefix is not a directory.
ENXIO
The named file is a character special or block special file, and the device associated with this special file does not exist.
EOVERFLOW
The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only file system and mode requires write access.

The freopen() function may fail if:

EINVAL
The value of the mode argument is not valid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG

Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

ENOMEM
Insufficient storage space is available.
ENXIO
A request was made of a nonexistent device, or the request was outside the capabilities of the device.
ETXTBSY
The file is a pure procedure (shared text) file that is being executed and mode requires write access.

The following sections are informative.

EXAMPLES

Directing Standard Output to a File

The following example logs all standard output to the /tmp/logfile file.

#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);
...

APPLICATION USAGE

The freopen() function is typically used to attach the preopened streams associated with stdin, stdout, and stderr to other files.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

fclose() , fopen() , fdopen() , mbsinit() , the Base Definitions volume of IEEE Std 1003.1-2001, <stdio.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strtoimax(3p)

STRTOIMAX

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strtoimax, strtoumax - convert string to integer type

SYNOPSIS

#include <inttypes.h>

intmax_t strtoimax(const char *restrict nptr, char **restrict endptr,
int base);
uintmax_t strtoumax(const char *restrict nptr, char **restrict endptr,
int base);

DESCRIPTION

These functions shall be equivalent to the strtol(), strtoll(), strtoul(), and strtoull() functions, except that the initial portion of the string shall be converted to intmax_t and uintmax_t representation, respectively.

RETURN VALUE

These functions shall return the converted value, if any.

If no conversion could be performed, zero shall be returned.

If the correct value is outside the range of representable values, {INTMAX_MAX}, {INTMAX_MIN}, or {UINTMAX_MAX} shall be returned (according to the return type and sign of the value, if any), and errno shall be set to [ERANGE].

ERRORS

These functions shall fail if:

ERANGE
The value to be returned is not representable.

These functions may fail if:

EINVAL
The value of base is not supported.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strtol() , strtoul() , the Base Definitions volume of IEEE Std 1003.1-2001, <inttypes.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


inet_ntoa (3p)

 Continue to this page.


sysconf(3p)

SYSCONF

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

sysconf - get configurable system variables

SYNOPSIS

#include <unistd.h>

long sysconf(int name);

DESCRIPTION

The sysconf() function provides a method for the application to determine the current value of a configurable system limit or option ( variable). The implementation shall support all of the variables listed in the following table and may support others.

The name argument represents the system variable to be queried. The following table lists the minimal set of system variables from <limits.h> or <unistd.h> that can be returned by sysconf(), and the symbolic constants defined in <unistd.h> that are the corresponding values used for name.
Variable | Value of Name
{AIO_LISTIO_MAX} | _SC_AIO_LISTIO_MAX
{AIO_MAX} | _SC_AIO_MAX
{AIO_PRIO_DELTA_MAX} | _SC_AIO_PRIO_DELTA_MAX
{ARG_MAX} | _SC_ARG_MAX
{ATEXIT_MAX} | _SC_ATEXIT_MAX
{BC_BASE_MAX} | _SC_BC_BASE_MAX
{BC_DIM_MAX} | _SC_BC_DIM_MAX
{BC_SCALE_MAX} | _SC_BC_SCALE_MAX
{BC_STRING_MAX} | _SC_BC_STRING_MAX
{CHILD_MAX} | _SC_CHILD_MAX
Clock ticks/second | _SC_CLK_TCK
{COLL_WEIGHTS_MAX} | _SC_COLL_WEIGHTS_MAX
{DELAYTIMER_MAX} | _SC_DELAYTIMER_MAX
{EXPR_NEST_MAX} | _SC_EXPR_NEST_MAX
{HOST_NAME_MAX} | _SC_HOST_NAME_MAX
{IOV_MAX} | _SC_IOV_MAX
{LINE_MAX} | _SC_LINE_MAX
{LOGIN_NAME_MAX} | _SC_LOGIN_NAME_MAX
{NGROUPS_MAX} | _SC_NGROUPS_MAX
Maximum size of getgrgid_r() and | _SC_GETGR_R_SIZE_MAX
getgrnam_r() data buffers |
Maximum size of getpwuid_r() and | _SC_GETPW_R_SIZE_MAX
getpwnam_r() data buffers |
{MQ_OPEN_MAX} | _SC_MQ_OPEN_MAX
{MQ_PRIO_MAX} | _SC_MQ_PRIO_MAX
{OPEN_MAX} | _SC_OPEN_MAX
_POSIX_ADVISORY_INFO | _SC_ADVISORY_INFO
_POSIX_BARRIERS | _SC_BARRIERS
_POSIX_ASYNCHRONOUS_IO | _SC_ASYNCHRONOUS_IO
_POSIX_CLOCK_SELECTION | _SC_CLOCK_SELECTION
_POSIX_CPUTIME | _SC_CPUTIME
_POSIX_FILE_LOCKING | _SC_FILE_LOCKING
_POSIX_FSYNC | _SC_FSYNC
_POSIX_IPV6 | _SC_IPV6
_POSIX_JOB_CONTROL | _SC_JOB_CONTROL
_POSIX_MAPPED_FILES | _SC_MAPPED_FILES
_POSIX_MEMLOCK | _SC_MEMLOCK
_POSIX_MEMLOCK_RANGE | _SC_MEMLOCK_RANGE
_POSIX_MEMORY_PROTECTION | _SC_MEMORY_PROTECTION
_POSIX_MESSAGE_PASSING | _SC_MESSAGE_PASSING
_POSIX_MONOTONIC_CLOCK | _SC_MONOTONIC_CLOCK
_POSIX_MULTI_PROCESS | _SC_MULTI_PROCESS
_POSIX_PRIORITIZED_IO | _SC_PRIORITIZED_IO
_POSIX_PRIORITY_SCHEDULING | _SC_PRIORITY_SCHEDULING
_POSIX_RAW_SOCKETS | _SC_RAW_SOCKETS
_POSIX_READER_WRITER_LOCKS | _SC_READER_WRITER_LOCKS
_POSIX_REALTIME_SIGNALS | _SC_REALTIME_SIGNALS
_POSIX_REGEXP | _SC_REGEXP
_POSIX_SAVED_IDS | _SC_SAVED_IDS
_POSIX_SEMAPHORES | _SC_SEMAPHORES
_POSIX_SHARED_MEMORY_OBJECTS | _SC_SHARED_MEMORY_OBJECTS
_POSIX_SHELL | _SC_SHELL
_POSIX_SPAWN | _SC_SPAWN
_POSIX_SPIN_LOCKS | _SC_SPIN_LOCKS
_POSIX_SPORADIC_SERVER | _SC_SPORADIC_SERVER
_POSIX_SYMLOOP_MAX | _SC_SYMLOOP_MAX
_POSIX_SYNCHRONIZED_IO | _SC_SYNCHRONIZED_IO
_POSIX_THREAD_ATTR_STACKADDR | _SC_THREAD_ATTR_STACKADDR
_POSIX_THREAD_ATTR_STACKSIZE | _SC_THREAD_ATTR_STACKSIZE
_POSIX_THREAD_CPUTIME | _SC_THREAD_CPUTIME
_POSIX_THREAD_PRIO_INHERIT | _SC_THREAD_PRIO_INHERIT
_POSIX_THREAD_PRIO_PROTECT | _SC_THREAD_PRIO_PROTECT
_POSIX_THREAD_PRIORITY_SCHEDULING | _SC_THREAD_PRIORITY_SCHEDULING
_POSIX_THREAD_PROCESS_SHARED | _SC_THREAD_PROCESS_SHARED
_POSIX_THREAD_SAFE_FUNCTIONS | _SC_THREAD_SAFE_FUNCTIONS
_POSIX_THREAD_SPORADIC_SERVER | _SC_THREAD_SPORADIC_SERVER
_POSIX_THREADS | _SC_THREADS
_POSIX_TIMEOUTS | _SC_TIMEOUTS
_POSIX_TIMERS | _SC_TIMERS
_POSIX_TRACE | _SC_TRACE
_POSIX_TRACE_EVENT_FILTER | _SC_TRACE_EVENT_FILTER
_POSIX_TRACE_INHERIT | _SC_TRACE_INHERIT
_POSIX_TRACE_LOG | _SC_TRACE_LOG
_POSIX_TYPED_MEMORY_OBJECTS | _SC_TYPED_MEMORY_OBJECTS
_POSIX_VERSION | _SC_VERSION
_POSIX_V6_ILP32_OFF32 | _SC_V6_ILP32_OFF32
_POSIX_V6_ILP32_OFFBIG | _SC_V6_ILP32_OFFBIG
_POSIX_V6_LP64_OFF64 | _SC_V6_LP64_OFF64
_POSIX_V6_LPBIG_OFFBIG | _SC_V6_LPBIG_OFFBIG
_POSIX2_C_BIND | _SC_2_C_BIND
_POSIX2_C_DEV | _SC_2_C_DEV
_POSIX2_C_VERSION | _SC_2_C_VERSION
_POSIX2_CHAR_TERM | _SC_2_CHAR_TERM
_POSIX2_FORT_DEV | _SC_2_FORT_DEV
_POSIX2_FORT_RUN | _SC_2_FORT_RUN
_POSIX2_LOCALEDEF | _SC_2_LOCALEDEF
_POSIX2_PBS | _SC_2_PBS
_POSIX2_PBS_ACCOUNTING | _SC_2_PBS_ACCOUNTING
_POSIX2_PBS_CHECKPOINT | _SC_2_PBS_CHECKPOINT
_POSIX2_PBS_LOCATE | _SC_2_PBS_LOCATE
_POSIX2_PBS_MESSAGE | _SC_2_PBS_MESSAGE
_POSIX2_PBS_TRACK | _SC_2_PBS_TRACK
_POSIX2_SW_DEV | _SC_2_SW_DEV
_POSIX2_UPE | _SC_2_UPE
_POSIX2_VERSION | _SC_2_VERSION
_REGEX_VERSION | _SC_REGEX_VERSION
{PAGE_SIZE} | _SC_PAGE_SIZE
{PAGESIZE} | _SC_PAGESIZE
{PTHREAD_DESTRUCTOR_ITERATIONS} | _SC_THREAD_DESTRUCTOR_ITERATIONS
{PTHREAD_KEYS_MAX} | _SC_THREAD_KEYS_MAX
{PTHREAD_STACK_MIN} | _SC_THREAD_STACK_MIN
{PTHREAD_THREADS_MAX} | _SC_THREAD_THREADS_MAX
{RE_DUP_MAX} | _SC_RE_DUP_MAX
{RTSIG_MAX} | _SC_RTSIG_MAX
{SEM_NSEMS_MAX} | _SC_SEM_NSEMS_MAX
{SEM_VALUE_MAX} | _SC_SEM_VALUE_MAX
{SIGQUEUE_MAX} | _SC_SIGQUEUE_MAX
{STREAM_MAX} | _SC_STREAM_MAX
{SYMLOOP_MAX} | _SC_SYMLOOP_MAX
{TIMER_MAX} | _SC_TIMER_MAX
{TTY_NAME_MAX} | _SC_TTY_NAME_MAX
{TZNAME_MAX} | _SC_TZNAME_MAX
_XBS5_ILP32_OFF32 (LEGACY) | _SC_XBS5_ILP32_OFF32 (LEGACY)
_XBS5_ILP32_OFFBIG (LEGACY) | _SC_XBS5_ILP32_OFFBIG (LEGACY)
_XBS5_LP64_OFF64 (LEGACY) | _SC_XBS5_LP64_OFF64 (LEGACY)
_XBS5_LPBIG_OFFBIG (LEGACY) | _SC_XBS5_LPBIG_OFFBIG (LEGACY)
_XOPEN_CRYPT | _SC_XOPEN_CRYPT
_XOPEN_ENH_I18N | _SC_XOPEN_ENH_I18N
_XOPEN_LEGACY | _SC_XOPEN_LEGACY
_XOPEN_REALTIME | _SC_XOPEN_REALTIME
_XOPEN_REALTIME_THREADS | _SC_XOPEN_REALTIME_THREADS
_XOPEN_SHM | _SC_XOPEN_SHM
_XOPEN_STREAMS | _SC_XOPEN_STREAMS
_XOPEN_UNIX | _SC_XOPEN_UNIX
_XOPEN_VERSION | _SC_XOPEN_VERSION
_XOPEN_XCU_VERSION | _SC_XOPEN_XCU_VERSION

RETURN VALUE

If name is an invalid value, sysconf() shall return -1 and set errno to indicate the error. If the variable corresponding to name has no limit, sysconf() shall return -1 without changing the value of errno. Note that indefinite limits do not imply infinite limits; see <limits.h>.

Otherwise, sysconf() shall return the current variable value on the system. The value returned shall not be more restrictive than the corresponding value described to the application when it was compiled with the implementation's <limits.h> or <unistd.h>. The value shall not change during the lifetime of the calling process, except that sysconf(_SC_OPEN_MAX) may return different values before and after a call to setrlimit() which changes the RLIMIT_NOFILE soft limit.

ERRORS

The sysconf() function shall fail if:

EINVAL
The value of the name argument is invalid.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

As -1 is a permissible return value in a successful situation, an application wishing to check for error situations should set errno to 0, then call sysconf(), and, if it returns -1, check to see if errno is non-zero.

If the value of sysconf(_SC_2_VERSION) is not equal to the value of the _POSIX2_VERSION symbolic constant, the utilities available via system() or popen() might not behave as described in the Shell and Utilities volume of IEEE Std 1003.1-2001. This would mean that the application is not running in an environment that conforms to the Shell and Utilities volume of IEEE Std 1003.1-2001. Some applications might be able to deal with this, others might not. However, the functions defined in this volume of IEEE Std 1003.1-2001 continue to operate as specified, even if sysconf(_SC_2_VERSION) reports that the utilities no longer perform as specified.

RATIONALE

This functionality was added in response to requirements of application developers and of system vendors who deal with many international system configurations. It is closely related to pathconf() and fpathconf().

Although a conforming application can run on all systems by never demanding more resources than the minimum values published in this volume of IEEE Std 1003.1-2001, it is useful for that application to be able to use the actual value for the quantity of a resource available on any given system. To do this, the application makes use of the value of a symbolic constant in <limits.h> or <unistd.h>.

However, once compiled, the application must still be able to cope if the amount of resource available is increased. To that end, an application may need a means of determining the quantity of a resource, or the presence of an option, at execution time.

Two examples are offered:

1.
Applications may wish to act differently on systems with or without job control. Applications vendors who wish to distribute only a single binary package to all instances of a computer architecture would be forced to assume job control is never available if it were to rely solely on the <unistd.h> value published in this volume of IEEE Std 1003.1-2001.

2.
International applications vendors occasionally require knowledge of the number of clock ticks per second. Without these facilities, they would be required to either distribute their applications partially in source form or to have 50 Hz and 60 Hz versions for the various countries in which they operate.

It is the knowledge that many applications are actually distributed widely in executable form that leads to this facility. If limited to the most restrictive values in the headers, such applications would have to be prepared to accept the most limited environments offered by the smallest microcomputers. Although this is entirely portable, there was a consensus that they should be able to take advantage of the facilities offered by large systems, without the restrictions associated with source and object distributions.

During the discussions of this feature, it was pointed out that it is almost always possible for an application to discern what a value might be at runtime by suitably testing the various functions themselves. And, in any event, it could always be written to adequately deal with error returns from the various functions. In the end, it was felt that this imposed an unreasonable level of complication and sophistication on the application writer.

This runtime facility is not meant to provide ever-changing values that applications have to check multiple times. The values are seen as changing no more frequently than once per system initialization, such as by a system administrator or operator with an automatic configuration program. This volume of IEEE Std 1003.1-2001 specifies that they shall not change within the lifetime of the process.

Some values apply to the system overall and others vary at the file system or directory level. The latter are described in pathconf() .

Note that all values returned must be expressible as integers. String values were considered, but the additional flexibility of this approach was rejected due to its added complexity of implementation and use.

Some values, such as {PATH_MAX}, are sometimes so large that they must not be used to, say, allocate arrays. The sysconf() function returns a negative value to show that this symbolic constant is not even defined in this case.

Similar to pathconf(), this permits the implementation not to have a limit. When one resource is infinite, returning an error indicating that some other resource limit has been reached is conforming behavior.

FUTURE DIRECTIONS

None.

SEE ALSO

confstr() , pathconf() , the Base Definitions volume of IEEE Std 1003.1-2001, <limits.h>, <unistd.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001, getconf

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


wctrans(3p)

WCTRANS

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

wctrans - define character mapping

SYNOPSIS

#include <wctype.h>

wctrans_t wctrans(const char *charclass);

DESCRIPTION

The wctrans() function is defined for valid character mapping names identified in the current locale. The charclass is a string identifying a generic character mapping name for which codeset-specific information is required. The following character mapping names are defined in all locales: tolower and toupper.

The function shall return a value of type wctrans_t, which can be used as the second argument to subsequent calls of towctrans(). The wctrans() function shall determine values of wctrans_t according to the rules of the coded character set defined by character mapping information in the program's locale (category LC_CTYPE ). The values returned by wctrans() shall be valid until a call to setlocale() that modifies the category LC_CTYPE .

RETURN VALUE

The wctrans() function shall return 0 and may set errno to indicate the error if the given character mapping name is not valid for the current locale (category LC_CTYPE ); otherwise, it shall return a non-zero object of type wctrans_t that can be used in calls to towctrans().

ERRORS

The wctrans() function may fail if:

EINVAL
The character mapping name pointed to by charclass is not valid in the current locale.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

towctrans() , the Base Definitions volume of IEEE Std 1003.1-2001, <wctype.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


utime(3p)

UTIME

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

utime - set file access and modification times

SYNOPSIS

#include <utime.h>

int utime(const char *path, const struct utimbuf *times);

DESCRIPTION

The utime() function shall set the access and modification times of the file named by the path argument.

If times is a null pointer, the access and modification times of the file shall be set to the current time. The effective user ID of the process shall match the owner of the file, or the process has write permission to the file or has appropriate privileges, to use utime() in this manner.

If times is not a null pointer, times shall be interpreted as a pointer to a utimbuf structure and the access and modification times shall be set to the values contained in the designated structure. Only a process with the effective user ID equal to the user ID of the file or a process with appropriate privileges may use utime() this way.

The utimbuf structure is defined in the <utime.h> header. The times in the structure utimbuf are measured in seconds since the Epoch.

Upon successful completion, utime() shall mark the time of the last file status change, st_ctime, to be updated; see <sys/stat.h>.

RETURN VALUE

Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno shall be set to indicate the error, and the file times shall not be affected.

ERRORS

The utime() function shall fail if:

EACCES
Search permission is denied by a component of the path prefix; or the times argument is a null pointer and the effective user ID of the process does not match the owner of the file, the process does not have write permission for the file, and the process does not have appropriate privileges.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
EPERM
The times argument is not a null pointer and the calling process' effective user ID does not match the owner of the file and the calling process does not have the appropriate privileges.
EROFS
The file system containing the file is read-only.

The utime() function may fail if:

ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

The actime structure member must be present so that an application may set it, even though an implementation may ignore it and not change the access time on the file. If an application intends to leave one of the times of a file unchanged while changing the other, it should use stat() to retrieve the file's st_atime and st_mtime parameters, set actime and modtime in the buffer, and change one of them before making the utime() call.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <sys/stat.h>, <utime.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


strncmp(3p)

STRNCMP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

strncmp - compare part of two strings

SYNOPSIS

#include <string.h>

int strncmp(const char *s1, const char *s2, size_t n);

DESCRIPTION

The strncmp() function shall compare not more than n bytes (bytes that follow a null byte are not compared) from the array pointed to by s1 to the array pointed to by s2.

The sign of a non-zero return value is determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared.

RETURN VALUE

Upon successful completion, strncmp() shall return an integer greater than, equal to, or less than 0, if the possibly null-terminated array pointed to by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2 respectively.

ERRORS

No errors are defined.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

strcmp() , the Base Definitions volume of IEEE Std 1003.1-2001, <string.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


inet_ntop(3p)

INET_NTOP

Section: POSIX Programmer's Manual (P)
Updated: 2003 Return to Main Contents

NAME

inet_ntop, inet_pton - convert IPv4 and IPv6 addresses between binary and text form

SYNOPSIS

#include <arpa/inet.h>

const char *inet_ntop(int af, const void *restrict src,
char *restrict dst, socklen_t size);
int inet_pton(int af, const char *restrict src, void *restrict dst);

DESCRIPTION

The inet_ntop() function shall convert a numeric address into a text string suitable for presentation. The af argument shall specify the family of the address. This can be AF_INET or AF_INET6. The src argument points to a buffer holding an IPv4 address if the af argument is AF_INET, or an IPv6 address if the af argument is AF_INET6; the address must be in network byte order. The dst argument points to a buffer where the function stores the resulting text string; it shall not be NULL. The size argument specifies the size of this buffer, which shall be large enough to hold the text string (INET_ADDRSTRLEN characters for IPv4, INET6_ADDRSTRLEN characters for IPv6).

The inet_pton() function shall convert an address in its standard text presentation form into its numeric binary form. The af argument shall specify the family of the address. The AF_INET and AF_INET6 address families shall be supported. The src argument points to the string being passed in. The dst argument points to a buffer into which the function stores the numeric address; this shall be large enough to hold the numeric address (32 bits for AF_INET, 128 bits for AF_INET6).

If the af argument of inet_pton() is AF_INET, the src string shall be in the standard IPv4 dotted-decimal form:

ddd.ddd.ddd.ddd

where "ddd" is a one to three digit decimal number between 0 and 255 (see inet_addr() ). The inet_pton() function does not accept other formats (such as the octal numbers, hexadecimal numbers, and fewer than four numbers that inet_addr() accepts).

If the af argument of inet_pton() is AF_INET6, the src string shall be in one of the following standard IPv6 text forms:

1.
The preferred form is "x:x:x:x:x:x:x:x" , where the 'x' s are the hexadecimal values of the eight 16-bit pieces of the address. Leading zeros in individual fields can be omitted, but there shall be at least one numeral in every field.

2.
A string of contiguous zero fields in the preferred form can be shown as "::" . The "::" can only appear once in an address. Unspecified addresses ( "0:0:0:0:0:0:0:0" ) may be represented simply as "::" .

3.
A third form that is sometimes more convenient when dealing with a mixed environment of IPv4 and IPv6 nodes is "x:x:x:x:x:x:d.d.d.d" , where the 'x' s are the hexadecimal values of the six high-order 16-bit pieces of the address, and the 'd' s are the decimal values of the four low-order 8-bit pieces of the address (standard IPv4 representation).

Note:
A more extensive description of the standard representations of IPv6 addresses can be found in RFC 2373.

RETURN VALUE

The inet_ntop() function shall return a pointer to the buffer containing the text string if the conversion succeeds, and NULL otherwise, and set errno to indicate the error.

The inet_pton() function shall return 1 if the conversion succeeds, with the address pointed to by dst in network byte order. It shall return 0 if the input is not a valid IPv4 dotted-decimal string or a valid IPv6 address string, or -1 with errno set to [EAFNOSUPPORT] if the af argument is unknown.

ERRORS

The inet_ntop() and inet_pton() functions shall fail if:

EAFNOSUPPORT

The af argument is invalid.

ENOSPC
The size of the inet_ntop() result buffer is inadequate.

The following sections are informative.

EXAMPLES

None.

APPLICATION USAGE

None.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

The Base Definitions volume of IEEE Std 1003.1-2001, <arpa/inet.h>

COPYRIGHT

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .


random(4)

RANDOM

Section: Linux Programmer's Manual (4)
Updated: 2003-10-25 Return to Main Contents

NAME

random, urandom - kernel random number source devices

DESCRIPTION

The character special files /dev/random and /dev/urandom (present since Linux 1.3.30) provide an interface to the kernel's random number generator. File /dev/random has major device number 1 and minor device number 8. File /dev/urandom has major device number 1 and minor device number 9.

The random number generator gathers environmental noise from device drivers and other sources into an entropy pool. The generator also keeps an estimate of the number of bits of noise in the entropy pool. From this entropy pool random numbers are created.

When read, the /dev/random device will only return random bytes within the estimated number of bits of noise in the entropy pool. /dev/random should be suitable for uses that need very high quality randomness such as one-time pad or key generation. When the entropy pool is empty, reads from /dev/random will block until additional environmental noise is gathered.

A read from the /dev/urandom device will not block waiting for more entropy. As a result, if there is not sufficient entropy in the entropy pool, the returned values are theoretically vulnerable to a cryptographic attack on the algorithms used by the driver. Knowledge of how to do this is not available in the current non-classified literature, but it is theoretically possible that such an attack may exist. If this is a concern in your application, use /dev/random instead.

CONFIGURING

If your system does not have /dev/random and /dev/urandom created already, they can be created with the following commands:

    mknod -m 644 /dev/random c 1 8
    mknod -m 644 /dev/urandom c 1 9
    chown root:root /dev/random /dev/urandom

When a Linux system starts up without much operator interaction, the entropy pool may be in a fairly predictable state. This reduces the actual amount of noise in the entropy pool below the estimate. In order to counteract this effect, it helps to carry entropy pool information across shut-downs and start-ups. To do this, add the following lines to an appropriate script which is run during the Linux system start-up sequence:

    echo "Initializing random number generator..."
    random_seed=/var/run/random-seed
    # Carry a random seed from start-up to start-up
    # Load and then save the whole entropy pool
    if [ -f $random_seed ]; then
        cat $random_seed >/dev/urandom
    else
        touch $random_seed
    fi
    chmod 600 $random_seed
    poolfile=/proc/sys/kernel/random/poolsize
    [ -r $poolfile ] && bytes=`cat $poolfile` || bytes=512
    dd if=/dev/urandom of=$random_seed count=1 bs=$bytes

Also, add the following lines in an appropriate script which is run during the Linux system shutdown:

    # Carry a random seed from shut-down to start-up
    # Save the whole entropy pool
    echo "Saving random seed..."
    random_seed=/var/run/random-seed
    touch $random_seed
    chmod 600 $random_seed
    poolfile=/proc/sys/kernel/random/poolsize
    [ -r $poolfile ] && bytes=`cat $poolfile` || bytes=512
    dd if=/dev/urandom of=$random_seed count=1 bs=$bytes

PROC INTERFACE

The files in the directory /proc/sys/kernel/random (present since 2.3.16) provide an additional interface to the /dev/random device.

The read-only file entropy_avail gives the available entropy. Normally, this will be 4096 (bits), a full entropy pool.

The file poolsize gives the size of the entropy pool. Normally, this will be 512 (bytes). It can be changed to any value for which an algorithm is available. Currently the choices are 32, 64, 128, 256, 512, 1024, 2048.

The file read_wakeup_threshold contains the number of bits of entropy required for waking up processes that sleep waiting for entropy from /dev/random. The default is 64. The file write_wakeup_threshold contains the number of bits of entropy below which we wake up processes that do a select(2) or poll(2) for write access to /dev/random. These values can be changed by writing to the files.

The read-only files uuid and boot_id contain random strings like 6fd5a44b-35f4-4ad4-a9b9-6b9be13e1fe9. The former is generated afresh for each read, the latter was generated once.

FILES

/dev/random
/dev/urandom

SEE ALSO

mknod (1)
RFC 1750, "Randomness Recommendations for Security"


zero (4)

 Continue to this page.


st(4)

ST

Section: Linux Programmer's Manual (4)
Updated: 2005-03-13 Return to Main Contents

NAME

st - SCSI tape device

SYNOPSIS

#include <sys/mtio.h>

int ioctl(int fd, int request [, (void *)arg3]);
int ioctl(int fd, MTIOCTOP, (struct mtop *)mt_cmd);
int ioctl(int fd, MTIOCGET, (struct mtget *)mt_status);
int ioctl(int fd, MTIOCPOS, (struct mtpos *)mt_pos);

DESCRIPTION

The st driver provides the interface to a variety of SCSI tape devices. Currently, the driver takes control of all detected devices of type "sequential-access." The st driver uses major device number 9.

Each device uses eight minor device numbers. The lowermost five bits in the minor numbers are assigned sequentially in the order of detection. In the 2.6 kernel, the bits above the eight lowermost bits are concatenated to the five lowermost bits to form the tape number. The minor numbers can be grouped into two sets of four numbers: the principal (auto-rewind) minor device numbers, n, and the "no-rewind" device numbers, (n+ 128). Devices opened using the principal device number will be sent a REWIND command when they are closed. Devices opened using the "no-rewind" device number will not. (Note that using an auto-rewind device for positioning the tape with, for instance, mt does not lead to the desired result: the tape is rewound after the mt command and the next command starts from the beginning of the tape).

Within each group, four minor numbers are available to define devices with different characteristics (block size, compression, density, etc.) When the system starts up, only the first device is available. The other three are activated when the default characteristics are defined (see below). (By changing compile-time constants, it is possible to change the balance between the maximum number of tape drives and the number of minor numbers for each drive. The default allocation allows control of 32 tape drives. For instance, it is possible to control up to 64 tape drives with two minor numbers for different options.)

Devices are typically created by:

mknod -m 666 /dev/st0 c 9 0
mknod -m 666 /dev/st0l c 9 32
mknod -m 666 /dev/st0m c 9 64
mknod -m 666 /dev/st0a c 9 96
mknod -m 666 /dev/nst0 c 9 128
mknod -m 666 /dev/nst0l c 9 160
mknod -m 666 /dev/nst0m c 9 192
mknod -m 666 /dev/nst0a c 9 224

There is no corresponding block device.

The driver uses an internal buffer that has to be large enough to hold at least one tape block. In kernels before 2.1.121, the buffer is allocated as one contiguous block. This limits the block size to the largest contiguous block of memory the kernel allocator can provide. The limit is currently 128 kB for 32-bit architectures and 256 kB for 64-bit architectures. In newer kernels the driver allocates the buffer in several parts if necessary. By default, the maximum number of parts is 16. This means that the maximum block size is very large (2 MB if allocation of 16 blocks of 128 kB succeeds).

The driver's internal buffer size is determined by a compile-time constant which can be overridden with a kernel startup option. In addition to this, the driver tries to allocate a larger temporary buffer at run-time if necessary. However, run-time allocation of large contiguous blocks of memory may fail and it is advisable not to rely too much on dynamic buffer allocation with kernels older than 2.1.121 (this applies also to demand-loading the driver with kerneld or kmod).

The driver does not specifically support any tape drive brand or model. After system start-up the tape device options are defined by the drive firmware. For example, if the drive firmware selects fixed-block mode, the tape device uses fixed-block mode. The options can be changed with explicit ioctl(2) calls and remain in effect when the device is closed and reopened. Setting the options affects both the auto-rewind and the non-rewind device.

Different options can be specified for the different devices within the subgroup of four. The options take effect when the device is opened. For example, the system administrator can define one device that writes in fixed-block mode with a certain block size, and one which writes in variable-block mode (if the drive supports both modes).

The driver supports tape partitions if they are supported by the drive. (Note that the tape partitions have nothing to do with disk partitions. A partitioned tape can be seen as several logical tapes within one medium.) Partition support has to be enabled with an ioctl(2). The tape location is preserved within each partition across partition changes. The partition used for subsequent tape operations is selected with an ioctl(2). The partition switch is executed together with the next tape operation in order to avoid unnecessary tape movement. The maximum number of partitions on a tape is defined by a compile-time constant (originally four). The driver contains an ioctl(2) that can format a tape with either one or two partitions.

Device /dev/tape is usually created as a hard or soft link to the default tape device on the system.

Starting from kernel 2.6.2, the driver exports in the sysfs directory /sys/class/scsi_tape the attached devices and some parameters assigned to the devices.

Data Transfer

The driver supports operation in both fixed-block mode and variable-block mode (if supported by the drive). In fixed-block mode the drive writes blocks of the specified size and the block size is not dependent on the byte counts of the write system calls. In variable-block mode one tape block is written for each write call and the byte count determines the size of the corresponding tape block. Note that the blocks on the tape don't contain any information about the writing mode: when reading, the only important thing is to use commands that accept the block sizes on the tape.

In variable-block mode the read byte count does not have to match the tape block size exactly. If the byte count is larger than the next block on tape, the driver returns the data and the function returns the actual block size. If the block size is larger than the byte count, the requested amount of data from the start of the block is returned and the rest of the block is discarded.

In fixed-block mode the read byte counts can be arbitrary if buffering is enabled, or a multiple of the tape block size if buffering is disabled. Kernels before 2.1.121 allow writes with arbitrary byte count if buffering is enabled. In all other cases (kernel before 2.1.121 with buffering disabled or newer kernel) the write byte count must be a multiple of the tape block size.

In the 2.6 kernel, the driver tries to use direct transfers between the user buffer and the device. If this is not possible, the driver's internal buffer is used. The reasons for not using direct transfers include improper alignment of the user buffer (default is 512 bytes but this can be changed by the HBA driver), one of more pages of the user buffer not reachable by the SCSI adapter, etc.

A filemark is automatically written to tape if the last tape operation before close was a write.

When a filemark is encountered while reading, the following happens. If there are data remaining in the buffer when the filemark is found, the buffered data is returned. The next read returns zero bytes. The following read returns data from the next file. The end of recorded data is signaled by returning zero bytes for two consecutive read calls. The third read returns an error.

Ioctls

The driver supports three ioctl(2) requests. Requests not recognized by the st driver are passed to the SCSI driver. The definitions below are from /usr/include/linux/mtio.h:

MTIOCTOP --- Perform a tape operation

This request takes an argument of type (struct mtop *). Not all drives support all operations. The driver returns an EIO error if the drive rejects an operation.

/* Structure for MTIOCTOP - mag tape op command: */
struct mtop {
    short   mt_op;       /* operations defined below */
    int     mt_count;    /* how many of them */
};

Magnetic Tape operations for normal tape use:

MTBSF
Backward space over mt_count filemarks.
MTBSFM
Backward space over mt_count filemarks. Reposition the tape to the EOT side of the last filemark.
MTBSR
Backward space over mt_count records (tape blocks).
MTBSS
Backward space over mt_count setmarks.
MTCOMPRESSION
Enable compression of tape data within the drive if mt_count is non-zero and disable compression if mt_count is zero. This command uses the MODE page 15 supported by most DATs.
MTEOM
Go to the end of the recorded media (for appending files).
MTERASE
Erase tape. With 2.6 kernel, short erase (mark tape empty) is performed if the argument is zero. Otherwise long erase (erase all) is done.
MTFSF
Forward space over mt_count filemarks.
MTFSFM
Forward space over mt_count filemarks. Reposition the tape to the BOT side of the last filemark.
MTFSR
Forward space over mt_count records (tape blocks).
MTFSS
Forward space over mt_count setmarks.
MTLOAD
Execute the SCSI load command. A special case is available for some HP autoloaders. If mt_count is the constant MT_ST_HPLOADER_OFFSET plus a number, the number is sent to the drive to control the autoloader.
MTLOCK
Lock the tape drive door.
MTMKPART
Format the tape into one or two partitions. If mt_count is non-zero, it gives the size of the first partition and the second partition contains the rest of the tape. If mt_count is zero, the tape is formatted into one partition. This command is not allowed for a drive unless the partition support is enabled for the drive (see MT_ST_CAN_PARTITIONS below).
MTNOP
No op --- flushes the driver's buffer as a side effect. Should be used before reading status with MTIOCGET.
MTOFFL
Rewind and put the drive off line.
MTRESET
Reset drive.
MTRETEN
Re-tension tape.
MTREW
Rewind.
MTSEEK
Seek to the tape block number specified in mt_count. This operation requires either a SCSI-2 drive that supports the LOCATE command (device-specific address) or a Tandberg-compatible SCSI-1 drive (Tandberg, Archive Viper, Wangtek, ... ). The block number should be one that was previously returned by MTIOCPOS if device-specific addresses are used.
MTSETBLK
Set the drive's block length to the value specified in mt_count. A block length of zero sets the drive to variable block size mode.
MTSETDENSITY
Set the tape density to the code in mt_count. The density codes supported by a drive can be found from the drive documentation.
MTSETPART
The active partition is switched to mt_count. The partitions are numbered from zero. This command is not allowed for a drive unless the partition support is enabled for the drive (see MT_ST_CAN_PARTITIONS below).
MTUNLOAD
Execute the SCSI unload command (does not eject the tape).
MTUNLOCK
Unlock the tape drive door.
MTWEOF
Write mt_count filemarks.
MTWSM
Write mt_count setmarks.

Magnetic Tape operations for setting of device options (by the superuser):

MTSETDRVBUFFER
Set various drive and driver options according to bits encoded in mt_count. These consist of the drive's buffering mode, a set of Boolean driver options, the buffer write threshold, defaults for the block size and density, and timeouts (only in kernels >= 2.1). A single operation can affect only one item in the list above (the Booleans counted as one item.)
A value having zeros in the high-order 4 bits will be used to set the drive's buffering mode. The buffering modes are:
0
The drive will not report GOOD status on write commands until the data blocks are actually written to the medium.
1
The drive may report GOOD status on write commands as soon as all the data has been transferred to the drive's internal buffer.
2
The drive may report GOOD status on write commands as soon as (a) all the data has been transferred to the drive's internal buffer, and (b) all buffered data from different initiators has been successfully written to the medium.
To control the write threshold the value in mt_count must include the constant MT_ST_WRITE_THRESHOLD logically ORed with a block count in the low 28 bits. The block count refers to 1024-byte blocks, not the physical block size on the tape. The threshold cannot exceed the driver's internal buffer size (see DESCRIPTION, above).
To set and clear the Boolean options the value in mt_count must include one of the constants MT_ST_BOOLEANS, MT_ST_SETBOOLEANS, MT_ST_CLEARBOOLEANS, or MT_ST_DEFBOOLEANS logically or'ed with whatever combination of the following options is desired. Using MT_ST_BOOLEANS the options can be set to the values defined in the corresponding bits. With MT_ST_SETBOOLEANS the options can be selectively set and with MT_ST_DEFBOOLEANS selectively cleared.
The default options for a tape device are set with MT_ST_DEFBOOLEANS. A non-active tape device (e.g., device with minor 32 or 160) is activated when the default options for it are defined the first time. An activated device inherits from the device activated at start-up the options not set explicitly.
The Boolean options are:
MT_ST_BUFFER_WRITES (Default: true)
Buffer all write operations in fixed-block mode. If this option is false and the drive uses a fixed block size, then all write operations must be for a multiple of the block size. This option must be set false to write reliable multi-volume archives.
MT_ST_ASYNC_WRITES (Default: true)
When this option is true, write operations return immediately without waiting for the data to be transferred to the drive if the data fits into the driver's buffer. The write threshold determines how full the buffer must be before a new SCSI write command is issued. Any errors reported by the drive will be held until the next operation. This option must be set false to write reliable multi-volume archives.
MT_ST_READ_AHEAD (Default: true)
This option causes the driver to provide read buffering and read-ahead in fixed-block mode. If this option is false and the drive uses a fixed block size, then all read operations must be for a multiple of the block size.
MT_ST_TWO_FM (Default: false)
This option modifies the driver behavior when a file is closed. The normal action is to write a single filemark. If the option is true the driver will write two filemarks and backspace over the second one.
Note: This option should not be set true for QIC tape drives since they are unable to overwrite a filemark. These drives detect the end of recorded data by testing for blank tape rather than two consecutive filemarks. Most other current drives also detect the end of recorded data and using two filemarks is usually necessary only when interchanging tapes with some other systems.

MT_ST_DEBUGGING (Default: false)
This option turns on various debugging messages from the driver (effective only if the driver was compiled with DEBUG defined non-zero).
MT_ST_FAST_EOM (Default: false)
This option causes the MTEOM operation to be sent directly to the drive, potentially speeding up the operation but causing the driver to lose track of the current file number normally returned by the MTIOCGET request. If MT_ST_FAST_EOM is false the driver will respond to an MTEOM request by forward spacing over files.
MT_ST_AUTO_LOCK (Default: false)
When this option is true, the drive door is locked when the device is opened and unlocked when it is closed.
MT_ST_DEF_WRITES (Default: false)
The tape options (block size, mode, compression, etc.) may change when changing from one device linked to a drive to another device linked to the same drive depending on how the devices are defined. This option defines when the changes are enforced by the driver using SCSI-commands and when the drives auto-detection capabilities are relied upon. If this option is false, the driver sends the SCSI-commands immediately when the device is changed. If the option is true, the SCSI-commands are not sent until a write is requested. In this case the drive firmware is allowed to detect the tape structure when reading and the SCSI-commands are used only to make sure that a tape is written according to the correct specification.
MT_ST_CAN_BSR (Default: false)
When read-ahead is used, the tape must sometimes be spaced backward to the correct position when the device is closed and the SCSI command to space backwards over records is used for this purpose. Some older drives can't process this command reliably and this option can be used to instruct the driver not to use the command. The end result is that, with read-ahead and fixed-block mode, the tape may not be correctly positioned within a file when the device is closed. With 2.6 kernel, the default is true for drives supporting SCSI-3.
MT_ST_NO_BLKLIMS (Default: false)
Some drives don't accept the READ BLOCK LIMITS SCSI command. If this is used, the driver does not use the command. The drawback is that the driver can't check before sending commands if the selected block size is acceptable to the drive.
MT_ST_CAN_PARTITIONS (Default: false)
This option enables support for several partitions within a tape. The option applies to all devices linked to a drive.
MT_ST_SCSI2LOGICAL (Default: false)
This option instructs the driver to use the logical block addresses defined in the SCSI-2 standard when performing the seek and tell operations (both with MTSEEK and MTIOCPOS commands and when changing tape partition). Otherwise the device-specific addresses are used. It is highly advisable to set this option if the drive supports the logical addresses because they count also filemarks. There are some drives that only support the logical block addresses.
MT_ST_SYSV (Default: false)
When this option is enabled, the tape devices use the SystemV semantics. Otherwise the BSD semantics are used. The most important difference between the semantics is what happens when a device used for reading is closed: in System V semantics the tape is spaced forward past the next filemark if this has not happened while using the device. In BSD semantics the tape position is not changed.
MT_NO_WAIT (Default: false)
Enables immediate mode (i.e., don't wait for the command to finish) for some commands (e.g., rewind).
EXAMPLE

struct mtop mt_cmd;
mt_cmd.mt_op = MTSETDRVBUFFER;
mt_cmd.mt_count = MT_ST_BOOLEANS |
        MT_ST_BUFFER_WRITES |
        MT_ST_ASYNC_WRITES;
ioctl(fd, MTIOCTOP, &mt_cmd);
The default block size for a device can be set with MT_ST_DEF_BLKSIZE and the default density code can be set with MT_ST_DEFDENSITY. The values for the parameters are or'ed with the operation code.
With kernels 2.1.x and later, the timeout values can be set with the subcommand MT_ST_SET_TIMEOUT ORed with the timeout in seconds. The long timeout (used for rewinds and other commands that may take a long time) can be set with MT_ST_SET_LONG_TIMEOUT. The kernel defaults are very long to make sure that a successful command is not timed out with any drive. Because of this the driver may seem stuck even if it is only waiting for the timeout. These commands can be used to set more practical values for a specific drive. The timeouts set for one device apply for all devices linked to the same drive.
Starting from kernels 2.4.19 and 2.5.43, the driver supports a status bit which indicates whether the drive requests cleaning. The method used by the drive to return cleaning information is set using the MT_ST_SEL_CLN subcommand. If the value is zero, the cleaning bit is always zero. If the value is one, the TapeAlert data defined in the SCSI-3 standard is used (not yet implemented). Values 2-17 are reserved. If the lowest eight bits are >= 18, bits from the extended sense data are used. The bits 9-16 specify a mask to select the bits to look at and the bits 17-23 specify the bit pattern to look for. If the bit pattern is zero, one or more bits under the mask indicate the cleaning request. If the pattern is non-zero, the pattern must match the masked sense data byte.

MTIOCGET --- Get status

This request takes an argument of type (struct mtget *).

/* structure for MTIOCGET - mag tape get status command */
struct mtget {
    long     mt_type;
    long     mt_resid;
    /* the following registers are device dependent */
    long     mt_dsreg;
    long     mt_gstat;
    long     mt_erreg;
    /* The next two fields are not always used */
    daddr_t  mt_fileno;
    daddr_t  mt_blkno;
};
mt_type
The header file defines many values for mt_type, but the current driver reports only the generic types MT_ISSCSI1 (Generic SCSI-1 tape) and MT_ISSCSI2 (Generic SCSI-2 tape).
mt_resid
contains the current tape partition number.
mt_dsreg
reports the drive's current settings for block size (in the low 24 bits) and density (in the high 8 bits). These fields are defined by MT_ST_BLKSIZE_SHIFT, MT_ST_BLKSIZE_MASK, MT_ST_DENSITY_SHIFT, and MT_ST_DENSITY_MASK.
mt_gstat
reports generic (device independent) status information. The header file defines macros for testing these status bits:
GMT_EOF(x):
The tape is positioned just after a filemark (always false after an MTSEEK operation).
GMT_BOT(x):
The tape is positioned at the beginning of the first file (always false after an MTSEEK operation).
GMT_EOT(x):
A tape operation has reached the physical End Of Tape.
GMT_SM(x):
The tape is currently positioned at a setmark (always false after an MTSEEK operation).
GMT_EOD(x):
The tape is positioned at the end of recorded data.
GMT_WR_PROT(x):
The drive is write-protected. For some drives this can also mean that the drive does not support writing on the current medium type.
GMT_ONLINE(x):
The last open(2) found the drive with a tape in place and ready for operation.
GMT_D_6250(x), GMT_D_1600(x), GMT_D_800(x):
This "generic" status information reports the current density setting for 9-track ½" tape drives only.
GMT_DR_OPEN(x):
The drive does not have a tape in place.
GMT_IM_REP_EN(x):
Immediate report mode. This bit is set if there are no guarantees that the data has been physically written to the tape when the write call returns. It is set zero only when the driver does not buffer data and the drive is set not to buffer data.
GMT_CLN(x):
The drive has requested cleaning. Implemented in kernels >= 2.4.19 and 2.5.43.
mt_erreg
The only field defined in mt_erreg is the recovered error count in the low 16 bits (as defined by MT_ST_SOFTERR_SHIFT and MT_ST_SOFTERR_MASK). Due to inconsistencies in the way drives report recovered errors, this count is often not maintained (most drives do not by default report soft errors but this can be changed with a SCSI MODE SELECT command).
mt_fileno
reports the current file number (zero-based). This value is set to -1 when the file number is unknown (e.g., after MTBSS or MTSEEK).
mt_blkno
reports the block number (zero-based) within the current file. This value is set to -1 when the block number is unknown (e.g., after MTBSF, MTBSS, or MTSEEK).

MTIOCPOS --- Get tape position

This request takes an argument of type (struct mtpos *) and reports the drive's notion of the current tape block number, which is not the same as mt_blkno returned by MTIOCGET. This drive must be a SCSI-2 drive that supports the READ POSITION command (device-specific address) or a Tandberg-compatible SCSI-1 drive (Tandberg, Archive Viper, Wangtek, ... ).

/* structure for MTIOCPOS - mag tape get position command */
struct mtpos {
    long mt_blkno;    /* current block number */
};

RETURN VALUE

EIO
The requested operation could not be completed.
ENOSPC
A write operation could not be completed because the tape reached end-of-medium.
ENOMEM
The byte count in read(2) is smaller than the next physical block on the tape. (Before 2.2.18 and 2.4.0-test6 the extra bytes have been silently ignored.)
EACCES
An attempt was made to write or erase a write-protected tape. (This error is not detected during open(2).)
EFAULT
The command parameters point to memory not belonging to the calling process.
ENXIO
During opening, the tape device does not exist.
EBUSY
The device is already in use or the driver was unable to allocate a buffer.
EOVERFLOW
An attempt was made to read or write a variable-length block that is larger than the driver's internal buffer.
EINVAL
An ioctl(2) had an illegal argument, or a requested block size was illegal.
ENOSYS
Unknown ioctl(2).
EROFS
Open is attempted with O_WRONLY or O_RDWR when the tape in the drive is write-protected.

FILES

/dev/st* : the auto-rewind SCSI tape devices
/dev/nst* : the non-rewind SCSI tape devices

NOTES

1. When exchanging data between systems, both systems have to agree on the physical tape block size. The parameters of a drive after startup are often not the ones most operating systems use with these devices. Most systems use drives in variable-block mode if the drive supports that mode. This applies to most modern drives, including DATs, 8mm helical scan drives, DLTs, etc. It may be advisable to use these drives in variable-block mode also in Linux (i.e., use MTSETBLK or MTSETDEFBLK at system startup to set the mode), at least when exchanging data with a foreign system. The drawback of this is that a fairly large tape block size has to be used to get acceptable data transfer rates on the SCSI bus.

2. Many programs (e.g., tar) allow the user to specify the blocking factor on the command line. Note that this determines the physical block size on tape only in variable-block mode.

3. In order to use SCSI tape drives, the basic SCSI driver, a SCSI-adapter driver and the SCSI tape driver must be either configured into the kernel or loaded as modules. If the SCSI-tape driver is not present, the drive is recognized but the tape support described in this page is not available.

4. The driver writes error messages to the console/log. The SENSE codes written into some messages are automatically translated to text if verbose SCSI messages are enabled in kernel configuration.

5. The driver's internal buffering allows good throughput in fixed-block mode also with small read(2) and write(2) byte counts. With direct transfers this is not possible and may cause a surprise when moving to the 2.6 kernel. The solution is to tell the software to use larger transfers (often telling it to use larger blocks). If this is not possible, direct transfers can be disabled.

SEE ALSO

mt(1)

The file README.st or st.txt (kernel >= 2.6) in the kernel sources contains the most recent information about the driver and its configuration possibilities.


vcs(4)

VCS

Section: Linux Programmer's Manual (4)
Updated: 1995-02-19 Return to Main Contents

NAME

vcs, vcsa - virtual console memory

DESCRIPTION

/dev/vcs0 is a character device with major number 7 and minor number 0, usually of mode 0644 and owner root.tty. It refers to the memory of the currently displayed virtual console terminal.

/dev/vcs[1-63] are character devices for virtual console terminals, they have major number 7 and minor number 1 to 63, usually mode 0644 and owner root.tty. /dev/vcsa[0-63] are the same, but including attributes, and prefixed with four bytes giving the screen dimensions and cursor position: lines, columns, x, y. (x = y = 0 at the top left corner of the screen.)

These replace the screendump ioctls of console(4), so the system administrator can control access using file system permissions.

The devices for the first eight virtual consoles may be created by:

    for x in 0 1 2 3 4 5 6 7 8; do
        mknod -m 644 /dev/vcs$x c 7 $x;
        mknod -m 644 /dev/vcsa$x c 7 $[$x+128];
    done
    chown root:tty /dev/vcs*

No ioctl(2) requests are supported.

FILES

/dev/vcs[0-63]
/dev/vcsa[0-63]

VERSIONS

Introduced with version 1.1.92 of the Linux kernel.

EXAMPLE

You may do a screendump on vt3 by switching to vt1 and typing cat /dev/vcs3 >foo. Note that the output does not contain newline characters, so some processing may be required, like in fold -w 81 /dev/vcs3 | lpr or (horrors) setterm -dump 3 -file /proc/self/fd/1.

The /dev/vcsa0 device is used for Braille support.

This program displays the character and screen attributes under the cursor of the second virtual console, then changes the background color there:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

int
main(void)
{
    int fd;
    char *device = "/dev/vcsa2";
    struct {unsigned char lines, cols, x, y;} scrn;
    char ch, attrib;

    fd = open(device, O_RDWR);
    if (fd < 0) {
        perror(device);
        exit(EXIT_FAILURE);
    }
    (void) read(fd, &scrn, 4);
    (void) lseek(fd, 4 + 2*(scrn.y*scrn.cols + scrn.x), 0);
    (void) read(fd, &ch, 1);
    (void) read(fd, &attrib, 1);
    printf("ch='%c' attrib=0x%02x\n", ch, attrib);
    attrib ^= 0x10;
    (void) lseek(fd, -1, 1);
    (void) write(fd, &attrib, 1);
    exit(EXIT_SUCCESS);
}

SEE ALSO

gpm(8), console(4), tty(4), ttyS(4)


vcsa (4)

 Continue to this page.


fifo (4)

 Continue to this page.


intro(4)

INTRO

Section: Linux Programmer's Manual (4)
Updated: 1993-07-24 Return to Main Contents

NAME

intro - Introduction to special files

DESCRIPTION

This chapter describes special files.

FILES

/dev/* --- device files

Authors and Copyright Conditions

Look at the header of the manual page for the author(s) and copyright conditions. Note that these can be different from page to page!

SEE ALSO

standards(7)


lp(4)

LP

Section: Linux Programmer's Manual (4)
Updated: 1995-01-15 Return to Main Contents

NAME

lp - line printer devices

SYNOPSIS

#include <linux/lp.h>

CONFIGURATION

lp[0-2] are character devices for the parallel line printers; they have major number 6 and minor number 0-2. The minor numbers correspond to the printer port base addresses 0x03bc, 0x0378 and 0x0278. Usually they have mode 220 and are owned by root and group lp. You can use printer ports either with polling or with interrupts. Interrupts are recommended when high traffic is expected, for example, for laser printers. For usual dot matrix printers polling will usually be enough. The default is polling.

DESCRIPTION

The following ioctl(2) calls are supported:
int ioctl(int fd, LPTIME, int arg)
Sets the amount of time that the driver sleeps before rechecking the printer when the printer's buffer appears to be filled to arg. If you have a fast printer, decrease this number; if you have a slow printer then increase it. This is in hundredths of a second, the default 2 being 0.02 seconds. It only influences the polling driver.
int ioctl(int fd, LPCHAR, int arg)
Sets the maximum number of busy-wait iterations which the polling driver does while waiting for the printer to get ready for receiving a character to arg. If printing is too slow, increase this number; if the system gets too slow, decrease this number. The default is 1000. It only influences the polling driver.
int ioctl(int fd, LPABORT, int arg)
If arg is 0, the printer driver will retry on errors, otherwise it will abort. The default is 0.
int ioctl(int fd, LPABORTOPEN, int arg)
If arg is 0, open(2) will be aborted on error, otherwise error will be ignored. The default is to ignore it.
int ioctl(int fd, LPCAREFUL, int arg)
If arg is 0, then the out-of-paper, offline and error signals are required to be false on all writes, otherwise they are ignored. The default is to ignore them.
int ioctl(int fd, LPWAIT, int arg)
Sets the number of busy waiting iterations to wait before strobing the printer to accept a just-written character, and the number of iterations to wait before turning the strobe off again, to arg. The specification says this time should be 0.5 microseconds, but experience has shown the delay caused by the code is already enough. For that reason, the default value is 0. This is used for both the polling and the interrupt driver.
int ioctl(int fd, LPSETIRQ, int arg)
This ioctl(2) requires superuser privileges. It takes an int containing the new IRQ as argument. As a side effect, the printer will be reset. When arg is 0, the polling driver will be used, which is also default.
int ioctl(int fd, LPGETIRQ, int *arg)
Stores the currently used IRQ in arg.
int ioctl(int fd, LPGETSTATUS, int *arg)
Stores the value of the status port in arg. The bits have the following meaning:
LP_PBUSY inverted busy input, active high
LP_PACK unchanged acknowledge input, active low
LP_POUTPA unchanged out-of-paper input, active high
LP_PSELECD unchanged selected input, active high
LP_PERRORP unchanged error input, active low

Refer to your printer manual for the meaning of the signals. Note that undocumented bits may also be set, depending on your printer.

int ioctl(int fd, LPRESET)
Resets the printer. No argument is used.

FILES

/dev/lp*

SEE ALSO

chmod(1), chown(1), mknod(1), lpcntl(8), tunelp(8)


mem(4)

MEM

Section: Linux Programmer's Manual (4)
Updated: 1992-11-21 Return to Main Contents

NAME

mem, kmem, port - system memory, kernel memory and system ports

DESCRIPTION

mem is a character device file that is an image of the main memory of the computer. It may be used, for example, to examine (and even patch) the system.

Byte addresses in mem are interpreted as physical memory addresses. References to non-existent locations cause errors to be returned.

Examining and patching is likely to lead to unexpected results when read-only or write-only bits are present.

It is typically created by:

mknod -m 660 /dev/mem c 1 1
chown root:kmem /dev/mem

The file kmem is the same as mem, except that the kernel virtual memory rather than physical memory is accessed.

It is typically created by:

mknod -m 640 /dev/kmem c 1 2
chown root:kmem /dev/kmem

port is similar to mem, but the I/O ports are accessed.

It is typically created by:

mknod -m 660 /dev/port c 1 4
chown root:mem /dev/port

FILES

/dev/mem
/dev/kmem
/dev/port

SEE ALSO

chown(1), mknod(1), ioperm(2)


tty(4)

TTY

Section: Linux Programmer's Manual (4)
Updated: 2003-04-07 Return to Main Contents

NAME

tty - controlling terminal

DESCRIPTION

The file /dev/tty is a character file with major number 5 and minor number 0, usually of mode 0666 and owner.group root.tty. It is a synonym for the controlling terminal of a process, if any.

In addition to the ioctl(2) requests supported by the device that tty refers to, the ioctl(2) request TIOCNOTTY is supported.

TIOCNOTTY

Detach the current process from its controlling terminal.

If the process is the session leader, then SIGHUP and SIGCONT signals are sent to the foreground process group and all processes in the current session lose their controlling tty.

This ioctl(2) call only works on file descriptors connected to /dev/tty. It is used by daemon processes when they are invoked by a user at a terminal. The process attempts to open /dev/tty. If the open succeeds, it detaches itself from the terminal by using TIOCNOTTY, while if the open fails, it is obviously not attached to a terminal and does not need to detach itself.

FILES

/dev/tty

SEE ALSO

chown(1), mknod(1), ioctl(2), termios(3), console(4), ttyS(4), mingetty(8)


fd(4)

FD

Section: Linux Programmer's Manual (4)
Updated: 1995-01-29 Return to Main Contents

NAME

fd - floppy disk device

CONFIGURATION

Floppy drives are block devices with major number 2. Typically they are owned by root.floppy (i.e., user root, group floppy) and have either mode 0660 (access checking via group membership) or mode 0666 (everybody has access). The minor numbers encode the device type, drive number, and controller number. For each device type (that is, combination of density and track count) there is a base minor number. To this base number, add the drive's number on its controller and 128 if the drive is on the secondary controller. In the following device tables, n represents the drive number.

Warning: If you use formats with more tracks than supported by your drive, you may cause it mechanical damage. Trying once if more tracks than the usual 40/80 are supported should not damage it, but no warranty is given for that. Don't create device entries for those formats to prevent their usage if you are not sure.

Drive independent device files which automatically detect the media format and capacity:
Name | Base minor #
fd n | 0

5.25 inch double density device files:
Name | Capac. | Cyl. | Sect. | Heads | Base minor #
fd n d360 | 360K | 40 | 9 | 2 | 4

5.25 inch high density device files:
Name | Capac. | Cyl. | Sect. | Heads | Base minor #
fd n h360 | 360K | 40 | 9 | 2 | 20
fd n h410 | 410K | 41 | 10 | 2 | 48
fd n h420 | 420K | 42 | 10 | 2 | 64
fd n h720 | 720K | 80 | 9 | 2 | 24
fd n h880 | 880K | 80 | 11 | 2 | 80
fd n h1200 | 1200K | 80 | 15 | 2 | 8
fd n h1440 | 1440K | 80 | 18 | 2 | 40
fd n h1476 | 1476K | 82 | 18 | 2 | 56
fd n h1494 | 1494K | 83 | 18 | 2 | 72
fd n h1600 | 1600K | 80 | 20 | 2 | 92

3.5 inch double density device files:
Name | Capac. | Cyl. | Sect. | Heads | Base minor #
fd n D360 | 360K | 80 | 9 | 1 | 12
fd n D720 | 720K | 80 | 9 | 2 | 16
fd n D800 | 800K | 80 | 10 | 2 | 120
fd n D1040 | 1040K | 80 | 13 | 2 | 84
fd n D1120 | 1120K | 80 | 14 | 2 | 88

3.5 inch high density device files:
Name | Capac. | Cyl. | Sect. | Heads | Base minor #
fd n H360 | 360K | 40 | 9 | 2 | 12
fd n H720 | 720K | 80 | 9 | 2 | 16
fd n H820 | 820K | 82 | 10 | 2 | 52
fd n H830 | 830K | 83 | 10 | 2 | 68
fd n H1440 | 1440K | 80 | 18 | 2 | 28
fd n H1600 | 1600K | 80 | 20 | 2 | 124
fd n H1680 | 1680K | 80 | 21 | 2 | 44
fd n H1722 | 1722K | 82 | 21 | 2 | 60
fd n H1743 | 1743K | 83 | 21 | 2 | 76
fd n H1760 | 1760K | 80 | 22 | 2 | 96
fd n H1840 | 1840K | 80 | 23 | 2 | 116
fd n H1920 | 1920K | 80 | 24 | 2 | 100

3.5 inch extra density device files:
Name | Capac. | Cyl. | Sect. | Heads | Base minor #
fd n E2880 | 2880K | 80 | 36 | 2 | 32
fd n CompaQ | 2880K | 80 | 36 | 2 | 36
fd n E3200 | 3200K | 80 | 40 | 2 | 104
fd n E3520 | 3520K | 80 | 44 | 2 | 108
fd n E3840 | 3840K | 80 | 48 | 2 | 112

DESCRIPTION

fd special files access the floppy disk drives in raw mode. The following ioctl(2) calls are supported by fd devices:
FDCLRPRM
clears the media information of a drive (geometry of disk in drive).
FDSETPRM
sets the media information of a drive. The media information will be lost when the media is changed.
FDDEFPRM
sets the media information of a drive (geometry of disk in drive). The media information will not be lost when the media is changed. This will disable autodetection. In order to re-enable autodetection, you have to issue an FDCLRPRM.
FDGETDRVTYP
returns the type of a drive (name parameter). For formats which work in several drive types, FDGETDRVTYP returns a name which is appropriate for the oldest drive type which supports this format.
FDFLUSH
invalidates the buffer cache for the given drive.
FDSETMAXERRS
sets the error thresholds for reporting errors, aborting the operation, recalibrating, resetting, and reading sector by sector.
FDSETMAXERRS
gets the current error thresholds.
FDGETDRVTYP
gets the internal name of the drive.
FDWERRORCLR
clears the write error statistics.
FDWERRORGET
reads the write error statistics. These include the total number of write errors, the location and disk of the first write error, and the location and disk of the last write error. Disks are identified by a generation number which is incremented at (almost) each disk change.
FDTWADDLE
Switch the drive motor off for a few microseconds. This might be needed in order to access a disk whose sectors are too close together.
FDSETDRVPRM
sets various drive parameters.
FDGETDRVPRM
reads these parameters back.
FDGETDRVSTAT
gets the cached drive state (disk changed, write protected et al.)
FDPOLLDRVSTAT
polls the drive and return its state.
FDGETFDCSTAT
gets the floppy controller state.
FDRESET
resets the floppy controller under certain conditions.
FDRAWCMD
sends a raw command to the floppy controller.

For more precise information, consult also the <linux/fd.h> and <linux/fdreg.h> include files, as well as the manual page for floppycontrol.

FILES

/dev/fd*

NOTES

The various formats allow to read and write many types of disks. However, if a floppy is formatted with a too small inter sector gap, performance may drop, up to needing a few seconds to access an entire track. To prevent this, use interleaved formats. It is not possible to read floppies which are formatted using GCR (group code recording), which is used by Apple II and Macintosh computers (800k disks). Reading floppies which are hard sectored (one hole per sector, with the index hole being a little skewed) is not supported. This used to be common with older 8 inch floppies.

SEE ALSO

chown(1), floppycontrol(1), getfdprm(1), mknod(1), superformat(1), mount(8), setfdprm(8)


mouse(4)

MOUSE

Section: Linux Programmer's Manual (4)
Updated: 1996-02-10 Return to Main Contents

NAME

mouse - serial mouse interface

CONFIG

Serial mice are connected to a serial RS232/V24 dialout line, see ttyS(4) for a description.

DESCRIPTION

Introduction

The pinout of the usual 9 pin plug as used for serial mice is:
pin | name | used for
2 | RX | Data
3 | TX | -12 V, Imax = 10 mA
4 | DTR | +12 V, Imax = 10 mA
7 | RTS | +12 V, Imax = 10 mA
5 | GND | Ground

This is the specification, in fact 9 V suffices with most mice.

The mouse driver can recognize a mouse by dropping RTS to low and raising it again. About 14 ms later the mouse will send 0x4D ('M') on the data line. After a further 63 ms, a Microsoft-compatible 3-button mouse will send 0x33 ('3').

The relative mouse movement is sent as dx (positive means right) and dy (positive means down). Various mice can operate at different speeds. To select speeds, cycle through the speeds 9600, 4800, 2400 and 1200 bit/s, each time writing the two characters from the table below and waiting 0.1 seconds. The following table shows available speeds and the strings that select them:

bit/s | string
9600 | *q
4800 | *p
2400 | *o
1200 | *n

The first byte of a data packet can be used to synchronization purposes.

Microsoft protocol

The Microsoft protocol uses 1 start bit, 7 data bits, no parity and one stop bit at the speed of 1200 bits/sec. Data is sent to RxD in 3-byte packets. The dx and dy movements are sent as two's-complement, lb (rb) are set when the left (right) button is pressed:
byte | d6 | d5 | d4 | d3 | d2 | d1 | d0
1 | 1 | lb | rb | dy7 | dy6 | dx7 | dx6
2 | 0 | dx5 | dx4 | dx3 | dx2 | dx1 | dx0
3 | 0 | dy5 | dy4 | dy3 | dy2 | dy1 | dy0

3-button Microsoft protocol

Original Microsoft mice only have two buttons. However, there are some three button mice which also use the Microsoft protocol. Pressing or releasing the middle button is reported by sending a packet with zero movement and no buttons pressed. (Thus, unlike for the other two buttons, the status of the middle button is not reported in each packet.)

Logitech protocol

Logitech serial 3-button mice use a different extension of the Microsoft protocol: when the middle button is up, the above 3-byte packet is sent. When the middle button is down a 4-byte packet is sent, where the 4th byte has value 0x20 (or at least has the 0x20 bit set). In particular, a press of the middle button is reported as 0,0,0,0x20 when no other buttons are down.

Mousesystems protocol

The Mousesystems protocol uses 1 start bit, 8 data bits, no parity and two stop bits at the speed of 1200 bits/sec. Data is sent to RxD in 5-byte packets. dx is sent as the sum of the two two's-complement values, dy is send as negated sum of the two two's-complement values. lb (mb, rb) are cleared when the left (middle, right) button is pressed:
byte | d7 | d6 | d5 | d4 | d3 | d2 | d1 | d0
1 | 1 | 0 | 0 | 0 | 0 | lb | mb | rb
2 | 0 | dxa6 | dxa5 | dxa4 | dxa3 | dxa2 | dxa1 | dxa0
3 | 0 | dya6 | dya5 | dya4 | dya3 | dya2 | dya1 | dya0
4 | 0 | dxb6 | dxb5 | dxb4 | dxb3 | dxb2 | dxb1 | dxb0
5 | 0 | dyb6 | dyb5 | dyb4 | dyb3 | dyb2 | dyb1 | dyb0

Bytes 4 and 5 describe the change that occurred since bytes 2 and 3 were transmitted.

Sun protocol

The Sun protocol is the 3-byte version of the above 5-byte Mousesystems protocol: the last two bytes are not sent.

MM protocol

The MM protocol uses 1 start bit, 8 data bits, odd parity and one stop bit at the speed of 1200 bits/sec. Data is sent to RxD in 3-byte packets. dx and dy are sent as single signed values, the sign bit indicating a negative value. lb (mb, rb) are set when the left (middle, right) button is pressed:
byte | d7 | d6 | d5 | d4 | d3 | d2 | d1 | d0
1 | 1 | 0 | 0 | dxs | dys | lb | mb | rb
2 | 0 | dx6 | dx5 | dx4 | dx3 | dx2 | dx1 | dx0
3 | 0 | dy6 | dy5 | dy4 | dy3 | dy2 | dy1 | dy0

FILES

/dev/mouse
A commonly used symlink pointing to a mouse device.

SEE ALSO

ttyS(4), gpm(8)


full(4)

FULL

Section: Linux Programmer's Manual (4)
Updated: 1997-08-02 Return to Main Contents

NAME

full - always full device

DESCRIPTION

File /dev/full has major device number 1 and minor device number 7.

Writes to the /dev/full device will fail with an ENOSPC error. This can be used to test how a program handles disk-full errors.

Reads from the /dev/full device will return \0 characters.

Seeks on /dev/full will always succeed.

CONFIGURING

If your system does not have /dev/full created already, it can be created with the following commands:

        mknod -m 666 /dev/full c 1 7
        chown root:root /dev/full

FILES

/dev/full

SEE ALSO

mknod(1), null(4), zero(4)


hd(4)

HD

Section: Linux Programmer's Manual (4)
Updated: 1992-12-17 Return to Main Contents

NAME

hd - MFM/IDE hard disk devices

DESCRIPTION

The hd* devices are block devices to access MFM/IDE hard disk drives in raw mode. The master drive on the primary IDE controller (major device number 3) is hda; the slave drive is hdb. The master drive of the second controller (major device number 22) is hdc and the slave hdd.

General IDE block device names have the form hd X, or hd XP, where X is a letter denoting the physical drive, and P is a number denoting the partition on that physical drive. The first form, hd X, is used to address the whole drive. Partition numbers are assigned in the order the partitions are discovered, and only non-empty, non-extended partitions get a number. However, partition numbers 1-4 are given to the four partitions described in the MBR (the `primary' partitions), regardless of whether they are unused or extended. Thus, the first logical partition will be hd X 5. Both DOS-type partitioning and BSD-disklabel partitioning are supported. You can have at most 63 partitions on an IDE disk.

For example, /dev/hda refers to all of the first IDE drive in the system; and /dev/hdb3 refers to the third DOS `primary' partition on the second one.

They are typically created by:

mknod -m 660 /dev/hda b 3 0
mknod -m 660 /dev/hda1 b 3 1
mknod -m 660 /dev/hda2 b 3 2
...
mknod -m 660 /dev/hda8 b 3 8
mknod -m 660 /dev/hdb b 3 64
mknod -m 660 /dev/hdb1 b 3 65
mknod -m 660 /dev/hdb2 b 3 66
...
mknod -m 660 /dev/hdb8 b 3 72
chown root:disk /dev/hd*

FILES

/dev/hd*

SEE ALSO

chown(1), mknod(1), sd(4), mount(8)


ttyS(4)

TTYS

Section: Linux Programmer's Manual (4)
Updated: 1992-12-19 Return to Main Contents

NAME

ttyS - serial terminal lines

DESCRIPTION

ttyS[0-3] are character devices for the serial terminal lines.

They are typically created by:

mknod -m 660 /dev/ttyS0 c 4 64 # base address 0x3f8
mknod -m 660 /dev/ttyS1 c 4 65 # base address 0x2f8
mknod -m 660 /dev/ttyS2 c 4 66 # base address 0x3e8
mknod -m 660 /dev/ttyS3 c 4 67 # base address 0x2e8
chown root:tty /dev/ttyS[0-3]

FILES

/dev/ttyS[0-3]

SEE ALSO

chown(1), mknod(1), tty(4), mingetty(8), setserial(8)


dsp56k(4)

DSP56K

Section: Linux Programmer's Manual (4)
Updated: 2000-03-01 Return to Main Contents

NAME

dsp56k - DSP56001 interface device

SYNOPSIS

#include <asm/dsp56k.h>

ssize_t read(int fd, void *data, size_t length);
ssize_t write(int fd, void *data, size_t length);
int ioctl(int fd, DSP56K_UPLOAD, struct dsp56k_upload *program);
int ioctl(int fd, DSP56K_SET_TX_WSIZE, int wsize);
int ioctl(int fd, DSP56K_SET_RX_WSIZE, int wsize);
int ioctl(int fd, DSP56K_HOST_FLAGS, struct dsp56k_host_flags *flags);
int ioctl(int fd, DSP56K_HOST_CMD, int cmd);

CONFIGURATION

The dsp56k device is a character device with major number 55 and minor number 0.

DESCRIPTION

The Motorola DSP56001 is a fully programmable 24-bit digital signal processor found in Atari Falcon030-compatible computers. The dsp56k special file is used to control the DSP56001, and to send and receive data using the bi-directional handshaked host port.

To send a data stream to the signal processor, use write(2) to the device, and read(2) to receive processed data. The data can be sent or received in 8, 16, 24, or 32-bit quantities on the host side, but will always be seen as 24-bit quantities in the DSP56001.

The following ioctl(2) calls are used to control the dsp56k device:

DSP56K_UPLOAD
resets the DSP56001 and uploads a program. The third ioctl(2) argument must be a pointer to a struct dsp56k_binary with members bin pointing to a DSP56001 binary program, and len set to the length of the program, counted in 24-bit words.
DSP56K_SET_TX_WSIZE
sets the transmit word size. Allowed values are in the range 1 to 4, and is the number of bytes that will be sent at a time to the DSP56001. These data quantities will either be padded with zero bytes, or truncated to fit the native 24-bit data format of the DSP56001.
DSP56K_SET_RX_WSIZE
sets the receive word size. Allowed values are in the range 1 to 4, and is the number of bytes that will be received at a time from the DSP56001. These data quantities will either truncated, or padded with a null byte ('\0') to fit the native 24-bit data format of the DSP56001.
DSP56K_HOST_FLAGS
read and write the host flags. The host flags are four general-purpose bits that can be read by both the hosting computer and the DSP56001. Bits 0 and 1 can be written by the host, and bits 2 and 3 can be written by the DSP56001.

To access the host flags, the third ioctl(2) argument must be a pointer to a struct dsp56k_host_flags. If bit 0 or 1 is set in the dir member, the corresponding bit in out will be written to the host flags. The state of all host flags will be returned in the lower four bits of the status member.

DSP56K_HOST_CMD
sends a host command. Allowed values are in the range 0 to 31, and is a user-defined command handled by the program running in the DSP56001.

FILES

/dev/dsp56k

SEE ALSO

linux/include/asm-m68k/dsp56k.h, linux/drivers/char/dsp56k.c, http://dsp56k.nocrew.org/, DSP56000/DSP56001 Digital Signal Processor User's Manual


initrd(4)

INITRD

Section: Linux Programmer's Manual (4)
Updated: 1997-11-06 Return to Main Contents

NAME

initrd - boot loader initialized RAM disk

DESCRIPTION

The special file /dev/initrd is a read-only block device. Device /dev/initrd is a RAM disk that is initialized (e.g., loaded) by the boot loader before the kernel is started. The kernel then can use the block device /dev/initrd's contents for a two phased system boot-up.

In the first boot-up phase, the kernel starts up and mounts an initial root file-system from the contents of /dev/initrd (e.g. RAM disk initialized by the boot loader). In the second phase, additional drivers or other modules are loaded from the initial root device's contents. After loading the additional modules, a new root file system (i.e., the normal root file system) is mounted from a different device.

BOOT-UP OPERATION

When booting up with initrd, the system boots as follows:

1. The boot loader loads the kernel program and /dev/initrd's contents into memory.

2. On kernel startup, the kernel uncompresses and copies the contents of the device /dev/initrd onto device /dev/ram0 and then frees the memory used by /dev/initrd.

3. The kernel then read-write mounts device /dev/ram0 as the initial root file system.

4. If the indicated normal root file system is also the initial root file-system (e.g. /dev/ram0 ) then the kernel skips to the last step for the usual boot sequence.

5. If the executable file /linuxrc is present in the initial root file-system, /linuxrc is executed with UID 0. (The file /linuxrc must have executable permission. The file /linuxrc can be any valid executable, including a shell script.)

6. If /linuxrc is not executed or when /linuxrc terminates, the normal root file system is mounted. (If /linuxrc exits with any file-systems mounted on the initial root file-system, then the behavior of the kernel is UNSPECIFIED. See the NOTES section for the current kernel behavior.)

7. If the normal root file has directory /initrd, device /dev/ram0 is moved from / to /initrd. Otherwise if directory /initrd does not exist device /dev/ram0 is unmounted. (When moved from / to /initrd, /dev/ram0 is not unmounted and therefore processes can remain running from /dev/ram0. If directory /initrd does not exist on the normal root file-system and any processes remain running from /dev/ram0 when /linuxrc exits, the behavior of the kernel is UNSPECIFIED. See the NOTES section for the current kernel behavior.)

8. The usual boot sequence (e.g. invocation of /sbin/init) is performed on the normal root file system.

OPTIONS

The following boot loader options when used with initrd, affect the kernel's boot-up operation:
initrd=filename
Specifies the file to load as the contents of /dev/initrd. For LOADLIN this is a command line option. For LILO you have to use this command in the LILO configuration file /etc/lilo.config. The filename specified with this option will typically be a gzipped file-system image.
noinitrd
This boot time option disables the two phase boot-up operation. The kernel performs the usual boot sequence as if /dev/initrd was not initialized. With this option, any contents of /dev/initrd loaded into memory by the boot loader contents are preserved. This option permits the contents of /dev/initrd to be any data and need not be limited to a file system image. However, device /dev/initrd is read-only and can be read only one time after system startup.
root=device-name
Specifies the device to be used as the normal root file system. For LOADLIN this is a command line option. For LILO this is a boot time option or can be used as an option line in the LILO configuration file /etc/lilo.config. The device specified by the this option must be a mountable device having a suitable root file-system.

CHANGING THE NORMAL ROOT FILE SYSTEM

By default, the kernel's settings (e.g. set in the kernel file with rdev(8) or compiled into the kernel file), or the boot loader option setting is used for the normal root file systems. For a NFS-mounted normal root file system, one has to use the nfs_root_name and nfs_root_addrs boot options to give the NFS settings. For more information on NFS-mounted root see the kernel documentation file nfsroot.txt. For more information on setting the root file system also see the LILO and LOADLIN documentation.

It is also possible for the /linuxrc executable to change the normal root device. For /linuxrc to change the normal root device, /proc must be mounted. After mounting /proc, /linuxrc changes the normal root device by writing into the proc files /proc/sys/kernel/real-root-dev, /proc/sys/kernel/nfs-root-name, and /proc/sys/kernel/nfs-root-addrs. For a physical root device, the root device is changed by having /linuxrc write the new root file system device number into /proc/sys/kernel/real-root-dev. For a NFS root file system, the root device is changed by having /linuxrc write the NFS setting into files /proc/sys/kernel/nfs-root-name and /proc/sys/kernel/nfs-root-addrs and then writing 0xff (e.g. the pseudo-NFS-device number) into file /proc/sys/kernel/real-root-dev. For example, the following shell command line would change the normal root device to /dev/hdb1:

    echo 0x365 >/proc/sys/kernel/real-root-dev
For a NFS example, the following shell command lines would change the normal root device to the NFS directory /var/nfsroot on a local networked NFS server with IP number 193.8.232.7 for a system with IP number 193.8.232.7 and named 'idefix':

    echo /var/nfsroot >/proc/sys/kernel/nfs-root-name
    echo 193.8.232.2:193.8.232.7::255.255.255.0:idefix \
        >/proc/sys/kernel/nfs-root-addrs
    echo 255 >/proc/sys/kernel/real-root-dev

Note: The use of /proc/sys/kernel/real-root-dev to change the root file system is obsolete. See the kernel source file Documentation/initrd.txt as well as pivot_root(2) and pivot_root(8) for information on the modern method of changing the root file system.

USAGE

The main motivation for implementing initrd was to allow for modular kernel configuration at system installation.

A possible system installation scenario is as follows:

1. The loader program boots from floppy or other media with a minimal kernel (e.g. support for /dev/ram, /dev/initrd, and the ext2 file-system) and loads /dev/initrd with a gzipped version of the initial file-system.

2. The executable /linuxrc determines what is needed to (1) mount the normal root file-system (i.e., device type, device drivers, file system) and (2) the distribution media (e.g. CD-ROM, network, tape, ...). This can be done by asking the user, by auto-probing, or by using a hybrid approach.

3. The executable /linuxrc loads the necessary modules from the initial root file-system.

4. The executable /linuxrc creates and populates the root file system. (At this stage the normal root file system does not have to be a completed system yet.)

5. The executable /linuxrc sets /proc/sys/kernel/real-root-dev, unmount /proc, the normal root file system and any other file systems it has mounted, and then terminates.

6. The kernel then mounts the normal root file system.

7. Now that the file system is accessible and intact, the boot loader can be installed.

8. The boot loader is configured to load into /dev/initrd a file system with the set of modules that was used to bring up the system. (e.g. Device /dev/ram0 can be modified, then unmounted, and finally, the image is written from /dev/ram0 to a file.)

9. The system is now bootable and additional installation tasks can be performed.

The key role of /dev/initrd in the above is to re-use the configuration data during normal system operation without requiring initial kernel selection, a large generic kernel or, recompiling the kernel.

A second scenario is for installations where Linux runs on systems with different hardware configurations in a single administrative network. In such cases, it may be desirable to use only a small set of kernels (ideally only one) and to keep the system-specific part of configuration information as small as possible. In this case, create a common file with all needed modules. Then, only the /linuxrc file or a file executed by /linuxrc would be different.

A third scenario is more convenient recovery disks. Because information like the location of the root file-system partition is not needed at boot time, the system loaded from /dev/initrd can use a dialog and/or auto-detection followed by a possible sanity check.

Last but not least, Linux distributions on CD-ROM may use initrd for easy installation from the CD-ROM. The distribution can use LOADLIN to directly load /dev/initrd from CD-ROM without the need of any floppies. The distribution could also use a LILO boot floppy and then bootstrap a bigger ram disk via /dev/initrd from the CD-ROM.

CONFIGURATION

The /dev/initrd is a read-only block device assigned major number 1 and minor number 250. Typically /dev/initrd is owned by root.disk with mode 0400 (read access by root only). If the Linux system does not have /dev/initrd already created, it can be created with the following commands:

        mknod -m 400 /dev/initrd b 1 250
        chown root:disk /dev/initrd
Also, support for both "RAM disk" and "Initial RAM disk" (e.g. CONFIG_BLK_DEV_RAM=y and CONFIG_BLK_DEV_INITRD=y ) support must be compiled directly into the Linux kernel to use /dev/initrd. When using /dev/initrd, the RAM disk driver cannot be loaded as a module.

FILES

/dev/initrd
/dev/ram0
/linuxrc
/initrd

NOTES

1. With the current kernel, any file systems that remain mounted when /dev/ram0 is moved from / to /initrd continue to be accessible. However, the /proc/mounts entries are not updated.

2. With the current kernel, if directory /initrd does not exist, then /dev/ram0 will NOT be fully unmounted if /dev/ram0 is used by any process or has any file-system mounted on it. If /dev/ram0 is NOT fully unmounted, then /dev/ram0 will remain in memory.

3. Users of /dev/initrd should not depend on the behavior give in the above notes. The behavior may change in future versions of the Linux kernel.

SEE ALSO

chown(1), mknod(1), ram(4), freeramdisk(8), rdev(8)

The documentation file initrd.txt in the kernel source package, the LILO documentation, the LOADLIN documentation, the SYSLINUX documentation.


sd(4)

SD

Section: Linux Programmer's Manual (4)
Updated: 1992-12-17 Return to Main Contents

NAME

sd - Driver for SCSI Disk Drives

SYNOPSIS

#include <linux/hdreg.h>        /* for HDIO_GETGEO */
#include <linux/fs.h>           /* for BLKGETSIZE and BLKRRPART */

CONFIG

The block device name has the following form: sd lp, where l is a letter denoting the physical drive, and p is a number denoting the partition on that physical drive. Often, the partition number, p, will be left off when the device corresponds to the whole drive.

SCSI disks have a major device number of 8, and a minor device number of the form (16 * drive_number) + partition_number, where drive_number is the number of the physical drive in order of detection, and partition_number is as follows:

partition 0 is the whole drive
partitions 1-4 are the DOS "primary" partitions
partitions 5-8 are the DOS "extended" (or "logical") partitions

For example, /dev/sda will have major 8, minor 0, and will refer to all of the first SCSI drive in the system; and /dev/sdb3 will have major 8, minor 19, and will refer to the third DOS "primary" partition on the second SCSI drive in the system.

At this time, only block devices are provided. Raw devices have not yet been implemented.

DESCRIPTION

The following ioctls are provided:
HDIO_GETGEO
Returns the BIOS disk parameters in the following structure:
struct hd_geometry {
      unsigned char heads;
      unsigned char sectors;
      unsigned short cylinders;
      unsigned long start;
};

A pointer to this structure is passed as the ioctl(2) parameter.

The information returned in the parameter is the disk geometry of the drive as understood by DOS! This geometry is not the physical geometry of the drive. It is used when constructing the drive's partition table, however, and is needed for convenient operation of fdisk(1), efdisk(1), and lilo(1). If the geometry information is not available, zero will be returned for all of the parameters.

BLKGETSIZE
Returns the device size in sectors. The ioctl(2) parameter should be a pointer to a long.
BLKRRPART
Forces a re-read of the SCSI disk partition tables. No parameter is needed.

The scsi(4) ioctl(2) operations are also supported. If the ioctl(2) parameter is required, and it is NULL, then ioctl(2) will return -EINVAL.

FILES

/dev/sd[a-h]: the whole device
/dev/sd[a-h][0-8]: individual block partitions


kmem (4)

 Continue to this page.


console_codes(4)

CONSOLE_CODES

Section: Linux Programmer's Manual (4)
Updated: 2006-05-29 Return to Main Contents

NAME

console_codes - Linux console escape and control sequences

DESCRIPTION

The Linux console implements a large subset of the VT102 and ECMA-48/ISO 6429/ANSI X3.64 terminal controls, plus certain private-mode sequences for changing the color palette, character-set mapping, etc. In the tabular descriptions below, the second column gives ECMA-48 or DEC mnemonics (the latter if prefixed with DEC) for the given function. Sequences without a mnemonic are neither ECMA-48 nor VT102.

After all the normal output processing has been done, and a stream of characters arrives at the console driver for actual printing, the first thing that happens is a translation from the code used for processing to the code used for printing.

If the console is in UTF-8 mode, then the incoming bytes are first assembled into 16-bit Unicode codes. Otherwise each byte is transformed according to the current mapping table (which translates it to a Unicode value). See the CHARACTER SETS section below for discussion.

In the normal case, the Unicode value is converted to a font index, and this is stored in video memory, so that the corresponding glyph (as found in video ROM) appears on the screen. Note that the use of Unicode (and the design of the PC hardware) allows us to use 512 different glyphs simultaneously.

If the current Unicode value is a control character, or we are currently processing an escape sequence, the value will treated specially. Instead of being turned into a font index and rendered as a glyph, it may trigger cursor movement or other control functions. See the LINUX CONSOLE CONTROLS section below for discussion.

It is generally not good practice to hard-wire terminal controls into programs. Linux supports a terminfo(5) database of terminal capabilities. Rather than emitting console escape sequences by hand, you will almost always want to use a terminfo-aware screen library or utility such as ncurses(3), tput(1), or reset(1).

LINUX CONSOLE CONTROLS

This section describes all the control characters and escape sequences that invoke special functions (i.e., anything other than writing a glyph at the current cursor location) on the Linux console.

Control characters

A character is a control character if (before transformation according to the mapping table) it has one of the 14 codes 00 (NUL), 07 (BEL), 08 (BS), 09 (HT), 0a (LF), 0b (VT), 0c (FF), 0d (CR), 0e (SO), 0f (SI), 18 (CAN), 1a (SUB), 1b (ESC), 7f (DEL). One can set a `display control characters' mode (see below), and allow 07, 09, 0b, 18, 1a, 7f to be displayed as glyphs. On the other hand, in UTF-8 mode all codes 00-1f are regarded as control characters, regardless of any `display control characters' mode.

If we have a control character, it is acted upon immediately and then discarded (even in the middle of an escape sequence) and the escape sequence continues with the next character. (However, ESC starts a new escape sequence, possibly aborting a previous unfinished one, and CAN and SUB abort any escape sequence.) The recognized control characters are BEL, BS, HT, LF, VT, FF, CR, SO, SI, CAN, SUB, ESC, DEL, CSI. They do what one would expect:

BEL (0x07, ^G) beeps;
BS (0x08, ^H) backspaces one column (but not past the beginning of the line);
HT (0x09, ^I) goes to the next tab stop or to the end of the line if there is no earlier tab stop;
LF (0x0A, ^J), VT (0x0B, ^K) and FF (0x0C, ^L) all give a linefeed;
CR (0x0D, ^M) gives a carriage return;
SO (0x0E, ^N) activates the G1 character set, and if LF/NL (new line mode) is set also a carriage return;
SI (0x0F, ^O) activates the G0 character set;
CAN (0x18, ^X) and SUB (0x1A, ^Z) interrupt escape sequences;
ESC (0x1B, ^[) starts an escape sequence;
DEL (0x7F) is ignored;
CSI (0x9B) is equivalent to ESC [.

ESC- but not CSI-sequences

ESC c | RIS | Reset.
ESC D | IND | Linefeed.
ESC E | NEL | Newline.
ESC H | HTS | Set tab stop at current column.
ESC M | RI | Reverse linefeed.
ESC Z | DECID | DEC private identification. The kernel returns the string ESC [ ? 6 c, claiming that it is a VT102.
ESC 7 | DECSC | Save current state (cursor coordinates, attributes, character sets pointed at by G0, G1).
ESC 8 | DECRC | Restore state most recently saved by ESC 7.
ESC [ | CSI | Control sequence introducer
ESC % |  | Start sequence selecting character set
ESC % @ |  | Select default (ISO 646 / ISO 8859-1)
ESC % G |  | Select UTF-8
ESC % 8 |  | Select UTF-8 (obsolete)
ESC # 8 | DECALN | DEC screen alignment test - fill screen with E's.
ESC ( |  | Start sequence defining G0 character set
ESC ( B |  | Select default (ISO 8859-1 mapping)
ESC ( 0 |  | Select VT100 graphics mapping
ESC ( U |  | Select null mapping - straight to character ROM
ESC ( K |  | Select user mapping - the map that is loaded by
 |  | the utility mapscrn(8).
ESC ) |  | Start sequence defining G1
 |  | (followed by one of B, 0, U, K, as above).
ESC > | DECPNM | Set numeric keypad mode
ESC = | DECPAM | Set application keypad mode
ESC ] | OSC | (Should be: Operating system command) ESC ] P nrrggbb: set palette, with parameter given in 7 hexadecimal digits after the final P :-(. Here n is the color (0-15), and rrggbb indicates the red/green/blue values (0-255). ESC ] R: reset palette

ECMA-48 CSI sequences

CSI (or ESC [) is followed by a sequence of parameters, at most NPAR (16), that are decimal numbers separated by semicolons. An empty or absent parameter is taken to be 0. The sequence of parameters may be preceded by a single question mark.

However, after CSI [ (or ESC [ [) a single character is read and this entire sequence is ignored. (The idea is to ignore an echoed function key.)

The action of a CSI sequence is determined by its final character.
@ | ICH | Insert the indicated # of blank characters.
A | CUU | Move cursor up the indicated # of rows.
B | CUD | Move cursor down the indicated # of rows.
C | CUF | Move cursor right the indicated # of columns.
D | CUB | Move cursor left the indicated # of columns.
E | CNL | Move cursor down the indicated # of rows, to column 1.
F | CPL | Move cursor up the indicated # of rows, to column 1.
G | CHA | Move cursor to indicated column in current row.
H | CUP | Move cursor to the indicated row, column (origin at 1,1).
J | ED | Erase display (default: from cursor to end of display).
 |  | ESC [ 1 J: erase from start to cursor.
 |  | ESC [ 2 J: erase whole display.
K | EL | Erase line (default: from cursor to end of line).
 |  | ESC [ 1 K: erase from start of line to cursor.
 |  | ESC [ 2 K: erase whole line.
L | IL | Insert the indicated # of blank lines.
M | DL | Delete the indicated # of lines.
P | DCH | Delete the indicated # of characters on the current line.
X | ECH | Erase the indicated # of characters on the current line.
a | HPR | Move cursor right the indicated # of columns.
c | DA | Answer ESC [ ? 6 c: `I am a VT102'.
d | VPA | Move cursor to the indicated row, current column.
e | VPR | Move cursor down the indicated # of rows.
f | HVP | Move cursor to the indicated row, column.
g | TBC | Without parameter: clear tab stop at the current position.
 |  | ESC [ 3 g: delete all tab stops.
h | SM | Set Mode (see below).
l | RM | Reset Mode (see below).
m | SGR | Set attributes (see below).
n | DSR | Status report (see below).
q | DECLL | Set keyboard LEDs.
 |  | ESC [ 0 q: clear all LEDs
 |  | ESC [ 1 q: set Scroll Lock LED
 |  | ESC [ 2 q: set Num Lock LED
 |  | ESC [ 3 q: set Caps Lock LED
r | DECSTBM | Set scrolling region; parameters are top and bottom row.
s | ? | Save cursor location.
u | ? | Restore cursor location.
` | HPA | Move cursor to indicated column in current row.

ECMA-48 Set Graphics Rendition

The ECMA-48 SGR sequence ESC [ parameters m sets display attributes. Several attributes can be set in the same sequence, separated by semicolons. An empty parameter (between semicolons or string initiator or terminator) is interpreted as a zero.
param | result
0 | reset all attributes to their defaults
1 | set bold
2 | set half-bright (simulated with color on a color display)
4 | set underscore (simulated with color on a color display) (the colors used to simulate dim or underline are set using ESC ] ...)
5 | set blink
7 | set reverse video
10 | reset selected mapping, display control flag, and toggle meta flag (ECMA-48 says "primary font").
11 | select null mapping, set display control flag, reset toggle meta flag (ECMA-48 says "first alternate font").
12 | select null mapping, set display control flag, set toggle meta flag (ECMA-48 says "second alternate font"). The toggle meta flag causes the high bit of a byte to be toggled before the mapping table translation is done.
21 | set normal intensity (ECMA-48 says "doubly underlined")
22 | set normal intensity
24 | underline off
25 | blink off
27 | reverse video off
30 | set black foreground
31 | set red foreground
32 | set green foreground
33 | set brown foreground
34 | set blue foreground
35 | set magenta foreground
36 | set cyan foreground
37 | set white foreground
38 | set underscore on, set default foreground color
39 | set underscore off, set default foreground color
40 | set black background
41 | set red background
42 | set green background
43 | set brown background
44 | set blue background
45 | set magenta background
46 | set cyan background
47 | set white background
49 | set default background color

ECMA-48 Mode Switches

ESC [ 3 h
DECCRM (default off): Display control chars.
ESC [ 4 h
DECIM (default off): Set insert mode.
ESC [ 20 h
LF/NL (default off): Automatically follow echo of LF, VT or FF with CR.

ECMA-48 Status Report Commands

ESC [ 5 n
Device status report (DSR): Answer is ESC [ 0 n (Terminal OK).
ESC [ 6 n
Cursor position report (CPR): Answer is ESC [ y ; x R, where x,y is the cursor location.

DEC Private Mode (DECSET/DECRST) sequences.

These are not described in ECMA-48. We list the Set Mode sequences; the Reset Mode sequences are obtained by replacing the final `h' by `l'.
ESC [ ? 1 h
DECCKM (default off): When set, the cursor keys send an ESC O prefix, rather than ESC [.
ESC [ ? 3 h
DECCOLM (default off = 80 columns): 80/132 col mode switch. The driver sources note that this alone does not suffice; some user-mode utility such as resizecons(8) has to change the hardware registers on the console video card.
ESC [ ? 5 h
DECSCNM (default off): Set reverse-video mode.
ESC [ ? 6 h
DECOM (default off): When set, cursor addressing is relative to the upper left corner of the scrolling region.
ESC [ ? 7 h
DECAWM (default on): Set autowrap on. In this mode, a graphic character emitted after column 80 (or column 132 of DECCOLM is on) forces a wrap to the beginning of the following line first.
ESC [ ? 8 h
DECARM (default on): Set keyboard autorepreat on.
ESC [ ? 9 h
X10 Mouse Reporting (default off): Set reporting mode to 1 (or reset to 0) --- see below.
ESC [ ? 25 h
DECTECM (default on): Make cursor visible.
ESC [ ? 1000 h
X11 Mouse Reporting (default off): Set reporting mode to 2 (or reset to 0) --- see below.

Linux Console Private CSI Sequences

The following sequences are neither ECMA-48 nor native VT102. They are native to the Linux console driver. Colors are in SGR parameters: 0 = black, 1 = red, 2 = green, 3 = brown, 4 = blue, 5 = magenta, 6 = cyan, 7 = white.
ESC [ 1 ; n ] | Set color n as the underline color
ESC [ 2 ; n ] | Set color n as the dim color
ESC [ 8 ] | Make the current color pair the default attributes.
ESC [ 9 ; n ] | Set screen blank timeout to n minutes.
ESC [ 10 ; n ] | Set bell frequency in Hz.
ESC [ 11 ; n ] | Set bell duration in msec.
ESC [ 12 ; n ] | Bring specified console to the front.
ESC [ 13 ] | Unblank the screen.
ESC [ 14 ; n ] | Set the VESA powerdown interval in minutes.

CHARACTER SETS

The kernel knows about 4 translations of bytes into console-screen symbols. The four tables are: a) Latin1 -> PC, b) VT100 graphics -> PC, c) PC -> PC, d) user-defined.

There are two character sets, called G0 and G1, and one of them is the current character set. (Initially G0.) Typing ^N causes G1 to become current, ^O causes G0 to become current.

These variables G0 and G1 point at a translation table, and can be changed by the user. Initially they point at tables a) and b), respectively. The sequences ESC ( B and ESC ( 0 and ESC ( U and ESC ( K cause G0 to point at translation table a), b), c) and d), respectively. The sequences ESC ) B and ESC ) 0 and ESC ) U and ESC ) K cause G1 to point at translation table a), b), c) and d), respectively.

The sequence ESC c causes a terminal reset, which is what you want if the screen is all garbled. The oft-advised "echo ^V^O" will only make G0 current, but there is no guarantee that G0 points at table a). In some distributions there is a program reset(1) that just does "echo ^[c". If your terminfo entry for the console is correct (and has an entry rs1=\Ec), then "tput reset" will also work.

The user-defined mapping table can be set using mapscrn(8). The result of the mapping is that if a symbol c is printed, the symbol s = map[c] is sent to the video memory. The bitmap that corresponds to s is found in the character ROM, and can be changed using setfont(8).

MOUSE TRACKING

The mouse tracking facility is intended to return xterm-compatible mouse status reports. Because the console driver has no way to know the device or type of the mouse, these reports are returned in the console input stream only when the virtual terminal driver receives a mouse update ioctl. These ioctls must be generated by a mouse-aware user-mode application such as the gpm(8) daemon.

The mouse tracking escape sequences generated by xterm encode numeric parameters in a single character as value+040. For example, `!' is 1. The screen coordinate system is 1-based.

The X10 compatibility mode sends an escape sequence on button press encoding the location and the mouse button pressed. It is enabled by sending ESC [ ? 9 h and disabled with ESC [ ? 9 l. On button press, xterm sends ESC [ M bxy (6 characters). Here b is button-1, and x and y are the x and y coordinates of the mouse when the button was pressed. This is the same code the kernel also produces.

Normal tracking mode (not implemented in Linux 2.0.24) sends an escape sequence on both button press and release. Modifier information is also sent. It is enabled by sending ESC [ ? 1000 h and disabled with ESC [ 1000 l. On button press or release, xterm sends ESC [ M bxy. The low two bits of b encode button information: 0=MB1 pressed, 1=MB2 pressed, 2=MB3 pressed, 3=release. The upper bits encode what modifiers were down when the button was pressed and are added together: 4=Shift, 8=Meta, 16=Control. Again x and y are the x and y coordinates of the mouse event. The upper left corner is (1,1).

COMPARISONS WITH OTHER TERMINALS

Many different terminal types are described, like the Linux console, as being `VT100-compatible'. Here we discuss differences between the Linux console and the two most important others, the DEC VT102 and xterm(1).

Control-character handling

The VT102 also recognized the following control characters:
NUL (0x00) was ignored;
ENQ (0x05) triggered an answerback message;
DC1 (0x11, ^Q, XON) resumed transmission;
DC3 (0x13, ^S, XOFF) caused VT100 to ignore (and stop transmitting) all codes except XOFF and XON.

VT100-like DC1/DC3 processing may be enabled by the tty driver.

The xterm program (in VT100 mode) recognizes the control characters BEL, BS, HT, LF, VT, FF, CR, SO, SI, ESC.

Escape sequences

VT100 console sequences not implemented on the Linux console:
ESC N | SS2 | Single shift 2. (Select G2 character set for the next
 |  | character only.)
ESC O | SS3 | Single shift 3. (Select G3 character set for the next
 |  | character only.)
ESC P | DCS | Device control string (ended by ESC \)
ESC X | SOS | Start of string.
ESC ^ | PM | Privacy message (ended by ESC \)
ESC \ | ST | String terminator
ESC * ... |  | Designate G2 character set
ESC + ... |  | Designate G3 character set

The program xterm (in VT100 mode) recognizes ESC c, ESC # 8, ESC >, ESC =, ESC D, ESC E, ESC H, ESC M, ESC N, ESC O, ESC P ... ESC , ESC Z (it answers ESC [ ? 1 ; 2 c, `I am a VT100 with advanced video option') and ESC ^ ... ESC with the same meanings as indicated above. It accepts ESC (, ESC ), ESC *, ESC + followed by 0, A, B for the DEC special character and line drawing set, UK, and US-ASCII, respectively.

The user can configure xterm to respond to VT220-specific control sequences, and it will identify itself as a VT52, VT100, and up depending on the way it is configured and initialized.

It accepts ESC ] (OSC) for the setting of certain resources. In addition to the ECMA-48 string terminator (ST), xterm accepts a BEL to terminate an OSC string. These are a few of the OSC control sequences recognized by xterm:
ESC ] 0 ; txt ST | Set icon name and window title to txt.
ESC ] 1 ; txt ST | Set icon name to txt.
ESC ] 2 ; txt ST | Set window title to txt.
ESC ] 4 ; num; txt ST | Set ANSI color num to txt.
ESC ] 10 ; txt ST | Set dynamic text color to txt.
ESC ] 4 6 ; name ST | Change log file to name (normally disabled
 | by a compile-time option)
ESC ] 5 0 ; fn ST | Set font to fn.

It recognizes the following with slightly modified meaning (saving more state, behaving closer to VT100/VT220):
ESC 7 DECSC | Save cursor
ESC 8 DECRC | Restore cursor

It also recognizes
ESC F |  | Cursor to lower left corner of screen (if enabled by
 |  | xterm's hpLowerleftBugCompat resource)
ESC l |  | Memory lock (per HP terminals).
 |  | Locks memory above the cursor.
ESC m |  | Memory unlock (per HP terminals).
ESC n | LS2 | Invoke the G2 character set.
ESC o | LS3 | Invoke the G3 character set.
ESC | | LS3R | Invoke the G3 character set as GR.
ESC } | LS2R | Invoke the G2 character set as GR.
ESC ~ | LS1R | Invoke the G1 character set as GR.

It also recognizes ESC % and provides a more complete UTF-8 implementation than Linux console.

CSI Sequences

Old versions of xterm, for example, from X11R5, interpret the blink SGR as a bold SGR. Later versions which implemented ANSI colors, for example, XFree86 3.1.2A in 1995, improved this by allowing the blink attribute to be displayed as a color. Modern versions of xterm implement blink SGR as blinking text and still allow colored text as an alternate rendering of SGRs. Stock X11R6 versions did not recognize the color-setting SGRs until the X11R6.8 release, which incorporated XFree86 xterm. All ECMA-48 CSI sequences recognized by Linux are also recognized by xterm, however xterm implements several ECMA-48 and DEC control sequences not recognized by Linux.

The xterm program recognizes all of the DEC Private Mode sequences listed above, but none of the Linux private-mode sequences. For discussion of xterm's own private-mode sequences, refer to the Xterm Control Sequences document by Edward Moy, Stephen Gildea, and Thomas E. Dickey available with the X distribution. That document, though terse, is much longer than this manual page. For a chronological overview,

http://invisible-island.net/xterm/xterm.log.html

details changes to xterm.

The vttest program

http://invisible-island.net/vttest/

demonstrates many of these control sequences. The xterm source distribution also contains sample scripts which exercise other features.

NOTES

ESC 8 (DECRC) is not able to restore the character set changed with ESC %.

BUGS

In 2.0.23, CSI is broken, and NUL is not ignored inside escape sequences.

Some older kernel versions (after 2.0) interpret 8-bit control sequences. These "C1 controls" use codes between 128 and 159 to replace ESC [, ESC ] and similar two-byte control sequence initiators. There are fragments of that in modern kernels (either overlooked or broken by changes to support UTF-8), but the implementation is incomplete and should be regarded as unreliable.

Linux "private mode" sequences do not follow the rules in ECMA-48 for private mode control sequences. In particular, those ending with ] do not use a standard terminating character. The OSC (set palette) sequence is a greater problem, since xterm may interpret this as a control sequence which requires a string terminator (ST). Unlike the setterm sequences which will be ignored (since they are invalid control sequences), the palette sequence will make xterm appear to hang (though pressing the return-key will fix that). To accommodate applications which have been hardcoded to use Linux control sequences, set the xterm resource brokenLinuxOSC to true.

An older version of this document implied that Linux recognizes the ECMA-48 control sequence for invisible text. It is ignored.

SEE ALSO

console(4), console_ioctl(4), charsets(7)


null(4)

NULL

Section: Linux Programmer's Manual (4)
Updated: 1992-11-21 Return to Main Contents

NAME

null, zero - data sink

DESCRIPTION

Data written on a null or zero special file is discarded.

Reads from the null special file always return end of file, whereas reads from zero always return \0 characters.

null and zero are typically created by:

mknod -m 666 /dev/null c 1 3
mknod -m 666 /dev/zero c 1 5
chown root:root /dev/null /dev/zero

FILES

/dev/null
/dev/zero

NOTES

If these devices are not writable and readable for all users, many programs will act strangely.

SEE ALSO

chown(1), mknod(1), full(4)


port (4)

 Continue to this page.


console(4)

CONSOLE

Section: Linux Programmer's Manual (4)
Updated: 1994-10-31 Return to Main Contents

NAME

console - console terminal and virtual consoles

DESCRIPTION

A Linux system has up to 63 virtual consoles (character devices with major number 4 and minor number 1 to 63), usually called /dev/ttyn with 1 < n < 63. The current console is also addressed by /dev/console or /dev/tty0, the character device with major number 4 and minor number 0. The device files /dev/* are usually created using the script MAKEDEV, or using mknod(1), usually with mode 0622 and owner root.tty.

Before kernel version 1.1.54 the number of virtual consoles was compiled into the kernel (in tty.h: #define NR_CONSOLES 8) and could be changed by editing and recompiling. Since version 1.1.54 virtual consoles are created on the fly, as soon as they are needed.

Common ways to start a process on a console are: (a) tell init(8) (in inittab(5)) to start a mingetty(8) on the console; (b) ask openvt(1) to start a process on the console; (c) start X --- it will find the first unused console, and display its output there. (There is also the ancient doshell(8).)

Common ways to switch consoles are: (a) use Alt+Fn or Ctrl+Alt+Fn to switch to console n; AltGr+Fn might bring you to console n+12 [here Alt and AltGr refer to the left and right Alt keys, respectively]; (b) use Alt+RightArrow or Alt+LeftArrow to cycle through the presently allocated consoles; (c) use the program chvt(1). (The key mapping is user settable, see loadkeys(1); the above mentioned key combinations are according to the default settings.)

The command deallocvt(1) (formerly disalloc) will free the memory taken by the screen buffers for consoles that no longer have any associated process.

Properties

Consoles carry a lot of state. I hope to document that some other time. The most important fact is that the consoles simulate vt100 terminals. In particular, a console is reset to the initial state by printing the two characters ESC c. All escape sequences can be found in console_codes(4).

FILES

/dev/console
/dev/tty*

SEE ALSO

chvt(1), deallocvt(1), loadkeys(1), mknod(1), openvt(1), console_codes(4), console_ioctl(4), tty(4), ttyS(4), charsets(7), mingetty(8), init(8), mapscrn(8), resizecons(8), setfont(8)


console_ioctl(4)

CONSOLE_IOCTLS

Section: Linux Programmer's Manual (4)
Updated: 1995-09-18 Return to Main Contents

NAME

console ioctl - ioctl's for console terminal and virtual consoles

DESCRIPTION

The following Linux-specific ioctl(2) requests are supported. Each requires a third argument, assumed here to be argp.
KDGETLED
Get state of LEDs. argp points to a long int. The lower three bits of *argp are set to the state of the LEDs, as follows:

LED_CAP 0x04 caps lock led
LEC_NUM 0x02 num lock led
LED_SCR 0x01 scroll lock led

KDSETLED
Set the LEDs. The LEDs are set to correspond to the lower three bits of argp. However, if a higher order bit is set, the LEDs revert to normal: displaying the state of the keyboard functions of caps lock, num lock, and scroll lock.

Before 1.1.54, the LEDs just reflected the state of the corresponding keyboard flags, and KDGETLED/KDSETLED would also change the keyboard flags. Since 1.1.54 the leds can be made to display arbitrary information, but by default they display the keyboard flags. The following two ioctl's are used to access the keyboard flags.

KDGKBLED
Get keyboard flags CapsLock, NumLock, ScrollLock (not lights). argp points to a char which is set to the flag state. The low order three bits (mask 0x7) get the current flag state, and the low order bits of the next nibble (mask 0x70) get the default flag state. (Since 1.1.54.)
KDSKBLED
Set keyboard flags CapsLock, NumLock, ScrollLock (not lights). argp has the desired flag state. The low order three bits (mask 0x7) have the flag state, and the low order bits of the next nibble (mask 0x70) have the default flag state. (Since 1.1.54.)
KDGKBTYPE
Get keyboard type. This returns the value KB_101, defined as 0x02.
KDADDIO
Add I/O port as valid. Equivalent to ioperm(arg,1,1).
KDDELIO
Delete I/O port as valid. Equivalent to ioperm(arg,1,0).
KDENABIO
Enable I/O to video board. Equivalent to ioperm(0x3b4, 0x3df-0x3b4+1, 1).
KDDISABIO
Disable I/O to video board. Equivalent to ioperm(0x3b4, 0x3df-0x3b4+1, 0).
KDSETMODE
Set text/graphics mode. argp is one of these:

KD_TEXT 0x00
KD_GRAPHICS 0x01

KDGETMODE
Get text/graphics mode. argp points to a long which is set to one of the above values.
KDMKTONE
Generate tone of specified length. The lower 16 bits of argp specify the period in clock cycles, and the upper 16 bits give the duration in msec. If the duration is zero, the sound is turned off. Control returns immediately. For example, argp = (125<<16) + 0x637 would specify the beep normally associated with a ctrl-G. (Thus since 0.99pl1; broken in 2.1.49-50.)
KIOCSOUND
Start or stop sound generation. The lower 16 bits of argp specify the period in clock cycles (that is, argp = 1193180/frequency). argp = 0 turns sound off. In either case, control returns immediately.
GIO_CMAP
Get the current default color map from kernel. argp points to a 48-byte array. (Since 1.3.3.)
PIO_CMAP
Change the default text-mode color map. argp points to a 48-byte array which contains, in order, the Red, Green, and Blue values for the 16 available screen colors: 0 is off, and 255 is full intensity. The default colors are, in order: black, dark red, dark green, brown, dark blue, dark purple, dark cyan, light grey, dark grey, bright red, bright green, yellow, bright blue, bright purple, bright cyan and white. (Since 1.3.3.)
GIO_FONT
Gets 256-character screen font in expanded form. argp points to an 8192 byte array. Fails with error code EINVAL if the currently loaded font is a 512-character font, or if the console is not in text mode.
GIO_FONTX
Gets screen font and associated information. argp points to a struct consolefontdesc (see PIO_FONTX). On call, the charcount field should be set to the maximum number of characters that would fit in the buffer pointed to by chardata. On return, the charcount and charheight are filled with the respective data for the currently loaded font, and the chardata array contains the font data if the initial value of charcount indicated enough space was available; otherwise the buffer is untouched and errno is set to ENOMEM. (Since 1.3.1.)
PIO_FONT
Sets 256-character screen font. Load font into the EGA/VGA character generator. argp points to a 8192 byte map, with 32 bytes per character. Only first N of them are used for an 8xN font (0 < N <= 32). This call also invalidates the Unicode mapping.
PIO_FONTX
Sets screen font and associated rendering information. argp points to a

struct consolefontdesc {
    u_short charcount;    /* characters in font (256 or 512) */
    u_short charheight;   /* scan lines per character (1-32) */
    char *chardata;       /* font data in expanded form */
};

If necessary, the screen will be appropriately resized, and SIGWINCH sent to the appropriate processes. This call also invalidates the Unicode mapping. (Since 1.3.1.)

PIO_FONTRESET
Resets the screen font, size and Unicode mapping to the bootup defaults. argp is unused, but should be set to NULL to ensure compatibility with future versions of Linux. (Since 1.3.28.)
GIO_SCRNMAP
Get screen mapping from kernel. argp points to an area of size E_TABSZ, which is loaded with the font positions used to display each character. This call is likely to return useless information if the currently loaded font is more than 256 characters.
GIO_UNISCRNMAP
Get full Unicode screen mapping from kernel. argp points to an area of size E_TABSZ*sizeof(unsigned short), which is loaded with the Unicodes each character represent. A special set of Unicodes, starting at U+F000, are used to represent ``direct to font'' mappings. (Since 1.3.1.)
PIO_SCRNMAP
Loads the ``user definable'' (fourth) table in the kernel which maps bytes into console screen symbols. argp points to an area of size E_TABSZ.
PIO_UNISCRNMAP
Loads the ``user definable'' (fourth) table in the kernel which maps bytes into Unicodes, which are then translated into screen symbols according to the currently loaded Unicode-to-font map. Special Unicodes starting at U+F000 can be used to map directly to the font symbols. (Since 1.3.1.)
GIO_UNIMAP
Get Unicode-to-font mapping from kernel. argp points to a

struct unimapdesc {
    u_short entry_ct;
    struct unipair *entries;
};

where entries points to an array of

struct unipair {
    u_short unicode;
    u_short fontpos;
};

(Since 1.1.92.)

PIO_UNIMAP
Put unicode-to-font mapping in kernel.
argp points to a struct unimapdesc. (Since 1.1.92)
PIO_UNIMAPCLR
Clear table, possibly advise hash algorithm. argp points to a

struct unimapinit {
    u_short advised_hashsize;  /* 0 if no opinion */
    u_short advised_hashstep;  /* 0 if no opinion */
    u_short advised_hashlevel; /* 0 if no opinion */
};

(Since 1.1.92.)

KDGKBMODE
Gets current keyboard mode. argp points to a long which is set to one of these:

K_RAW 0x00
K_XLATE 0x01
K_MEDIUMRAW 0x02
K_UNICODE 0x03

KDSKBMODE
Sets current keyboard mode. argp is a long equal to one of the above values.
KDGKBMETA
Gets meta key handling mode. argp points to a long which is set to one of these:

K_METABIT 0x03 set high order bit
K_ESCPREFIX 0x04 escape prefix

KDSKBMETA
Sets meta key handling mode. argp is a long equal to one of the above values.
KDGKBENT
Gets one entry in key translation table (keycode to action code). argp points to a

struct kbentry {
    u_char kb_table;
    u_char kb_index;
    u_short kb_value;
};

with the first two members filled in: kb_table selects the key table (0 <= kb_table < MAX_NR_KEYMAPS), and kb_index is the keycode (0 <= kb_index < NR_KEYS). kb_value is set to the corresponding action code, or K_HOLE if there is no such key, or K_NOSUCHMAP if kb_table is invalid.

KDSKBENT
Sets one entry in translation table. argp points to a struct kbentry.
KDGKBSENT
Gets one function key string. argp points to a

struct kbsentry {
    u_char kb_func;
    u_char kb_string[512];
};

kb_string is set to the (NULL terminated) string corresponding to the kb_functh function key action code.

KDSKBSENT
Sets one function key string entry. argp points to a struct kbsentry.
KDGKBDIACR
Read kernel accent table. argp points to a

struct kbdiacrs {
    unsigned int kb_cnt;
    struct kbdiacr kbdiacr[256];
};

where kb_cnt is the number of entries in the array, each of which is a

struct kbdiacr {
    u_char diacr;
    u_char base;
    u_char result;
};

KDGETKEYCODE
Read kernel keycode table entry (scan code to keycode).
argp points to a

struct kbkeycode {
    unsigned int scancode;
    unsigned int keycode;
};

keycode is set to correspond to the given scancode. (89 <= scancode <= 255 only. For 1 <= scancode <= 88, keycode==scancode.) (Since 1.1.63.)

KDSETKEYCODE
Write kernel keycode table entry. argp points to a struct kbkeycode. (Since 1.1.63.)
KDSIGACCEPT
The calling process indicates its willingness to accept the signal argp when it is generated by pressing an appropriate key combination. (1 <= argp <= NSIG). (See spawn_console() in linux/drivers/char/keyboard.c.)
VT_OPENQRY
Returns the first available (non-opened) console. argp points to an int which is set to the number of the vt (1 <= *argp <= MAX_NR_CONSOLES).
VT_GETMODE
Get mode of active vt. argp points to a

struct vt_mode {
    char mode;     /* vt mode */
    char waitv;    /* if set, hang on writes if not active */
    short relsig;  /* signal to raise on release req */
    short acqsig;  /* signal to raise on acquisition */
    short frsig;   /* unused (set to 0) */
};

which is set to the mode of the active vt. mode is set to one of these values:

VT_AUTO auto vt switching
VT_PROCESS process controls switching
VT_ACKACQ acknowledge switch

VT_SETMODE
Set mode of active vt. argp points to a struct vt_mode.
VT_GETSTATE
Get global vt state info. argp points to a

struct vt_stat {
    ushort v_active;  /* active vt */
    ushort v_signal;  /* signal to send */
    ushort v_state;   /* vt bitmask */
};

For each vt in use, the corresponding bit in the v_state member is set. (Kernels 1.0 through 1.1.92.)

VT_RELDISP
Release a display.
VT_ACTIVATE
Switch to vt argp (1 <= argp <= MAX_NR_CONSOLES).
VT_WAITACTIVE
Wait until vt argp has been activated.
VT_DISALLOCATE
Deallocate the memory associated with vt argp. (Since 1.1.54.)
VT_RESIZE
Set the kernel's idea of screensize. argp points to a

struct vt_sizes {
    ushort v_rows;       /* # rows */
    ushort v_cols;       /* # columns */
    ushort v_scrollsize; /* no longer used */
};

Note that this does not change the videomode. See resizecons(8). (Since 1.1.54.)

VT_RESIZEX
Set the kernel's idea of various screen parameters. argp points to a

struct vt_consize {
    ushort v_rows;    /* number of rows */
    ushort v_cols;    /* number of columns */
    ushort v_vlin;    /* number of pixel rows on screen */
    ushort v_clin;    /* number of pixel rows per character */
    ushort v_vcol;    /* number of pixel columns on screen */
    ushort v_ccol;    /* number of pixel columns per character */
};

Any parameter may be set to zero, indicating ``no change'', but if multiple parameters are set, they must be self-consistent. Note that this does not change the videomode. See resizecons(8). (Since 1.3.3.)

The action of the following ioctls depends on the first byte in the struct pointed to by argp, referred to here as the subcode. These are legal only for the superuser or the owner of the current tty.

TIOCLINUX, subcode=0
Dump the screen. Disappeared in 1.1.92. (With kernel 1.1.92 or later, read from /dev/vcsN or /dev/vcsaN instead.)
TIOCLINUX, subcode=1
Get task information. Disappeared in 1.1.92.
TIOCLINUX, subcode=2
Set selection. argp points to a

struct {
   char subcode;
   short xs, ys, xe, ye;
   short sel_mode;
}
xs and ys are the starting column and row. xe and ye are the ending column and row. (Upper left corner is row=column=1.) sel_mode is 0 for character-by-character selection, 1 for word-by-word selection, or 2 for line-by-line selection. The indicated screen characters are highlighted and saved in the static array sel_buffer in devices/char/console.c.
TIOCLINUX, subcode=3
Paste selection. The characters in the selection buffer are written to fd.
TIOCLINUX, subcode=4
Unblank the screen.
TIOCLINUX, subcode=5
Sets contents of a 256-bit look up table defining characters in a "word", for word-by-word selection. (Since 1.1.32.)
TIOCLINUX, subcode=6
argp points to a char which is set to the value of the kernel variable shift_state. (Since 1.1.32.)
TIOCLINUX, subcode=7
argp points to a char which is set to the value of the kernel variable report_mouse. (Since 1.1.33.)
TIOCLINUX, subcode=8
Dump screen width and height, cursor position, and all the character-attribute pairs. (Kernels 1.1.67 through 1.1.91 only. With kernel 1.1.92 or later, read from /dev/vcsa* instead.)
TIOCLINUX, subcode=9
Restore screen width and height, cursor position, and all the character-attribute pairs. (Kernels 1.1.67 through 1.1.91 only. With kernel 1.1.92 or later, write to /dev/vcsa* instead.)
TIOCLINUX, subcode=10
Handles the Power Saving feature of the new generation of monitors. VESA screen blanking mode is set to argp[1], which governs what screen blanking does:

0: Screen blanking is disabled.

1: The current video adapter register settings are saved, then the controller is programmed to turn off the vertical synchronization pulses. This puts the monitor into "standby" mode. If your monitor has an Off_Mode timer, then it will eventually power down by itself.

2: The current settings are saved, then both the vertical and horizontal synchronization pulses are turned off. This puts the monitor into "off" mode. If your monitor has no Off_Mode timer, or if you want your monitor to power down immediately when the blank_timer times out, then you choose this option. (Caution: Powering down frequently will damage the monitor.)

(Since 1.1.76.)

RETURN VALUE

On success, 0 is returned. On error -1 is returned, and errno is set.

ERRORS

errno may take on these values:
EBADF
The file descriptor is invalid.
ENOTTY
The file descriptor is not associated with a character special device, or the specified request does not apply to it.
EINVAL
The file descriptor or argp is invalid.
EPERM
Insufficient permission.

NOTES

Warning: Do not regard this man page as documentation of the Linux console ioctl's. This is provided for the curious only, as an alternative to reading the source. Ioctl's are undocumented Linux internals, liable to be changed without warning. (And indeed, this page more or less describes the situation as of kernel version 1.1.94; there are many minor and not-so-minor differences with earlier versions.)

Very often, ioctl's are introduced for communication between the kernel and one particular well-known program (fdisk, hdparm, setserial, tunelp, loadkeys, selection, setfont, etc.), and their behavior will be changed when required by this particular program.

Programs using these ioctl's will not be portable to other versions of Unix, will not work on older versions of Linux, and will not work on future versions of Linux.

Use POSIX functions.

SEE ALSO

dumpkeys(1), kbd_mode(1), loadkeys(1), mknod(1), setleds(1), setmetamode(1), execve(2), fcntl(2), ioperm(2), termios(3), console(4), console_codes(4), mt(4), sd(4), tty(4), tty_ioctl(4), ttyS(4), vcs(4), vcsa(4), charsets(7), mapscrn(8), resizecons(8), setfont(8), /usr/include/linux/kd.h, /usr/include/linux/vt.h


ram(4)

RAM

Section: Linux Programmer's Manual (4)
Updated: 1992-11-21 Return to Main Contents

NAME

ram - ram disk device

DESCRIPTION

The Ram device is a block device to access the ram disk in raw mode.

It is typically created by:

mknod -m 660 /dev/ram b 1 1
chown root:disk /dev/ram

FILES

/dev/ram

SEE ALSO

chown(1), mknod(1), mount(8)


urandom (4)

 Continue to this page.


wavelan(4)

WAVELAN

Section: Linux Programmer's Manual (4)
Updated: 1996-10-22 Return to Main Contents

NAME

wavelan - AT&T GIS WaveLAN ISA device driver

SYNOPSIS

insmod wavelan_cs.o [io=B,B..] [ irq=I,I..] [name=N,N..]

DESCRIPTION

wavelan is the low-level device driver for the NCR / AT&T / Lucent WaveLAN ISA and Digital (DEC) RoamAbout DS wireless ethernet adapter. This driver is available as a module or might be compiled in the kernel. This driver supports multiple cards in both forms (up to 4) and allocates the next available ethernet device (eth0..eth#) for each card found, unless a device name is explicitly specified (see below). This device name will be reported in the kernel log file with the MAC address, NWID and frequency used by the card.

Parameters

This section apply to the module form (parameters passed on the insmod(8) command line). If the driver is included in the kernel, use the ether=IRQ,IO,NAME syntax on the kernel command line.
io
Specify the list of base address where to search for wavelan cards (setting by dip switch on the card). If you don't specify any io address, the driver will scan 0x390 and 0x3E0 addresses, which might conflict with other hardware...
irq
Set the list of irq that each wavelan card should use (the value is saved in permanent storage for future use).
name
Set the list of name to be used for each wavelan cards device (name used by ifconfig(8)).

Wireless Extensions

Use iwconfig(8) to manipulate wireless extensions.

NWID (or domain)

Set the network ID [0 to FFFF] or disable it [off]. As the NWID is stored in the card Permanent Storage Area, it will be reuse at any further invocation of the driver.

Frequency & channels

For the 2.4GHz 2.00 Hardware, you are able to set the frequency by specifying one of the 10 defined channels (2.412, 2.422, 2.425, 2.4305, 2.432, 2.442, 2.452, 2.460, 2.462 or 2.484) or directly by its value. The frequency is changed immediately and permanently. Frequency availability depends on the regulations...

Statistics spy

Set a list of MAC addresses in the driver (up to 8) and get the last quality of link for each of those (see iwspy(8)).

/proc/net/wireless

status is the status reported by the modem. Link quality reports the quality of the modulation on the air (direct sequence spread spectrum) [max = 16]. Level and Noise refer to the signal level and noise level [max = 64]. The crypt discarded packet and misc discarded packet counters are not implemented.

Private Ioctl

You may use iwpriv(8) to manipulate private ioctls.

Quality and Level threshold

Enable you the define the quality and level threshold used by the modem (packet below that level are discarded).

Histogram

This functionality allow to set a number of signal level intervals and to count the number of packets received in each of those defined intervals. This distribution might be used to calculate the mean value and standard deviation of the signal level.

Specific Notes

This driver will fail to detect some non NCR/ATT&T/Lucent Wavelan cards. If this happens for you, you must look in the source code on how to add your card to the detection routine.

Some of the mentioned features are optional. You may enable to disable them by changing flags in the driver header and recompile.

SEE ALSO

wavelan_cs(4), ifconfig(8), insmod(8), iwconfig(8), iwspy(8), iwpriv(8)


futex (4)

 Continue to this page.


tty_ioctl(4)

TTY_IOCTL

Section: Linux Programmer's Manual (4)
Updated: 2002-12-29 Return to Main Contents

NAME

tty ioctl - ioctls for terminals and serial lines

SYNOPSIS

#include <termios.h>

int ioctl(int fd, int cmd, ...);

DESCRIPTION

The ioctl() call for terminals and serial ports accepts many possible command arguments. Most require a third argument, of varying type, here called argp or arg.

Use of ioctl makes for non-portable programs. Use the POSIX interface described in termios(3) whenever possible.

Get and Set Terminal Attributes

TCGETS        struct termios *argp
Equivalent to
tcgetattr(fd, argp).
Get the current serial port settings.
TCSETS const struct termios *argp
Equivalent to
tcsetattr(fd, TCSANOW, argp).
Set the current serial port settings.
TCSETSW        const struct termios *argp
Equivalent to
tcsetattr(fd, TCSADRAIN, argp).
Allow the output buffer to drain, and set the current serial port settings.
TCSETSF        const struct termios *argp
Equivalent to
tcsetattr(fd, TCSAFLUSH, argp).
Allow the output buffer to drain, discard pending input, and set the current serial port settings.

The following four ioctls are just like TCGETS, TCSETS, TCSETSW, TCSETSF, except that they take a struct termio * instead of a struct termios *.

TCGETA    struct termio *argp
TCSETA        const struct termio *argp
TCSETAW       const struct termio *argp
TCSETAF       const struct termio *argp

Locking the termios structure

The termios structure of a tty can be locked.
The lock is itself a termios structure, with non-zero bits or fields indicating a locked value.
TIOCGLCKTRMIOS struct termios *argp
Gets the locking status of the termios structure of
the terminal.
TIOCSLCKTRMIOS const struct termios *argp
Sets the locking status of the termios structure of
the terminal. Only root can do this.

Get and Set Window Size

Window sizes are kept in the kernel, but not used by the kernel (except in the case of virtual consoles, where the kernel will update the window size when the size of the virtual console changes, for example, by loading a new font).
TIOCGWINSZ     struct winsize *argp
Get window size.
TIOCSWINSZ     const struct winsize *argp
Set window size.

The struct used by these ioctls is defined as

struct winsize {
    unsigned short ws_row;
    unsigned short ws_col;
    unsigned short ws_xpixel;   /* unused */
    unsigned short ws_ypixel;   /* unused */
};

When the window size changes, a SIGWINCH signal is sent to the foreground process group.

Sending a Break

TCSBRK        int arg
Equivalent to
tcsendbreak(fd, arg).
If the terminal is using asynchronous serial data transmission, and arg is zero, then send a break (a stream of zero bits) for between 0.25 and 0.5 seconds. If the terminal is not using asynchronous serial data transmission, then either a break is sent, or the function returns without doing anything. When arg is non-zero, nobody knows what will happen.

(SVr4, UnixWare, Solaris, Linux treat tcsendbreak(fd,arg) with non-zero arg like tcdrain(fd). SunOS treats arg as a multiplier, and sends a stream of bits arg times as long as done for zero arg. DG/UX and AIX treat arg (when non-zero) as a timeinterval measured in milliseconds. HP-UX ignores arg.)

TCSBRKP int arg
So-called "POSIX version" of TCSBRK.
It treats non-zero arg as a timeinterval measured in deciseconds, and does nothing when the driver does not support breaks.
TIOCSBRK       void
Turn break on, that is, start sending zero bits.
TIOCCBRK       void
Turn break off, that is, stop sending zero bits.

Software flow control

TCXONC        int arg
Equivalent to
tcflow(fd, arg).
See tcflow(3) for the argument values TCOOFF, TCOON, TCIOFF, TCION.

Buffer count and flushing

FIONREAD      int *argp
Get the number of bytes in the input buffer.
TIOCINQ        int *argp
Same as FIONREAD.
TIOCOUTQ       int *argp
Get the number of bytes in the output buffer.
TCFLSH int arg
Equivalent to
tcflush(fd, arg).
See tcflush(3) for the argument values TCIFLUSH, TCOFLUSH, TCIOFLUSH.

Faking input

TIOCSTI       const char *argp
Insert the given byte in the input queue.

Redirecting console output

TIOCCONS      void
Redirect output that would have gone to
/dev/console or /dev/tty0 to the given tty. If that was a pty master, send it to the slave. Anybody can do this as long as the output was not redirected yet. If it was redirected already EBUSY is returned, but root may stop redirection by using this ioctl with fd pointing at /dev/console or /dev/tty0.

Controlling tty

TIOCSCTTY     int arg
Make the given tty the controlling tty of the current process.
The current process must be a session leader and not have a controlling tty already. If this tty is already the controlling tty of a different session group then the ioctl fails with EPERM, unless the caller is root and arg equals 1, in which case the tty is stolen, and all processes that had it as controlling tty lose it.
TIOCNOTTY void
If the given tty was the controlling tty of the current process, give up this controlling tty. If the process was session leader, then send SIGHUP and SIGCONT to the foreground process group and all processes in the current session lose their controlling tty.

Process group and session ID

TIOCGPGRP     pid_t *argp
When successful, equivalent to
*argp = tcgetpgrp(fd).
Get the process group ID of the foreground process group on this tty.
TIOCSPGRP      const pid_t *argp
Equivalent to
tcsetpgrp(fd, *argp).
Set the foreground process group ID of this tty.
TIOCGSID       pid_t *argp
Get the session ID of the given tty.
This will fail with ENOTTY in case the tty is not a master pty and not our controlling tty. Strange.

Exclusive mode

TIOCEXCL      void
Put the tty into exclusive mode.
No further open(2) operations on the terminal are permitted. (They will fail with EBUSY, except for root.)
TIOCNXCL       void
Disable exclusive mode.

Line discipline

TIOCGETD      int *argp
Get the line discipline of the tty.
TIOCSETD       const int *argp
Set the line discipline of the tty.

Pseudo-tty ioctls

TIOCPKT       const int *argp
Enable (when
*argp is non-zero) or disable packet mode. Can be applied to the master side of a pseudo-terminal only (and will return ENOTTY otherwise). In packet mode, each subsequent read(2) will return a packet that either contains a single non-zero control byte, or has a single byte containing zero ('' ') followed by data written on the slave side of the pty. If the first byte is not TIOCPKT_DATA (0), it is an OR of one or more of the following bits:

TIOCPKT_FLUSHREAD   The read queue for the terminal is flushed.
TIOCPKT_FLUSHWRITE  The write queue for the terminal is flushed.
TIOCPKT_STOP        Output to the terminal is stopped.
TIOCPKT_START       Output to the terminal is restarted.
TIOCPKT_DOSTOP      t_stopc is `^S' and t_startc is `^Q'.
TIOCPKT_NOSTOP      the start and stop characters are not `^S/^Q'.

While this mode is in use, the presence of control status information to be read from the master side may be detected by a select(2) for exceptional conditions.

This mode is used by rlogin(1) and rlogind(8) to implement a remote-echoed, locally `^S/^Q' flow-controlled remote login.

The BSD ioctls TIOCSTOP, TIOCSTART, TIOCUCNTL, TIOCREMOTE have not been implemented under Linux.

Modem control

TIOCMGET      int *argp
get the status of modem bits.
TIOCMSET       const int *argp
set the status of modem bits.
TIOCMBIC       const int *argp
clear the indicated modem bits.
TIOCMBIS       const int *argp
set the indicated modem bits.

Bits used by these four ioctls:

TIOCM_LE        DSR (data set ready/line enable)
TIOCM_DTR       DTR (data terminal ready)
TIOCM_RTS       RTS (request to send)
TIOCM_ST        Secondary TXD (transmit)
TIOCM_SR        Secondary RXD (receive)
TIOCM_CTS       CTS (clear to send)
TIOCM_CAR       DCD (data carrier detect)
TIOCM_CD         see TIOCM_CAR
TIOCM_RNG       RNG (ring)
TIOCM_RI         see TIOCM_RNG
TIOCM_DSR       DSR (data set ready)

Marking a line as local

TIOCGSOFTCAR  int *argp
("Get software carrier flag")
Get the status of the CLOCAL flag in the c_cflag field of the termios structure.
TIOCSSOFTCAR   const int *argp
("Set software carrier flag")
Set the CLOCAL flag in the termios structure when *argp is non-zero, and clear it otherwise.

If the CLOCAL flag for a line is off, the hardware carrier detect (DCD) signal is significant, and an open(2) of the corresponding tty will block until DCD is asserted, unless the O_NONBLOCK flag is given. If CLOCAL is set, the line behaves as if DCD is always asserted. The software carrier flag is usually turned on for local devices, and is off for lines with modems.

Linux specific

For the TIOCLINUX ioctl, see console_ioctl(4).

Kernel debugging

#include <linux/tty.h>

TIOCTTYGSTRUCT      struct tty_struct *argp
Get the tty_struct corresponding to
fd.

RETURN VALUE

The ioctl() system call returns 0 on success. On error it returns -1 and sets errno appropriately.

ERRORS

ENOIOCTLCMD
Unknown command.
EINVAL
Invalid command parameter.
EPERM
Insufficient permission.
ENOTTY
Inappropriate fd.

EXAMPLE

Check the condition of DTR on the serial port.

#include <termios.h>
#include <fcntl.h>
#include <sys/ioctl.h>

int
main(void)
{
    int fd, serial;

    fd = open("/dev/ttyS0", O_RDONLY);
    ioctl(fd, TIOCMGET, &serial);
    if (serial & TIOCM_DTR)
        puts("TIOCM_DTR is not set");
    else
        puts("TIOCM_DTR is set");
    close(fd);
}

SEE ALSO

ioctl(2), termios(3), console_ioctl(4), pty(7)


ptmx (4)

 Continue to this page.


pts(4)

PTS

Section: Linux Programmer's Manual (4)
Updated: 2002-10-09 Return to Main Contents

NAME

ptmx and pts - pseudo-terminal master and slave

DESCRIPTION

The file /dev/ptmx is a character file with major number 5 and minor number 2, usually of mode 0666 and owner.group of root.root. It is used to create a pseudo-terminal master and slave pair.

When a process opens /dev/ptmx, it gets a file descriptor for a pseudo-terminal master (PTM), and a pseudo-terminal slave (PTS) device is created in the /dev/pts directory. Each file descriptor obtained by opening /dev/ptmx is an independent PTM with its own associated PTS, whose path can be found by passing the descriptor to ptsname(3).

Before opening the pseudo-terminal slave, you must pass the master's file descriptor to grantpt(3) and unlockpt(3).

Once both the pseudo-terminal master and slave are open, the slave provides processes with an interface that is identical to that of a real terminal.

Data written to the slave is presented on the master descriptor as input. Data written to the master is presented to the slave as input.

In practice, pseudo-terminals are used for implementing terminal emulators such as xterm(1), in which data read from the pseudo-terminal master is interpreted by the application in the same way a real terminal would interpret the data, and for implementing remote-login programs such as sshd(8), in which data read from the pseudo-terminal master is sent across the network to a client program that is connected to a terminal or terminal emulator.

Pseudo-terminals can also be used to send input to programs that normally refuse to read input from pipes (such as su(8), and passwd(8)).

FILES

/dev/ptmx, /dev/pts/*

NOTES

The Linux support for the above (known as Unix98 pty naming) is done using the devpts filesystem, that should be mounted on /dev/pts.

Before this Unix98 scheme, master ptys were called /dev/ptyp0, ... and slave ptys /dev/ttyp0, ... and one needed lots of preallocated device nodes.

SEE ALSO

getpt(3), grantpt(3), ptsname(3), unlockpt(3), pty(7)


epoll (4)

 Continue to this page.


sk98lin(4)

SK98LIN

Section: Linux Programmer's Manual (4)
Updated: 2003-12-17 Return to Main Contents

NAME

sk98lin - Marvell/SysKonnect Gigabit Ethernet driver v6.21

SYNOPSIS

insmod sk98lin.o [Speed_A=i,j,...] [Speed_B=i,j,...] [AutoNeg_A=i,j,...] [AutoNeg_B=i,j,...] [DupCap_A=i,j,...] [DupCap_B=i,j,...] [FlowCtrl_A=i,j,...] [FlowCtrl_B=i,j,...] [Role_A=i,j,...] [Role_B=i,j,...] [ConType=i,j,...] [Moderation=i,j,...] [IntsPerSec=i,j,...] [PrefPort=i,j,...] [RlmtMode=i,j,...]

DESCRIPTION

sk98lin is the Gigabit Ethernet driver for Marvell and SysKonnect network adapter cards. It supports SysKonnect SK-98xx/SK-95xx compliant Gigabit Ethernet Adapter and any Yukon compliant chipset.

When loading the driver using insmod, parameters for the network adapter cards might be stated as a sequence of comma separated commands. If for instance two network adapters are installed and AutoNegotiation on Port A of the first adapter should be ON, but on the Port A of the second adapter switched OFF, one must enter:

insmod sk98lin.o AutoNeg_A=On,Off

After sk98lin is bound to one or more adapter cards and the /proc filesystem is mounted on your system, a dedicated statistics file will be created in folder /proc/net/sk98lin for all ports of the installed network adapter cards. Those files are named eth[x] whereas x is the number of the interface that has been assigned to a dedicated port by the system.

If loading is finished, any desired IP address can be assigned to the respective eth[x] interface using the ifconfig(8) command. This causes the adapter to connect to the Ethernet and to display a status message on the console saying "ethx: network connection up using port y" followed by the configured or detected connection parameters.

The sk98lin also supports large frames (also called jumbo frames). Using jumbo frames can improve throughput tremendously when transferring large amounts of data. To enable large frames, the MTU (maximum transfer unit) size for an interface is to be set to a high value. The default MTU size is 1500 and can be changed up to 9000 (bytes). Setting the MTU size can be done when assigning the IP address to the interface or later by using the ifconfig(8) command with the mtu parameter. If for instance eth0 needs an IP address and a large frame MTU size, the following two commands might be used:

ifconfig eth0 10.1.1.1
ifconfig eth0 mtu 9000

Those two commands might even be combined into one:

ifconfig eth0 10.1.1.1 mtu 9000

Note that large frames can only be used if your network infrastructure allows to do so. This means, that any switch being used in your Ethernet must also support large frames. Quite some switches support large frames, but need to be configured to do so. Most of the times, their default setting is to support only standard frames with an MTU size of 1500 (bytes). In addition to the switches inside the network, all network adapters that are to be used must also be enabled regarding jumbo frames. If an adapter is not set to receive large frames it will simply drop them.

Switching back to the standard Ethernet frame size can be done by using the ifconfig(8) command again:

ifconfig eth0 mtu 1500

The Marvell/SysKonnect Gigabit Ethernet driver for Linux is able to support VLAN and Link Aggregation according to IEEE standards 802.1, 802.1q, and 802.3ad. Those features are only available after installation of open source modules which can be found on the Internet:

VLAN: http://www.candelatech.com/~greear/vlan.html
Link Aggregation: http://www.st.rim.or.jp/~yumo

Note that Marvell/SysKonnect does not offer any support for these open source modules and does not take the responsibility for any kind of failures or problems arising when using these modules.

PARAMETERS

Speed_A=i,j,...
This parameter is used to set the speed capabilities of port A of an adapter card. It is only valid for Yukon copper adapters. Possible values are: 10, 100, 1000 or Auto whereas Auto is the default. Usually, the speed is negotiated between the two ports during link establishment. If this fails, a port can be forced to a specific setting with this parameter.
Speed_B=i,j,...
This parameter is used to set the speed capabilities of port B of an adapter card. It is only valid for Yukon copper adapters. Possible values are: 10, 100, 1000 or Auto whereas Auto is the default. Usually, the speed is negotiated between the two ports during link establishment. If this fails, a port can be forced to a specific setting with this parameter.
AutoNeg_A=i,j,...
Enables or disables the use of autonegotiation of port A of an adapter card. Possible values are: On, Off or Sense whereas On is the default. The Sense mode automatically detects whether the link partner supports auto-negotiation or not.
AutoNeg_B=i,j,...
Enables or disables the use of autonegotiation of port B of an adapter card. Possible values are: On, Off or Sense whereas On is the default. The Sense mode automatically detects whether the link partner supports auto-negotiation or not.
DupCap_A=i,j,...
This parameter indicates the duplex mode to be used for port A of an adapter card. Possible values are: Half, Full or Both whereas Both is the default. This parameter is only relevant if AutoNeg_A of port A is not set to Sense. If AutoNeg_A is set to On, all three values of DupCap_A ( Half, Full or Both) might be stated. If AutoNeg_A is set to Off, only DupCap_A values Full and Half are allowed. This DupCap_A parameter is useful if your link partner does not support all possible duplex combinations.
DupCap_B=i,j,...
This parameter indicates the duplex mode to be used for port B of an adapter card. Possible values are: Half, Full or Both whereas Both is the default. This parameter is only relevant if AutoNeg_B of port B is not set to Sense. If AutoNeg_B is set to On, all three values of DupCap_B ( Half, Full or Both) might be stated. If AutoNeg_B is set to Off, only DupCap_B values Full and Half are allowed. This DupCap_B parameter is useful if your link partner does not support all possible duplex combinations.
FlowCtrl_A=i,j,...
This parameter can be used to set the flow control capabilities the port reports during auto-negotiation. Possible values are: Sym, SymOrRem, LocSend or None whereas SymOrRem is the default. The different modes have the following meaning:

Sym = Symmetric
both link partners are allowed to send PAUSE frames
SymOrRem = SymmetricOrRemote
both or only remote partner are allowed to send PAUSE frames
LocSend = LocalSend
only local link partner is allowed to send PAUSE frames
None = None
no link partner is allowed to send PAUSE frames

Note that this parameter is ignored if AutoNeg_A is set to Off.

FlowCtrl_B=i,j,...
This parameter can be used to set the flow control capabilities the port reports during auto-negotiation. Possible values are: Sym, SymOrRem, LocSend or None whereas SymOrRem is the default. The different modes have the following meaning:

Sym = Symmetric
both link partners are allowed to send PAUSE frames
SymOrRem = SymmetricOrRemote
both or only remote partner are allowed to send PAUSE frames
LocSend = LocalSend
only local link partner is allowed to send PAUSE frames
None = None
no link partner is allowed to send PAUSE frames

Note that this parameter is ignored if AutoNeg_B is set to Off.

Role_A=i,j,...
This parameter is only valid for 1000Base-T adapter cards. For two 1000Base-T ports to communicate, one must take the role of the master (providing timing information), while the other must be the slave. Possible values are: Auto, Master or Slave whereas Auto is the default. Usually, the role of a port is negotiated between two ports during link establishment, but if that fails the port A of an adapter card can be forced to a specific setting with this parameter.
Role_B=i,j,...
This parameter is only valid for 1000Base-T adapter cards. For two 1000Base-T ports to communicate, one must take the role of the master (providing timing information), while the other must be the slave. Possible values are: Auto, Master or Slave whereas Auto is the default. Usually, the role of a port is negotiated between two ports during link establishment, but if that fails the port B of an adapter card can be forced to a specific setting with this parameter.
ConType=i,j,...
This parameter is a combination of all five per-port parameters within one single parameter. This simplifies the configuration of both ports of an adapter card. The different values of this variable reflect the most meaningful combinations of port parameters. Possible values and their corresponding combination of per-port parameters:

ConType | DupCap AutoNeg FlowCtrl Role Speed --------+-------------------------------------------
Auto
| Both On SymOrRem Auto Auto
100FD
| Full Off None Auto 100
100HD
| Half Off None Auto 100
10FD
| Full Off None Auto 10
10HD
| Half Off None Auto 10

Stating any other port parameter together with this ConType parameter will result in a merged configuration of those settings. This is due to the fact, that the per-port parameters (e.g. Speed_A) have a higher priority than the combined variable ConType.

Moderation=i,j,...
Interrupt moderation is employed to limit the maximum number of interrupts the driver has to serve. That is, one or more interrupts (which indicate any transmit or receive packet to be processed) are queued until the driver processes them. When queued interrupts are to be served, is determined by the IntsPerSec parameter, which is explained later below. Possible moderation modes are: None, Static or Dynamic whereas None is the default. The different modes have the following meaning:

None No interrupt moderation is applied on the adapter card. Therefore, each transmit or receive interrupt is served immediately as soon as it appears on the interrupt line of the adapter card.

Static Interrupt moderation is applied on the adapter card. All transmit and receive interrupts are queued until a complete moderation interval ends. If such a moderation interval ends, all queued interrupts are processed in one big bunch without any delay. The term Static reflects the fact, that interrupt moderation is always enabled, regardless how much network load is currently passing via a particular interface. In addition, the duration of the moderation interval has a fixed length that never changes while the driver is operational.

Dynamic Interrupt moderation might be applied on the adapter card, depending on the load of the system. If the driver detects that the system load is too high, the driver tries to shield the system against too much network load by enabling interrupt moderation. If --- at a later time --- the CPU utilization decreases again (or if the network load is negligible) the interrupt moderation will automatically be disabled.

Interrupt moderation should be used when the driver has to handle one or more interfaces with a high network load, which --- as a consequence --- leads also to a high CPU utilization. When moderation is applied in such high network load situations, CPU load might be reduced by 20-30% on slow computers.

Note that the drawback of using interrupt moderation is an increase of the round-trip-time (RTT), due to the queuing and serving of interrupts at dedicated moderation times.

IntsPerSec=i,j,...
This parameter determines the length of any interrupt moderation interval. Assuming that static interrupt moderation is to be used, an IntsPerSec parameter value of 2000 will lead to an interrupt moderation interval of 500 microseconds. Possible values for this parameter are in the range of 30...40000 (interrupts per second). The default value is 2000.

This parameter is only used, if either static or dynamic interrupt moderation is enabled on a network adapter card. This parameter is ignored if no moderation is applied.

Note that the duration of the moderation interval is to be chosen with care. At first glance, selecting a very long duration (e.g., only 100 interrupts per second) seems to be meaningful, but the increase of packet-processing delay is tremendous. On the other hand, selecting a very short moderation time might compensate the use of any moderation being applied.

PrefPort=i,j,...
This parameter is used to force the preferred port to A or B (on dual-port network adapters). The preferred port is the one that is used if both ports A and B are detected as fully functional. Possible values are: A or B whereas A is the default.
RlmtMode=i,j,...
RLMT monitors the status of the port. If the link of the active port fails, RLMT switches immediately to the standby link. The virtual link is maintained as long as at least one 'physical' link is up. This parameters states how RLMT should monitor both ports. Possible values are: CheckLinkState, CheckLocalPort, CheckSeg or DualNet whereas CheckLinkState is the default. The different modes have the following meaning:

CheckLinkState Check link state only: RLMT uses the link state reported by the adapter hardware for each individual port to determine whether a port can be used for all network traffic or not.

CheckLocalPort In this mode, RLMT monitors the network path between the two ports of an adapter by regularly exchanging packets between them. This mode requires a network configuration in which the two ports are able to "see" each other (i.e., there must not be any router between the ports).

CheckSeg Check local port and segmentation: This mode supports the same functions as the CheckLocalPort mode and additionally checks network segmentation between the ports. Therefore, this mode is only to be used if Gigabit Ethernet switches are installed on the network that have been configured to use the Spanning Tree protocol.

DualNet In this mode, ports A and B are used as separate devices. If you have a dual port adapter, port A will be configured as eth[x]andportBas eth[x+1]. Both ports can be used independently with distinct IP addresses. The preferred port setting is not used. RLMT is turned off.

Note that RLMT modes CheckLocalPort and CheckLinkState are designed to operate in configurations where a network path between the ports on one adapter exists. Moreover, they are not designed to work where adapters are connected back-to-back.

FILES

/proc/net/sk98lin/eth[x]

The statistics file of a particular interface of an adapter card. It contains generic information about the adapter card plus a detailed summary of all transmit and receive counters.
/usr/src/linux/Documentation/network/sk98lin.txt

This is the README file of the sk98lin driver. It contains a detailed installation HOWTO and describes all parameters of the driver. It denotes also common problems and provides the solution to them.

BUGS

Report any bugs to linux@syskonnect.de

SEE ALSO

modprobe(8), insmod(8), ifconfig(8)


rtc(4)

RTC

Section: Linux Programmer's Manual (4)
Updated: 2006-11-26 Return to Main Contents

NAME

rtc - real-time clock

SYNOPSIS

#include <linux/rtc.h>

int ioctl(fd, RTC_request, param);

DESCRIPTION

This is the interface to drivers for real-time clocks (RTCs).

Most computers have one or more hardware clocks which record the current "wall clock" time. These are called "Real Time Clocks" (RTCs). One of these usually has battery backup power so that it tracks the time even while the computer is turned off. RTCs often provide alarms and other interrupts.

All x86 PCs, and ACPI based systems, have an RTC that is compatible with the Motorola MC146818 chip on the original PC/AT. Today such an RTC is usually integrated into the mainboard's chipset (south bridge), and uses a replaceable coin-sized backup battery.

Non-PC systems, such as embedded systems built around system-on-chip processors, use other implementations. They usually won't offer the same functionality as the RTC from a PC/AT.

RTC vs System Clock

RTCs should not be confused with the system clock, which is a software clock maintained by the kernel and used to implement gettimeofday(2) and time(2), as well as setting timestamps on files, etc. The system clock reports seconds and microseconds since a start point, defined to be the POSIX Epoch: Jan 1, 1970, 0:00 UTC. (One common implementation counts timer interrupts, once per "jiffy", at a frequency of 100, 250, or 1000 Hz.) That is, it is supposed to report wall clock time, which RTCs also do.

A key difference between an RTC and the system clock is that RTCs run even when the system is in a low power state (including "off"), and the system clock can't. Until it is initialized, the system clock can only report time since system boot ... not since the POSIX Epoch. So at boot time, and after resuming from a system low power state, the system clock will often be set to the current wall clock time using an RTC. Systems without an RTC need to set the system clock using another clock, maybe across the network or by entering that data manually.

RTC functionality

RTCs can be read and written with hwclock(8), or directly with the ioctl requests listed below.

Besides tracking the date and time, many RTCs can also generate interrupts

*
on every clock update (i.e., once per second);
*
at periodic intervals with a frequency that can be set to any power-of-2 multiple in the range 2 Hz to 8192 Hz;
*
on reaching a previously specified alarm time.

Each of those interrupt sources can be enabled or disabled separately. On many systems, the alarm interrupt can be configured as a system wakeup event, which can resume the system from a low power state such as Suspend-to-RAM (STR, called S3 in ACPI systems), Hibernation (called S4 in ACPI systems), or even "off" (called S5 in ACPI systems). On some systems, the battery backed RTC can't issue interrupts, but another one can.

The /dev/rtc (or /dev/rtc0, /dev/rtc1, etc) device can be opened only once (until it is closed) and it is read-only. On read(2) and select(2) the calling process is blocked until the next interrupt from that RTC is received. Following the interrupt, the process can read a long integer, of which the least significant byte contains a bit mask encoding the types of interrupt that occurred, while the remaining 3 bytes contain the number of interrupts since the last read(2).

ioctl(2) interface

The following ioctl(2) requests are defined on file descriptors connected to RTC devices:
RTC_RD_TIME
Returns this RTC's time in the following structure:

struct rtc_time {
    int tm_sec;
    int tm_min;
    int tm_hour;
    int tm_mday;
    int tm_mon;
    int tm_year;
    int tm_wday;     /* unused */
    int tm_yday;     /* unused */
    int tm_isdst;    /* unused */
};
The fields in this structure have the same meaning and ranges as for the tm structure described in gmtime(3). A pointer to this structure should be passed as the third ioctl(2) argument.
RTC_SET_TIME
Sets this RTC's time to the time specified by the rtc_time structure pointed to by the third ioctl(2) argument. To set the RTC's time the process must be privileged (i.e., have the CAP_SYS_TIME capability).
RTC_ALM_READ, RTC_ALM_SET
Read and set the alarm time, for RTCs that support alarms. The alarm interrupt must be separately enabled or disabled using the RTC_AIE_ON, RTC_AIE_OFF requests. The third ioctl(2) argument is a pointer to an rtc_time structure. Only the tm_sec, tm_min, and tm_hour fields of this structure are used.
RTC_IRQP_READ, RTC_IRQP_SET
Read and set the frequency for periodic interrupts, for RTCs that support periodic interrupts. The periodic interrupt must be separately enabled or disabled using the RTC_PIE_ON, RTC_PIE_OFF requests. The third ioctl(2) argument is a unsigned long * or a unsigned long, respectively. The value is the frequency in interrupts per second. The set of allowable frequencies is the multiples of two in the range 2 to 8192. Only a privileged process (i.e., one having the CAP_SYS_RESOURCE capability) can set frequencies above the value specified in /proc/sys/dev/rtc/max-user-freq. (This file contains the value 64 by default.)
RTC_AIE_ON, RTC_AIE_OFF
Enable or disable the alarm interrupt, for RTCs that support alarms. The third ioctl(2) argument is ignored.
RTC_UIE_ON, RTC_UIE_OFF
Enable or disable the interrupt on every clock update, for RTCs that support this once-per-second interrupt. The third ioctl(2) argument is ignored.
RTC_PIE_ON, RTC_PIE_OFF
Enable or disable the periodic interrupt, for RTCs that support these periodic interrupts. The third ioctl(2) argument is ignored. Only a privileged process (i.e., one having the CAP_SYS_RESOURCE capability) can enable the periodic interrupt if the frequency is currently set above the value specified in /proc/sys/dev/rtc/max-user-freq.
RTC_EPOCH_READ, RTC_EPOCH_SET
Many RTCs encode the year in an 8-bit register which is either interpreted as an 8-bit binary number or as a BCD number. In both cases, the number is interpreted relative to this RTC's Epoch. The RTC's Epoch is initialized to 1900 on most systems but on Alpha and MIPS it might also be initialized to 1952, 1980, or 2000, depending on the value of an RTC register for the year. With some RTCs, these operations can be used to read or to set the RTC's Epoch, respectively. The third ioctl(2) argument is a unsigned long * or a unsigned long, respectively, and the value returned (or assigned) is the epoch. To set the RTC's Epoch the process must be privileged (i.e., have the CAP_SYS_TIME capability).
RTC_WKALM_RD, RTC_WKALM_SET
Some RTCs support a more powerful alarm interface, using these ioctls to read or write the RTC's alarm time (respectively) with this structure:

struct rtc_wkalrm {
    unsigned char enabled;
    unsigned char pending;
    struct rtc_time time;
};
The enabled flag is used to enable or disable the alarm interrupt, or to read its current status; when using these calls, RTC_AIE_ON and RTC_AIE_OFF are not used. The pending flag is used by RTC_WKALM_RD to report a pending interrupt (so it's mostly useless on Linux, except when talking to the RTC managed by EFI firmware). The time field is as used with RTC_ALM_READ and RTC_ALM_SET except that the tm_mday, tm_mon, and tm_year fields are also valid. A pointer to this structure should be passed as the third ioctl(2) argument.

FILES

/dev/rtc, /dev/rtc0, /dev/rtc1, etc: RTC special character device files.

/proc/driver/rtc: status of the (first) RTC.

NOTES

When the kernel's system time is synchronized with an external reference using adjtimex(2) it will update a designated RTC periodically every 11 minutes. To do so, the kernel has to briefly turn off periodic interrupts; this might affect programs using that RTC.

An RTC's Epoch has nothing to do with the POSIX Epoch which is only used for the system clock.

If the year according to the RTC's Epoch and the year register is less than 1970 it is assumed to be 100 years later, that is, between 2000 and 2069.

Some RTCs support "wildcard" values in alarm fields, to support scenarios like periodic alarms at fifteen minutes after every hour, or on the first day of each month. Such usage is non portable; portable user space code only expects a single alarm interrupt, and will either disable or reinitialize the alarm after receiving it.

Some RTCs support periodic interrupts with periods that are multiples of a second rather than fractions of a second; multiple alarms; programmable output clock signals; non-volatile memory; and other hardware capabilities that are not currently exposed by this API.

SEE ALSO

hwclock(8), date(1), time(2), stime(2), gettimeofday(2), settimeofday(2), adjtimex(2), gmtime(3), time(7), /usr/src/linux/Documentation/rtc.txt


motd(5)

MOTD

Section: Linux Programmer's Manual (5)
Updated: 1992-12-29 Return to Main Contents

NAME

motd - message of the day

DESCRIPTION

The contents of /etc/motd are displayed by login(1) after a successful login but just before it executes the login shell.

The abbreviation "motd" stands for "message of the day", and this file has been traditionally used for exactly that (it requires much less disk space than mail to all users).

FILES

/etc/motd

SEE ALSO

login(1), issue(5)


fs(5)

FILESYSTEMS

Section: Linux Programmer's Manual (5)
Updated: 2001-12-07 Return to Main Contents

NAME

filesystems - Linux filesystem types: minix, ext, ext2, ext3, xia, msdos, umsdos, vfat, proc, nfs, iso9660, hpfs, sysv, smb, ncpfs

DESCRIPTION

When, as is customary, the proc filesystem is mounted on /proc, you can find in the file /proc/filesystems which filesystems your kernel currently supports. If you need a currently unsupported one, insert the corresponding module or recompile the kernel.

In order to use a filesystem, you have to mount it, see mount(8) for the mount command, and for the available mount options.

Below a short description of a few of the available filesystems.

minix
is the filesystem used in the Minix operating system, the first to run under Linux. It has a number of shortcomings: a 64MB partition size limit, short filenames, a single time stamp, etc. It remains useful for floppies and RAM disks.
ext
is an elaborate extension of the minix filesystem. It has been completely superseded by the second version of the extended filesystem (ext2) and has been removed from the kernel (in 2.1.21).
ext2
is the high performance disk filesystem used by Linux for fixed disks as well as removable media. The second extended filesystem was designed as an extension of the extended file system (ext). ext2 offers the best performance (in terms of speed and CPU usage) of the filesystems supported under Linux.
ext3
is a journaling version of the ext2 filesystem. It is easy to switch back and forth between ext2 and ext3.
xiafs
was designed and implemented to be a stable, safe filesystem by extending the Minix filesystem code. It provides the basic most requested features without undue complexity. The xia filesystem is no longer actively developed or maintained. It was removed from the kernel in 2.1.21.
msdos
is the filesystem used by DOS, Windows, and some OS/2 computers. msdos filenames can be no longer than 8 characters, followed by an optional period and 3 character extension.
umsdos
is an extended DOS filesystem used by Linux. It adds capability for long filenames, UID/GID, POSIX permissions, and special files (devices, named pipes, etc.) under the DOS filesystem, without sacrificing compatibility with DOS.
vfat
is an extended DOS filesystem used by Microsoft Windows95 and Windows NT. VFAT adds the capability to use long filenames under the MSDOS filesystem.
proc
is a pseudo-filesystem which is used as an interface to kernel data structures rather than reading and interpreting /dev/kmem. In particular, its files do not take disk space. See proc(5).
iso9660
is a CD-ROM filesystem type conforming to the ISO 9660 standard.
High Sierra
Linux supports High Sierra, the precursor to the ISO 9660 standard for CD-ROM filesystems. It is automatically recognized within the iso9660 filesystem support under Linux.
Rock Ridge
Linux also supports the System Use Sharing Protocol records specified by the Rock Ridge Interchange Protocol. They are used to further describe the files in the iso9660 filesystem to a UNIX host, and provide information such as long filenames, UID/GID, POSIX permissions, and devices. It is automatically recognized within the iso9660 filesystem support under Linux.
hpfs
is the High Performance Filesystem, used in OS/2. This filesystem is read-only under Linux due to the lack of available documentation.
sysv
is an implementation of the SystemV/Coherent filesystem for Linux. It implements all of Xenix FS, SystemV/386 FS, and Coherent FS.
nfs
is the network filesystem used to access disks located on remote computers.
smb
is a network filesystem that supports the SMB protocol, used by Windows for Workgroups, Windows NT, and Lan Manager.

To use smb fs, you need a special mount program, which can be found in the ksmbfs package, found at ftp://sunsite.unc.edu/pub/Linux/system/Filesystems/smbfs.

ncpfs
is a network filesystem that supports the NCP protocol, used by Novell NetWare.

To use ncpfs, you need special programs, which can be found at ftp://linux01.gwdg.de/pub/ncpfs.

SEE ALSO

proc(5), fsck(8), mkfs(8), mount(8)


securetty(5)

SECURETTY

Section: Linux Programmer's Manual (5)
Updated: 1992-12-29 Return to Main Contents

NAME

securetty - file which lists ttys from which root can log in

DESCRIPTION

The file /etc/securetty is used by (some versions of) login(1). The file contains the device names of tty lines (one per line, without leading /dev/) on which root is allowed to login. See login.defs(5) if you use the shadow suite.

FILES

/etc/securetty

SEE ALSO

login(1), login.defs(5)


tzfile(5)

TZFILE

Section: Linux Programmer's Manual (5)
Updated: 1996-06-05 Return to Main Contents

NAME

tzfile - time zone information

SYNOPSIS

#include <tzfile.h>

DESCRIPTION

The time zone information files used by tzset(3) begin with the magic characters "TZif" to identify then as time zone information files, followed by sixteen bytes reserved for future use, followed by six four-byte values of type long, written in a ``standard'' byte order (the high-order byte of the value is written first). These values are, in order:
tzh_ttisgmtcnt
The number of UTC/local indicators stored in the file.
tzh_ttisstdcnt
The number of standard/wall indicators stored in the file.
tzh_leapcnt
The number of leap seconds for which data is stored in the file.
tzh_timecnt
The number of "transition times" for which data is stored in the file.
tzh_typecnt
The number of "local time types" for which data is stored in the file (must not be zero).
tzh_charcnt
The number of characters of "time zone abbreviation strings" stored in the file.

The above header is followed by tzh_timecnt four-byte values of type long, sorted in ascending order. These values are written in ``standard'' byte order. Each is used as a transition time (as returned by time(2)) at which the rules for computing local time change. Next come tzh_timecnt one-byte values of type unsigned char; each one tells which of the different types of ``local time'' types described in the file is associated with the same-indexed transition time. These values serve as indices into an array of ttinfo structures that appears next in the file; these structures are defined as follows:

struct ttinfo {
    long         tt_gmtoff;
    int          tt_isdst;
    unsigned int tt_abbrind;
};

Each structure is written as a four-byte value for tt_gmtoff of type long, in a standard byte order, followed by a one-byte value for tt_isdst and a one-byte value for tt_abbrind. In each structure, tt_gmtoff gives the number of seconds to be added to UTC, tt_isdst tells whether tm_isdst should be set by localtime(3), and tt_abbrind serves as an index into the array of time zone abbreviation characters that follow the ttinfo structure(s) in the file.

Then there are tzh_leapcnt pairs of four-byte values, written in standard byte order; the first value of each pair gives the time (as returned by time(2)) at which a leap second occurs; the second gives the total number of leap seconds to be applied after the given time. The pairs of values are sorted in ascending order by time.

Then there are tzh_ttisstdcnt standard/wall indicators, each stored as a one-byte value; they tell whether the transition times associated with local time types were specified as standard time or wall clock time, and are used when a time zone file is used in handling POSIX-style time zone environment variables.

Finally, there are tzh_ttisgmtcnt UTC/local indicators, each stored as a one-byte value; they tell whether the transition times associated with local time types were specified as UTC or local time, and are used when a time zone file is used in handling POSIX-style time zone environment variables.

Localtime uses the first standard-time ttinfo structure in the file (or simply the first ttinfo structure in the absence of a standard-time structure) if either tzh_timecnt is zero or the time argument is less than the first transition time recorded in the file.


group(5)

GROUP

Section: Linux Programmer's Manual (5)
Updated: 1992-12-29 Return to Main Contents

NAME

group - user group file

DESCRIPTION

/etc/group is an ASCII file which defines the groups to which users belong. There is one entry per line, and each line has the format:

group_name:passwd:GID:user_list

The field descriptions are:

group_name
the name of the group.
password
the (encrypted) group password. If this field is empty, no password is needed.
GID
the numerical group ID.
user_list
all the group member's user names, separated by commas.

FILES

/etc/group

BUGS

As the 4.2BSD initgroups(3) man page says: No-one seems to keep /etc/group up-to-date.

SEE ALSO

login(1), newgrp(1), passwd(5)


issue(5)

ISSUE

Section: Linux Programmer's Manual (5)
Updated: 1993-07-24 Return to Main Contents

NAME

issue - pre-login message and identification file

DESCRIPTION

The file /etc/issue is a text file which contains a message or system identification to be printed before the login prompt. It may contain various @char and \char sequences, if supported by the getty-type program employed on the system.

FILES

/etc/issue

SEE ALSO

motd(5), mingetty(8)


dir_colors(5)

DIR_COLORS

Section: Linux User Manual (5)
Updated: 2001-12-26 Return to Main Contents

NAME

dir_colors - configuration file for dircolors(1)

DESCRIPTION

The program ls(1) uses the environment variable LS_COLORS to determine the colors in which the filenames are to be displayed. This environment variable is usually set by a command like

eval `dircolors some_path/dir_colors`

found in a system default shell initialization file, like /etc/profile or /etc/csh.cshrc. (See also dircolors(1).) Usually, the file used here is /etc/DIR_COLORS and can be overridden by a .dir_colors file in one's home directory.

This configuration file consists of several statements, one per line. Anything right of a hash mark (#) is treated as a comment, if the hash mark is at the beginning of a line or is preceded by at least one whitespace. Blank lines are ignored.

The global section of the file consists of any statement before the first TERM statement. Any statement in the global section of the file is considered valid for all terminal types. Following the global section is one or more terminal-specific sections, preceded by one or more TERM statements which specify the terminal types (as given by the TERM environment variable) the following declarations apply to. It is always possible to override a global declaration by a subsequent terminal-specific one.

The following statements are recognized; case is insignificant:

TERM terminal-type
Starts a terminal-specific section and specifies which terminal it applies to. Multiple TERM statements can be used to create a section which applies for several terminal types.
COLOR yes|all|no|none|tty
(Slackware only; ignored by GNU dircolors(1).) Specifies that colorization should always be enabled (yes or all), never enabled (no or none), or enabled only if the output is a terminal (tty). The default is no.
EIGHTBIT yes|no
(Slackware only; ignored by GNU dircolors(1).) Specifies that eight-bit ISO 8859 characters should be enabled by default. For compatibility reasons, this can also be specified as 1 for yes or 0 for no. The default is no.
OPTIONS options
(Slackware only; ignored by GNU dircolors(1).) Adds command line options to the default ls command line. The options can be any valid ls command line options, and should include the leading minus sign. Please note that dircolors does not verify the validity of these options.
NORMAL color-sequence
Specifies the color used for normal (non-filename) text.
FILE color-sequence
Specifies the color used for a regular file.
DIR color-sequence
Specifies the color used for directories.
LINK color-sequence
Specifies the color used for a symbolic link.
ORPHAN color-sequence
Specifies the color used for an orphaned symbolic link (one which points to a nonexistent file). If this is unspecified, ls will use the LINK color instead.
MISSING color-sequence
Specifies the color used for a missing file (a nonexistent file which nevertheless has a symbolic link pointing to it). If this is unspecified, ls will use the FILE color instead.
FIFO color-sequence
Specifies the color used for a FIFO (named pipe).
SOCK color-sequence
Specifies the color used for a socket.
DOOR color-sequence
(Supported since fileutils 4.1) Specifies the color used for a door (Solaris 2.5 and later).
BLK color-sequence
Specifies the color used for a block device special file.
CHR color-sequence
Specifies the color used for a character device special file.
EXEC color-sequence
Specifies the color used for a file with the executable attribute set.
LEFTCODE color-sequence
Specifies the left code for non-ISO 6429 terminals (see below).
RIGHTCODE color-sequence
Specifies the right code for non-ISO 6429 terminals (see below).
ENDCODE color-sequence
Specifies the end code for non-ISO 6429 terminals (see below).
*extension color-sequence
Specifies the color used for any file that ends in extension.
.extension color-sequence
Same as *.extension. Specifies the color used for any file that ends in .extension. Note that the period is included in the extension, which makes it impossible to specify an extension not starting with a period, such as ~ for emacs backup files. This form should be considered obsolete.

ISO 6429 (ANSI) Color Sequences

Most color-capable ASCII terminals today use ISO 6429 (ANSI) color sequences, and many common terminals without color capability, including xterm and the widely used and cloned DEC VT100, will recognize ISO 6429 color codes and harmlessly eliminate them from the output or emulate them. ls uses ISO 6429 codes by default, assuming colorization is enabled.

ISO 6429 color sequences are composed of sequences of numbers separated by semicolons. The most common codes are:

 0     to restore default color
 1     for brighter colors
 4     for underlined text
 5     for flashing text
30     for black foreground
31     for red foreground
32     for green foreground
33     for yellow (or brown) foreground
34     for blue foreground
35     for purple foreground
36     for cyan foreground
37     for white (or gray) foreground
40     for black background
41     for red background
42     for green background
43     for yellow (or brown) background
44     for blue background
45     for purple background
46     for cyan background
47     for white (or gray) background

Not all commands will work on all systems or display devices.

ls uses the following defaults:

NORMAL   0       Normal (non-filename) text
FILE     0       Regular file
DIR      32      Directory
LINK     36      Symbolic link
ORPHAN   undefined       Orphaned symbolic link
MISSING  undefined       Missing file
FIFO     31      Named pipe (FIFO)
SOCK     33      Socket
BLK      44;37   Block device
CHR      44;37   Character device
EXEC     35      Executable file

A few terminal programs do not recognize the default properly. If all text gets colorized after you do a directory listing, change the NORMAL and FILE codes to the numerical codes for your normal foreground and background colors.

Other Terminal Types (Advanced Configuration)

If you have a color-capable (or otherwise highlighting) terminal (or printer!) which uses a different set of codes, you can still generate a suitable setup. To do so, you will have to use the LEFTCODE, RIGHTCODE, and ENDCODE definitions.

When writing out a filename, ls generates the following output sequence: LEFTCODE typecode RIGHTCODE filename ENDCODE, where the typecode is the color sequence that depends on the type or name of file. If the ENDCODE is undefined, the sequence LEFTCODE NORMAL RIGHTCODE will be used instead. The purpose of the left- and rightcodes is merely to reduce the amount of typing necessary (and to hide ugly escape codes away from the user). If they are not appropriate for your terminal, you can eliminate them by specifying the respective keyword on a line by itself.

NOTE: If the ENDCODE is defined in the global section of the setup file, it cannot be undefined in a terminal-specific section of the file. This means any NORMAL definition will have no effect. A different ENDCODE can, however, be specified, which would have the same effect.

Escape Sequences

To specify control- or blank characters in the color sequences or filename extensions, either C-style \-escaped notation or stty-style ^-notation can be used. The C-style notation includes the following characters:

\a      Bell (ASCII 7)
\b      Backspace (ASCII 8)
\e      Escape (ASCII 27)
\f      Form feed (ASCII 12)
\n      Newline (ASCII 10)
\r      Carriage Return (ASCII 13)
\t      Tab (ASCII 9)
\v      Vertical Tab (ASCII 11)
\?      Delete (ASCII 127)
\nnn Any character (octal notation)
\xnnn        Any character (hexadecimal notation)
\_      Space
\\     Backslash (\)
\^      Caret (^)
\#      Hash mark (#)

Please note that escapes are necessary to enter a space, backslash, caret, or any control character anywhere in the string, as well as a hash mark as the first character.

FILES

/etc/DIR_COLORS
System-wide configuration file.
~/.dir_colors
Per-user configuration file.

This page describes the dir_colors file format as used in the fileutils-4.1 package; other versions may differ slightly.

NOTES

The default LEFTCODE and RIGHTCODE definitions, which are used by ISO 6429 terminals are:

LEFTCODE  \e[
RIGHTCODE m

The default ENDCODE is undefined.

SEE ALSO

dircolors(1), ls(1), stty(1), xterm(1)


rpc(5)

RPC

Section: Linux Programmer's Manual (5)
Updated: 1985-09-26 Return to Main Contents

NAME

rpc - rpc program number data base

SYNOPSIS

/etc/rpc

DESCRIPTION

The rpc file contains user readable names that can be used in place of rpc program numbers. Each line has the following information:
name of server for the rpc program
rpc program number
aliases

Items are separated by any number of blanks and/or tab characters. A '#' indicates the beginning of a comment; characters from the '#' to the end of the line are not interpreted by routines which search the file.

Here is an example of the /etc/rpc file from the Sun RPC Source distribution.

#
# rpc 88/08/01 4.0 RPCSRC; from 1.12   88/02/07 SMI
#
portmapper          100000    portmap sunrpc
rstatd              100001    rstat rstat_svc rup perfmeter
rusersd             100002    rusers
nfs                 100003    nfsprog
ypserv              100004    ypprog
mountd              100005    mount showmount
ypbind              100007
walld               100008    rwall shutdown
yppasswdd           100009    yppasswd
etherstatd          100010    etherstat
rquotad             100011    rquotaprog quota rquota
sprayd              100012    spray
3270_mapper         100013
rje_mapper          100014
selection_svc       100015    selnsvc
database_svc        100016
rexd                100017    rex
alis                100018
sched               100019
llockmgr            100020
nlockmgr            100021
x25.inr             100022
statmon             100023
status              100024
bootparam           100026
ypupdated           100028    ypupdate
keyserv             100029    keyserver
tfsd                100037
nsed                100038
nsemntd             100039

FILES

/etc/rpc
rpc program number data base

SEE ALSO

getrpcent(3)


ttytype(5)

TTYTYPE

Section: Linux Programmer's Manual (5)
Updated: 1993-07-24 Return to Main Contents

NAME

ttytype - terminal device to default terminal type mapping

DESCRIPTION

The /etc/ttytype file associates termcap/terminfo terminal type names with tty lines. Each line consists of a terminal type, followed by whitespace, followed by a tty name (a device name without the /dev/) prefix.

This association is used by the program tset(1) to set the environment variable TERM to the default terminal name for the user's current tty.

This facility was designed for a traditional time-sharing environment featuring character-cell terminals hardwired to a Unix minicomputer. It is little used on modern workstation and personal Unixes.

FILES

/etc/ttytype
the tty definitions file.

EXAMPLE

A typical /etc/ttytype is:

con80x25 tty1
vt320 ttys0

SEE ALSO

termcap(5), terminfo(5) mingetty(8)


utmp(5)

UTMP

Section: Linux Programmer's Manual (5)
Updated: 2004-10-31 Return to Main Contents

NAME

utmp, wtmp - login records

SYNOPSIS

#include <utmp.h>

DESCRIPTION

The utmp file allows one to discover information about who is currently using the system. There may be more users currently using the system, because not all programs use utmp logging.

Warning: utmp must not be writable, because many system programs (foolishly) depend on its integrity. You risk faked system logfiles and modifications of system files if you leave utmp writable to any user.

The file is a sequence of entries with the following structure declared in the include file (note that this is only one of several definitions around; details depend on the version of libc):

#define UT_UNKNOWN      0
#define RUN_LVL         1
#define BOOT_TIME       2
#define NEW_TIME        3
#define OLD_TIME        4
#define INIT_PROCESS    5
#define LOGIN_PROCESS   6
#define USER_PROCESS    7
#define DEAD_PROCESS    8
#define ACCOUNTING      9

#define UT_LINESIZE     12
#define UT_NAMESIZE     32
#define UT_HOSTSIZE     256

struct exit_status {
    short int e_termination;    /* process termination status */
    short int e_exit;           /* process exit status */
};

struct utmp {
    short ut_type;              /* type of login */
    pid_t ut_pid;               /* PID of login process */
    char ut_line[UT_LINESIZE];  /* device name of tty - "/dev/" */
    char ut_id[4];              /* init id or abbrev. ttyname */
    char ut_user[UT_NAMESIZE];  /* user name */
    char ut_host[UT_HOSTSIZE];  /* hostname for remote login */
    struct exit_status ut_exit; /* The exit status of a process
                                   marked as DEAD_PROCESS */

    /* The ut_session and ut_tv fields must be the same size when
       compiled 32- and 64-bit.  This allows data files and shared
       memory to be shared between 32- and 64-bit applications */
#if __WORDSIZE == 64 && defined __WORDSIZE_COMPAT32
    int32_t ut_session;         /* Session ID, used for windowing */
    struct {
        int32_t tv_sec;         /* Seconds */
        int32_t tv_usec;        /* Microseconds */
    } ut_tv;                    /* Time entry was made */
#else
     long int ut_session;        /* Session ID, used for windowing */
     struct timeval ut_tv;       /* Time entry was made */
#endif

    int32_t ut_addr_v6[4];       /* IP address of remote host */
    char __unused[20];           /* Reserved for future use */
};

/* Backwards compatibility hacks.  */
#define ut_name ut_user
#ifndef _NO_UT_TIME
#define ut_time ut_tv.tv_sec
#endif
#define ut_xtime ut_tv.tv_sec
#define ut_addr ut_addr_v6[0]
This structure gives the name of the special file associated with the user's terminal, the user's login name, and the time of login in the form of time(2). String fields are terminated by '\0' if they are shorter than the size of the field.

The first entries ever created result from init(8) processing inittab(5). Before an entry is processed, though, init(8) cleans up utmp by setting ut_type to DEAD_PROCESS, clearing ut_user, ut_host, and ut_time with null bytes for each record which ut_type is not DEAD_PROCESS or RUN_LVL and where no process with PID ut_pid exists. If no empty record with the needed ut_id can be found, init creates a new one. It sets ut_id from the inittab, ut_pid and ut_time to the current values, and ut_type to INIT_PROCESS.

getty(8) locates the entry by the PID, changes ut_type to LOGIN_PROCESS, changes ut_time, sets ut_line, and waits for connection to be established. login(8), after a user has been authenticated, changes ut_type to USER_PROCESS, changes ut_time, and sets ut_host and ut_addr. Depending on getty(8) and login(8), records may be located by ut_line instead of the preferable ut_pid.

When init(8) finds that a process has exited, it locates its utmp entry by ut_pid, sets ut_type to DEAD_PROCESS, and clears ut_user, ut_host and ut_time with null bytes.

xterm(1) and other terminal emulators directly create a USER_PROCESS record and generate the ut_id by using the last two letters of /dev/ttyp%c or by using p%d for /dev/pts/%d. If they find a DEAD_PROCESS for this ID, they recycle it, otherwise they create a new entry. If they can, they will mark it as DEAD_PROCESS on exiting and it is advised that they null ut_line, ut_time, ut_user, and ut_host as well.

telnetd(8) sets up a LOGIN_PROCESS entry and leaves the rest to login(8) as usual. After the telnet session ends, telnetd(8) cleans up utmp in the described way.

The wtmp file records all logins and logouts. Its format is exactly like utmp except that a null user name indicates a logout on the associated terminal. Furthermore, the terminal name ~ with user name shutdown or reboot indicates a system shutdown or reboot and the pair of terminal names |/} logs the old/new system time when date(1) changes it. wtmp is maintained by login(1), init(1), and some versions of getty(8). Neither of these programs creates the file, so if it is removed, record-keeping is turned off.

Note that on biarch platforms, that is, systems which can run both 32-bit and 64-bit applications (x86-64, ppc64, s390x, etc.), ut_tv is the same size in 32-bit mode as in 64-bit mode. The same goes for ut_session and ut_time if they are present. This allows data files and shared memory to be shared between 32-bit and 64-bit applications. Since ut_tv may not be the same as struct timeval, then instead of the call:

gettimeofday((struct timeval *) &ut.ut_tv, NULL);

the following method of setting this field is recommended:

struct utmp ut;
struct timeval tv;

gettimeofday(&tv, NULL);
ut.ut_tv.tv_sec = tv.tv_sec;
ut.ut_tv.tv_usec = tv.tv_usec;

FILES

/var/run/utmp
/var/log/wtmp

CONFORMING TO

Linux utmp entries conform neither to v7/BSD nor to System V; they are a mix of the two. v7/BSD has fewer fields; most importantly it lacks ut_type, which causes native v7/BSD-like programs to display (for example) dead or login entries. Further, there is no configuration file which allocates slots to sessions. BSD does so because it lacks ut_id fields. In Linux (as in System V), the ut_id field of a record will never change once it has been set, which reserves that slot without needing a configuration file. Clearing ut_id may result in race conditions leading to corrupted utmp entries and potential security holes. Clearing the above mentioned fields by filling them with null bytes is not required by System V semantics, but it allows to run many programs which assume BSD semantics and which do not modify utmp. Linux uses the BSD conventions for line contents, as documented above.

System V only uses the type field to mark them and logs informative messages such as "new time" in the line field. UT_UNKNOWN seems to be a Linux invention. System V has no ut_host or ut_addr_v6 fields.

Unlike various other systems, where utmp logging can be disabled by removing the file, utmp must always exist on Linux. If you want to disable who(1) then do not make utmp world readable.

Note that the utmp struct from libc5 has changed in libc6. Because of this, binaries using the old libc5 struct will corrupt /var/run/utmp and/or /var/log/wtmp.

NOTES

The file format is machine dependent, so it is recommended that it be processed only on the machine architecture where it was created.

Note that on platforms which can run both 32-bit and 64-bit applications (x86-64, ppc64, s390x, etc.), the sizes of the fields of a struct utmp must be the same in 32-bit mode as in 64-bit mode. This is achieved by changing the type of ut_session to int32_t, and that of ut_tv to a struct with two int32_t fields tv_sec and tv_usec. (Thus, in order to fill it, first get the time into a real struct timeval, then copy the two fields to ut_tv.)

BUGS

This man page is based on the libc5 one, things may work differently now.

SEE ALSO

ac(1), date(1), last(1), login(1), who(1), getutent(3), updwtmp(3), init(8)


wtmp (5)

 Continue to this page.


acct(5)

ACCT

Section: Linux Programmer's Manual (5)
Updated: 2003-11-01 Return to Main Contents

NAME

acct - execution accounting file

SYNOPSIS

#include <sys/acct.h>

DESCRIPTION

If the kernel was compiled with the process accounting option enabled, the system call
acct("/somewhere/accountingfile");
will start the process accounting. Each time a process terminates a record for this process is appended to the accounting file. The accounting structure struct acct is also described in the file /usr/include/linux/acct.h.

SEE ALSO

lastcomm(1), sa(1), acct(2), accton(8)


passwd(5)

PASSWD

Section: Linux Programmer's Manual (5)
Updated: 1998-01-05 Return to Main Contents

NAME

passwd - password file

DESCRIPTION

Passwd is a text file, that contains a list of the system's accounts, giving for each account some useful information like user ID, group ID, home directory, shell, etc. Often, it also contains the encrypted passwords for each account. It should have general read permission (many utilities, like ls(1) use it to map user IDs to user names), but write access only for the superuser.

In the good old days there was no great problem with this general read permission. Everybody could read the encrypted passwords, but the hardware was too slow to crack a well-chosen password, and moreover, the basic assumption used to be that of a friendly user-community. These days many people run some version of the shadow password suite, where /etc/passwd has asterisks (*) instead of encrypted passwords, and the encrypted passwords are in /etc/shadow which is readable by the superuser only.

Regardless of whether shadow passwords are used, many sysadmins use an asterisk in the encrypted password field to make sure that this user can not authenticate him- or herself using a password. (But see the Notes below.)

If you create a new login, first put an asterisk in the password field, then use passwd(1) to set it.

There is one entry per line, and each line has the format:

account:password:UID:GID:GECOS:directory:shell

The field descriptions are:

account
the name of the user on the system. It should not contain capital letters.
password
the encrypted user password, an asterisk (*), or the letter 'x'. (See pwconv(8) for an explanation of 'x'.)
UID
the numerical user ID.
GID
the numerical primary group ID for this user.
GECOS
This field is optional and only used for informational purposes. Usually, it contains the full user name. GECOS means General Electric Comprehensive Operating System, which has been renamed to GCOS when GE's large systems division was sold to Honeywell. Dennis Ritchie has reported: "Sometimes we sent printer output or batch jobs to the GCOS machine. The gcos field in the password file was a place to stash the information for the $IDENTcard. Not elegant."
directory
the user's $HOME directory.
shell
the program to run at login (if empty, use /bin/sh). If set to a non-existing executable, the user will be unable to login through login(1).

FILES

/etc/passwd

NOTES

If you want to create user groups, their GIDs must be equal and there must be an entry in /etc/group, or no group will exist.

If the encrypted password is set to an asterisk, the user will be unable to login using login(1), but may still login using rlogin(1), run existing processes and initiate new ones through rsh(1), cron(1), at(1), or mail filters, etc. Trying to lock an account by simply changing the shell field yields the same result and additionally allows the use of su(1).

SEE ALSO

login(1), passwd(1), su(1), group(5), shadow(5)


shells(5)

SHELLS

Section: Linux Programmer's Manual (5)
Updated: 1993-11-21 Return to Main Contents

NAME

shells - pathnames of valid login shells

DESCRIPTION

/etc/shells is a text file which contains the full pathnames of valid login shells. This file is consulted by chsh(1) and available to be queried by other programs.

Be aware that there are programs which consult this file to find out if a user is a normal user. E.g.: ftp daemons traditionally disallow access to users with shells not included in this file.

FILES

/etc/shells

EXAMPLE

/etc/shells may contain the following paths:

/bin/sh
/bin/csh

SEE ALSO

chsh(1), getusershell(3)


termcap(5)

TERMCAP

Section: Linux Programmer's Manual (5)
Updated: 1996-10-21 Return to Main Contents

NAME

termcap - terminal capability database

DESCRIPTION

The termcap database is an obsolete facility for describing the capabilities of character-cell terminals and printers. It is retained only for capability with old programs; new ones should use the terminfo(5) database and associated libraries.

/etc/termcap is an ASCII file (the database master) that lists the capabilities of many different types of terminals. Programs can read termcap to find the particular escape codes needed to control the visual attributes of the terminal actually in use. (Other aspects of the terminal are handled by stty(1).) The termcap database is indexed on the TERM environment variable.

Termcap entries must be defined on a single logical line, with `\' used to suppress the newline. Fields are separated by `:'. The first field of each entry starts at the left-hand margin, and contains a list of names for the terminal, separated by '|'.

The first subfield may (in BSD termcap entries from versions 4.3 and prior) contain a short name consisting of two characters. This short name may consist of capital or small letters. In 4.4BSD termcap entries this field is omitted.

The second subfield (first, in the newer 4.4BSD format) contains the name used by the environment variable TERM. It should be spelled in lowercase letters. Selectable hardware capabilities should be marked by appending a hyphen and a suffix to this name. See below for an example. Usual suffixes are w (more than 80 characters wide), am (automatic margins), nam (no automatic margins), and rv (reverse video display). The third subfield contains a long and descriptive name for this termcap entry.

Subsequent fields contain the terminal capabilities; any continued capability lines must be indented one tab from the left margin.

Although there is no defined order, it is suggested to write first boolean, then numeric, and then string capabilities, each sorted alphabetically without looking at lower or upper spelling. Capabilities of similar functions can be written in one line.

Example for:

Head line: vt|vt101|DEC VT 101 terminal in 80 character mode:\
Head line: Vt|vt101-w|DEC VT 101 terminal in (wide) 132 character mode:\
Boolean: :bs:\
Numeric: :co#80:\
String: :sr=\E[H:\

Boolean Capabilities

5i      Printer will not echo on screen
am      Automatic margins which means automatic line wrap
bs      Control-H (8 dec.) performs a backspace
bw      Backspace on left margin wraps to previous line and right margin
da      Display retained above screen
db      Display retained below screen
eo      A space erases all characters at cursor position
es      Escape sequences and special characters work in status line
gn      Generic device
hc      This is a hardcopy terminal
HC      The cursor is hard to see when not on bottom line
hs      Has a status line
hz      Hazeltine bug, the terminal can not print tilde characters
in      Terminal inserts null bytes, not spaces, to fill whitespace
km      Terminal has a meta key
mi      Cursor movement works in insert mode
ms      Cursor movement works in standout/underline mode
NP      No pad character
NR      ti does not reverse te
nx      No padding, must use XON/XOFF
os      Terminal can overstrike
ul      Terminal underlines although it can not overstrike
xb      Beehive glitch, f1 sends ESCAPE, f2 sends ^C
xn      Newline/wraparound glitch
xo      Terminal uses xon/xoff protocol
xs      Text typed over standout text will be displayed in standout
xt      Teleray glitch, destructive tabs and odd standout mode

Numeric Capabilities

co      Number of columns
dB      Delay in milliseconds for backspace on hardcopy terminals
dC      Delay in milliseconds for carriage return on hardcopy terminals
dF      Delay in milliseconds for form feed on hardcopy terminals
dN      Delay in milliseconds for new line on hardcopy terminals
dT      Delay in milliseconds for tabulator stop on hardcopy terminals
dV      Delay in milliseconds for vertical tabulator stop on hardcopy terminals
it      Difference between tab positions
lh      Height of soft labels
lm      Lines of memory
lw      Width of soft labels
li      Number of lines
Nl      Number of soft labels
pb      Lowest baud rate which needs padding
sg      Standout glitch
ug      Underline glitch
vt      virtual terminal number
ws      Width of status line if different from screen width

String Capabilities

!1      shifted save key
!2      shifted suspend key
!3      shifted undo key
#1      shifted help key
#2      shifted home key
#3      shifted input key
#4      shifted cursor left key
%0      redo key
%1      help key
%2      mark key
%3      message key
%4      move key
%5      next-object key
%6      open key
%7      options key
%8      previous-object key
%9      print key
%a      shifted message key
%b      shifted move key
%c      shifted next key
%d      shifted options key
%e      shifted previous key
%f      shifted print key
%g      shifted redo key
%h      shifted replace key
%i      shifted cursor right key
%j      shifted resume key
&0      shifted cancel key
&1      reference key
&2      refresh key
&3      replace key
&4      restart key
&5      resume key
&6      save key
&7      suspend key
&8      undo key
&9      shifted begin key
*0      shifted find key
*1      shifted command key
*2      shifted copy key
*3      shifted create key
*4      shifted delete character
*5      shifted delete line
*6      select key
*7      shifted end key
*8      shifted clear line key
*9      shifted exit key
@0      find key
@1      begin key
@2      cancel key
@3      close key
@4      command key
@5      copy key
@6      create key
@7      end key
@8      enter/send key
@9      exit key
al      Insert one line
AL      Insert %1 lines
ac      Pairs of block graphic characters to map alternate character set
ae      End alternative character set
as      Start alternative character set for block graphic characters
bc      Backspace, if not ^H
bl      Audio bell
bt      Move to previous tab stop
cb      Clear from beginning of line to cursor
cc      Dummy command character
cd      Clear to end of screen
ce      Clear to end of line
ch      Move cursor horizontally only to column %1
cl      Clear screen and cursor home
cm      Cursor move to row %1 and column %2 (on screen)
CM      Move cursor to row %1 and column %2 (in memory)
cr      Carriage return
cs      Scroll region from line %1 to %2
ct      Clear tabs
cv      Move cursor vertically only to line %1
dc      Delete one character
DC      Delete %1 characters
dl      Delete one line
DL      Delete %1 lines
dm      Begin delete mode
do      Cursor down one line
DO      Cursor down #1 lines
ds      Disable status line
eA      Enable alternate character set
ec      Erase %1 characters starting at cursor
ed      End delete mode
ei      End insert mode
ff      Formfeed character on hardcopy terminals
fs      Return character to its position before going to status line
F1      The string sent by function key f11
F2      The string sent by function key f12
F3      The string sent by function key f13
...     ...
F9      The string sent by function key f19
FA      The string sent by function key f20
FB      The string sent by function key f21
...     ...
FZ      The string sent by function key f45
Fa      The string sent by function key f46
Fb      The string sent by function key f47
...     ...
Fr      The string sent by function key f63
hd      Move cursor a half line down
ho      Cursor home
hu      Move cursor a half line up
i1      Initialization string 1 at login
i3      Initialization string 3 at login
is      Initialization string 2 at login
ic      Insert one character
IC      Insert %1 characters
if      Initialization file
im      Begin insert mode
ip      Insert pad time and needed special characters after insert
iP      Initialization program
K1      upper left key on keypad
K2      center key on keypad
K3      upper right key on keypad
K4      bottom left key on keypad
K5      bottom right key on keypad
k0      Function key 0
k1      Function key 1
k2      Function key 2
k3      Function key 3
k4      Function key 4
k5      Function key 5
k6      Function key 6
k7      Function key 7
k8      Function key 8
k9      Function key 9
k;      Function key 10
ka      Clear all tabs key
kA      Insert line key
kb      Backspace key
kB      Back tab stop
kC      Clear screen key
kd      Cursor down key
kD      Key for delete character under cursor
ke      turn keypad off
kE      Key for clear to end of line
kF      Key for scrolling forward/down
kh      Cursor home key
kH      Cursor hown down key
kI      Insert character/Insert mode key
kl      Cursor left key
kL      Key for delete line
kM      Key for exit insert mode
kN      Key for next page
kP      Key for previous page
kr      Cursor right key
kR      Key for scrolling backward/up
ks      Turn keypad on
kS      Clear to end of screen key
kt      Clear this tab key
kT      Set tab here key
ku      Cursor up key
l0      Label of zeroth function key, if not f0
l1      Label of first function key, if not f1
l2      Label of first function key, if not f2
...     ...
la      Label of tenth function key, if not f10
le      Cursor left one character
ll      Move cursor to lower left corner
LE      Cursor left %1 characters
LF      Turn soft labels off
LO      Turn soft labels on
mb      Start blinking
MC      Clear soft margins
md      Start bold mode
me      End all mode like so, us, mb, md and mr
mh      Start half bright mode
mk      Dark mode (Characters invisible)
ML      Set left soft margin
mm      Put terminal in meta mode
mo      Put terminal out of meta mode
mp      Turn on protected attribute
mr      Start reverse mode
MR      Set right soft margin
nd      Cursor right one character
nw      Carriage return command
pc      Padding character
pf      Turn printer off
pk      Program key %1 to send string %2 as if typed by user
pl      Program key %1 to execute string %2 in local mode
pn      Program soft label %1 to show string %2
po      Turn the printer on
pO      Turn the printer on for %1 (<256) bytes
ps      Print screen contents on printer
px      Program key %1 to send string %2 to computer
r1      Reset string 1 to set terminal to sane modes
r2      Reset string 2 to set terminal to sane modes
r3      Reset string 3 to set terminal to sane modes
RA      disable automatic margins
rc      Restore saved cursor position
rf      Reset string filename
RF      Request for input from terminal
RI      Cursor right %1 characters
rp      Repeat character %1 for %2 times
rP      Padding after character sent in replace mode
rs      Reset string
RX      Turn off XON/XOFF flow control
sa      Set %1 %2 %3 %4 %5 %6 %7 %8 %9 attributes
SA      enable automatic margins
sc      Save cursor position
se      End standout mode
sf      Normal scroll one line
SF      Normal scroll %1 lines
so      Start standout mode
sr      Reverse scroll
SR      scroll back %1 lines
st      Set tabulator stop in all rows at current column
SX      Turn on XON/XOFF flow control
ta      move to next hardware tab
tc      Read in terminal description from another entry
te      End program that uses cursor motion
ti      Begin program that uses cursor motion
ts      Move cursor to column %1 of status line
uc      Underline character under cursor and move cursor right
ue      End underlining
up      Cursor up one line
UP      Cursor up %1 lines
us      Start underlining
vb      Visible bell
ve      Normal cursor visible
vi      Cursor invisible
vs      Standout cursor
wi      Set window from line %1 to %2 and column %3 to %4
XF      XOFF character if not ^S

There are several ways of defining the control codes for string capabilities:

Every normal character represents itself, except '^','\' and '%'.

A '^x' means Control-x. Control-A equals 1 decimal.

\x means a special code. x can be one of the following characters:

E Escape (27)
n Linefeed (10)
r Carriage return (13)
t Tabulation (9)
b Backspace (8)
f Form feed (12)
0 Null character. A \xxx specifies the octal character xxx.
i
Increments parameters by one.
r
Single parameter capability
+
Add value of next character to this parameter and do binary output
2
Do ASCII output of this parameter with a field with of 2
d
Do ASCII output of this parameter with a field with of 3
%
Print a '%'

If you use binary output, then you should avoid the null character because it terminates the string. You should reset tabulator expansion if a tabulator can be the binary output of a parameter.

Warning:
The above metacharacters for parameters may be wrong, they document Minix termcap which may not be compatible with Linux termcap.

The block graphic characters can be specified by three string capabilities:

as
start the alternative charset
ae
end it
ac
pairs of characters. The first character is the name of the block graphic symbol and the second characters is its definition.

The following names are available:

+       right arrow (>)
,       left arrow (<)
.       down arrow (v)
0       full square (#)
I       lantern (#)
-       upper arrow (^)
'       rhombus (+)
a       chess board (:)
f       degree (')
g       plus-minus (#)
h       square (#)
j       right bottom corner (+)
k       right upper corner (+)
l       left upper corner (+)
m       left bottom corner (+)
n       cross (+)
o       upper horizontal line (-)
q       middle horizontal line (-)
s       bottom horizontal line (_)
t       left tee (+)
u       right tee (+)
v       bottom tee (+)
w       normal tee (+)
x       vertical line (|)
~       paragraph (???)

The values in parentheses are suggested defaults which are used by curses, if the capabilities are missing.

SEE ALSO

ncurses(3), termcap(3), terminfo(5)


nsswitch.conf(5)

NSSWITCH.CONF

Section: Linux Programmer's Manual (5)
Updated: 1999-01-17 Return to Main Contents

NAME

nsswitch.conf - System Databases and Name Service Switch configuration file

DESCRIPTION

Various functions in the C Library need to be configured to work correctly in the local environment. Traditionally, this was done by using files (e.g., `/etc/passwd'), but other nameservices (like the Network Information Service (NIS) and the Domain Name Service (DNS)) became popular, and were hacked into the C library, usually with a fixed search order.

The Linux libc5 with NYS support and the GNU C Library 2.x (libc.so.6) contain a cleaner solution of this problem. It is designed after a method used by Sun Microsystems in the C library of Solaris 2. We follow their name and call this scheme "Name Service Switch" (NSS). The sources for the "databases" and their lookup order are specified in the /etc/nsswitch.conf file.

The following databases are available in the NSS:

aliases
Mail aliases, used by sendmail(8). Presently ignored.
ethers
Ethernet numbers.
group
Groups of users, used by getgrent(3) functions.
hosts
Host names and numbers, used by gethostbyname(3) and similar functions.
netgroup
Network wide list of hosts and users, used for access rules. C libraries before glibc 2.1 only support netgroups over NIS.
networks
Network names and numbers, used by getnetent(3) functions.
passwd
User passwords, used by getpwent(3) functions.
protocols
Network protocols, used by getprotoent(3) functions.
publickey
Public and secret keys for Secure_RPC used by NFS and NIS+.
rpc
Remote procedure call names and numbers, used by getrpcbyname(3) and similar functions.
services
Network services, used by getservent(3) functions.
shadow
Shadow user passwords, used by getspnam(3).

An example /etc/nsswitch.conf (namely, the default used when /etc/nsswitch.conf is missing):

passwd:
compat
group:
compat
shadow:
compat

hosts:
dns [!UNAVAIL=return] files
networks:
nis [NOTFOUND=return] files
ethers:
nis [NOTFOUND=return] files
protocols:
nis [NOTFOUND=return] files
rpc:
nis [NOTFOUND=return] files
services:
nis [NOTFOUND=return] files

The first column is the database. The rest of the line specifies how the lookup process works. You can specify the way it works for each database individually.

The configuration specification for each database can contain two different items:

* The service specification like `files', `db', or `nis'.
* The reaction on lookup result like `[NOTFOUND=return]'.

For libc5 with NYS, the allowed service specifications are `files', `nis', and `nisplus'. For hosts, you could specify `dns' as extra service, for passwd and group `compat', but not for shadow.

For glibc, you must have a file called /lib/libnss_SERVICE.so.X for every SERVICE you are using. On a standard installation, you could use `files', `db', `nis', and `nisplus'. For hosts, you could specify `dns' as extra service, for passwd, group, and shadow `compat'. These services will not be used by libc5 with NYS. The version number X is 1 for glibc 2.0 and 2 for glibc 2.1.

The second item in the specification gives the user much finer control on the lookup process. Action items are placed between two service names and are written within brackets. The general form is

`[' ( `!'? STATUS `=' ACTION )+ `]'

where

STATUS => success | notfound | unavail | tryagain
ACTION => return | continue

The case of the keywords is insignificant. The STATUS values are the results of a call to a lookup function of a specific service. They mean:

success
No error occurred and the wanted entry is returned. The default action for this is `return'.
notfound
The lookup process works ok but the needed value was not found. The default action is `continue'.
unavail
The service is permanently unavailable. This can either mean the needed file is not available, or, for DNS, the server is not available or does not allow queries. The default action is `continue'.
tryagain
The service is temporarily unavailable. This could mean a file is locked or a server currently cannot accept more connections. The default action is `continue'.

Interaction with +/- syntax (compat mode)

Linux libc5 without NYS does not have the name service switch but does allow the user some policy control. In /etc/passwd you could have entries of the form +user or +@netgroup (include the specified user from the NIS passwd map), -user or -@netgroup (exclude the specified user), and + (include every user, except the excluded ones, from the NIS passwd map). Since most people only put a + at the end of /etc/passwd to include everything from NIS, the switch provides a faster alternative for this case (`passwd: files nis') which doesn't require the single + entry in /etc/passwd, /etc/group, and /etc/shadow. If this is not sufficient, the NSS `compat' service provides full +/- semantics. By default, the source is `nis', but this may be overridden by specifying `nisplus' as source for the pseudo-databases passwd_compat, group_compat and shadow_compat. This pseudo-databases are only available in GNU C Library.

FILES

A service named SERVICE is implemented by a shared object library named libnss_SERVICE.so.X that resides in /lib.
/etc/nsswitch.conf configuration file
/lib/libnss_compat.so.X
implements `compat' source for glibc2
/lib/libnss_db.so.X
implements `db' source for glibc2
/lib/libnss_dns.so.X
implements `dns' source for glibc2
/lib/libnss_files.so.X
implements `files' source for glibc2
/lib/libnss_hesiod.so.X
implements `hesiod' source for glibc2
/lib/libnss_nis.so.X
implements `nis' source for glibc2
/lib/libnss_nisplus.so.2
implements `nisplus' source for glibc 2.1

NOTES

Within each process that uses nsswitch.conf, the entire file is read only once; if the file is later changed, the process will continue using the old configuration.

With Solaris, it isn't possible to link programs using the NSS Service statically. With Linux, this is no problem.


charmap(5)

CHARMAP

Section: Linux User Manual (5)
Updated: 1994-11-28 Return to Main Contents

NAME

charmap - character symbols to define character encodings

DESCRIPTION

A character set description (charmap) defines a character set of available characters and their encodings. All supported character sets should have the portable character set as a proper subset.

SYNTAX

The charmap file starts with a header, that may consist of the following keywords:
<codeset>
is followed by the name of the codeset.
<mb_cur_max>
is followed by the max number of bytes for a multibyte-character. Multibyte characters are currently not supported. The default value is 1.
<mb_cur_min>
is followed by the min number of bytes for a character. This value must be less or equal than mb_cur_max. If not specified, it defaults to mb_cur_max.
<escape_char>
is followed by a character that should be used as the escape-character for the rest of the file to mark characters that should be interpreted in a special way. It defaults to the backslash ( \\ ).
<comment_char>
is followed by a character that will be used as the comment-character for the rest of the file. It defaults to the number sign ( # ).

The charmap-definition itself starts with the keyword CHARMAP in column 1.

The following lines may have one of the two following forms to define the character-encodings:

<symbolic-name> <encoding> <comments>
This form defines exactly one character and its encoding.
<symbolic-name>...<symbolic-name> <encoding> <comments>
This form defines a couple of characters. This is only useful for multibyte-characters, which are currently not implemented.

The last line in a charmap-definition file must contain END CHARMAP.

SYMBOLIC NAMES

A symbolic name for a character contains only characters of the portable character set. The name itself is enclosed between angle brackets. Characters following an <escape_char> are interpreted as itself; for example, the sequence '<\\\\\\>>' represents the symbolic name '\\>' enclosed in angle brackets.

CHARACTER ENCODING

The encoding may be in each of the following three forms:
<escape_char>d<number>
with a decimal number
<escape_char>x<number>
with a hexadecimal number
<escape_char><number>
with an octal number.

FILES

/usr/share/i18n/charmaps/*

CONFORMING TO

POSIX.2

SEE ALSO

locale(1), localedef(1), localeconv(3), setlocale(3), locale(5)


intro(5)

INTRO

Section: Linux Programmer's Manual (5)
Updated: 1993-07-24 Return to Main Contents

NAME

intro - Introduction to file formats

DESCRIPTION

This chapter describes various file formats and protocols, and the used C structures, if any.

Authors and Copyright Conditions

Look at the header of the manual page for the author(s) and copyright conditions. Note that these can be different from page to page!

SEE ALSO

standards(7)


protocols(5)

PROTOCOLS

Section: Linux Programmer's Manual (5)
Updated: 2002-09-22 Return to Main Contents

NAME

protocols - the protocols definition file

DESCRIPTION

This file is a plain ASCII file, describing the various DARPA internet protocols that are available from the TCP/IP subsystem. It should be consulted instead of using the numbers in the ARPA include files, or, even worse, just guessing them. These numbers will occur in the protocol field of any ip header.

Keep this file untouched since changes would result in incorrect ip packages. Protocol numbers and names are specified by the IANA (Internet Assigned Numbers Authority).

Each line is of the following format:

protocol number aliases ...

where the fields are delimited by spaces or tabs. Empty lines are ignored. If a line contains a hash mark (#), the hash mark and the part of the line following it are ignored.

The field descriptions are:

protocol
the native name for the protocol. For example ip, tcp, or udp.
number
the official number for this protocol as it will appear within the ip header.
aliases
optional aliases for the protocol.

This file might be distributed over a network using a networkwide naming service like Yellow Pages/NIS or BIND/Hesiod.

FILES

/etc/protocols
The protocols definition file.

SEE ALSO

getprotoent(3)

Guide to Yellow Pages Service

Guide to BIND/Hesiod Service

http://www.iana.org/assignments/protocol-numbers


environ (5)

 Continue to this page.


ipc (5)

 Continue to this page.


locale(5)

LOCALE

Section: Linux User Manual (5)
Updated: 1994-11-09 Return to Main Contents

NAME

locale - Describes a locale definition file

DESCRIPTION

The locale definition files contains all the information that the localedef(1) command needs to convert it into the binary locale database.

The definition files consist of sections which each describe a locale category in detail.

Syntax

The locale definition file starts with a header that may consist of the following keywords:
<escape_char>
is followed by a character that should be used as the escape-character for the rest of the file to mark characters that should be interpreted in a special way. It defaults to the backslash ( \\ ).
<comment_char>
is followed by a character that will be used as the comment-character for the rest of the file. It defaults to the number sign (#).

The locale definition has one part for each locale category. Each part can be copied from another existing locale or can be defined from scratch. If the category should be copied, the only valid keyword in the definition is copy followed by the name of the locale which should be copied.

LC_CTYPE

The definition for the LC_CTYPE category starts with the string LC_CTYPE in the first column.

There are the following keywords allowed:

upper
followed by a list of uppercase letters. The letters A trough Z are included automatically. Characters also specified as cntrl, digit, punct, or space are not allowed.
lower
followed by a list of lowercase letters. The letters a trough z are included automatically. Characters also specified as cntrl, digit, punct, or space are not allowed.
alpha
followed by a list of letters. All character specified as either upper or lower are automatically included. Characters also specified as cntrl, digit, punct, or space are not allowed.
digit
followed by the characters classified as numeric digits. Only the digits 0 trough 9 are allowed. They are included by default in this class.
space
followed by a list of characters defined as white-space characters. Characters also specified as upper, lower, alpha, digit, graph, or xdigit are not allowed. The characters <space>, <form-feed>, <newline>, <carriage-return>, <tab>, and <vertical-tab> are automatically included.
cntrl
followed by a list of control characters. Characters also specified as upper, lower, alpha, digit, punct, graph, print, or xdigit are not allowed.
punct
followed by a list of punctuation characters. Characters also specified as upper, lower, alpha, digit, cntrl, xdigit, or the <space> character are not allowed.
graph
followed by a list of printable characters, not including the <space> character. The characters defined as upper, lower, alpha, digit, xdigit, and punct are automatically included. Characters also specified as cntrl are not allowed.
print
followed by a list of printable characters, including the <space> character. The characters defined as upper, lower, alpha, digit, xdigit, punct, and the <space> character are automatically included. Characters also specified as cntrl are not allowed.
xdigit
followed by a list of characters classified as hexadecimal digits. The decimal digits must be included followed by one or more set of six characters in ascending order. The following characters are included by default: 0 trough 9, a trough f, A trough F.
blank
followed by a list of characters classified as blank. The characters <space> and <tab> are automatically included.
toupper
followed by a list of mappings from lowercase to uppercase letters. Each mapping is a pair of a lowercase and an uppercase letter separated with a , and enclosed in parentheses. The members of the list are separated with semicolons.
tolower
followed by a list of mappings from uppercase to lowercase letters. If the keyword tolower is not present, the reverse of the toupper list is used.

The LC_CTYPE definition ends with the string END LC_CYTPE.

LC_COLLATE

The LC_COLLATE category defines the rules for collating characters. Due to limitations of libc not all POSIX-options are implemented.

The definition starts with the string LC_COLLATE in the first column.

There are the following keywords allowed:

collating-element
collating-symbol

The order-definition starts with a line:

order_start

followed by a list of keywords out of forward, backward, or position. The order definition consists of lines that describe the order and is terminated with the keyword

order_end.

For more details see the sources in /usr/lib/nls/src notably the examples POSIX, Example and Example2

The LC_COLLATE definition ends with the string ENDLC_COLLATE.

LC_MONETARY

The definition starts with the string LC_MONETARY in the first column.

There are the following keywords allowed:

int_curr_symbol
followed by the international currency symbol. This must be a 4-character string containing the international currency symbol as defined by the ISO 4217 standard (three characters) followed by a separator.
currency_symbol
followed by the local currency symbol.
mon_decimal_point
followed by the string that will be used as the decimal delimiter when formatting monetary quantities.
mon_thousands_sep
followed by the string that will be used as a group separator when formatting monetary quantities.
mon_grouping
followed by a string that describes the formatting of numeric quantities.
positive_sign
followed by a string that is used to indicate a positive sign for monetary quantities.
negative_sign
followed by a string that is used to indicate a negative sign for monetary quantities.
int_frac_digits
followed by the number of fractional digits that should be used when formatting with the int_curr_symbol.
frac_digits
followed by the number of fractional digits that should be used when formatting with the currency_symbol.
p_cs_precedes
followed by an integer set to 1 if the currency_symbol or int_curr_symbol
should precede the formatted monetary quantity or set to 0 if the symbol succeeds the value.
p_sep_by_space
followed by an integer.
0
means that no space should be printed between the symbol and the value.
1
means that a space should be printed between the symbol and the value.
2
means that a space should be printed between the symbol and the sign string, if adjacent.
n_cs_precedes
0
- the symbol succeeds the value.
1
- the symbol precedes the value.
n_sep_by_space
An integer set to 0 if no space separates the currency_symbol or int_curr_symbol from the value for a negative monetary quantity, set to 1 if a space separates the symbol from the value and set to 2 if a space separates the symbol and the sign string, if adjacent.
p_sign_posn
0
Parentheses enclose the quantity and the currency_symbol or int_curr_symbol.
1
The sign string precedes the quantity and the currency_symbol or the int_curr_symbol.
2
The sign string succeeds the quantity and the currency_symbol or the int_curr_symbol.
3
The sign string precedes the currency_symbol or the int_curr_symbol.
4
The sign string succeeds the currency_symbol or the int_curr_symbol.
n_sign_posn
0
Parentheses enclose the quantity and the currency_symbol or int_curr_symbol.
1
The sign string precedes the quantity and the currency_symbol or the int_curr_symbol.
2
The sign string succeeds the quantity and the currency_symbol or the int_curr_symbol.
3
The sign string precedes the currency_symbol or the int_curr_symbol.
4
The sign string succeeds the currency_symbol or the int_curr_symbol.

The LC_MONETARY definition ends with the string END LC_MONETARY.

LC_NUMERIC

The definition starts with the string LC_NUMERIC in the first column.

The following keywords are allowed:

decimal_point
followed by the string that will be used as the decimal delimiter when formatting numeric quantities.
thousands_sep
followed by the string that will be used as a group separator when formatting numeric quantities.
grouping
followed by a string that describes the formatting of numeric quantities.

The LC_NUMERIC definition ends with the string END LC_NUMERIC.

LC_TIME

The definition starts with the string LC_TIME in the first column.

The following keywords are allowed:

abday
followed by a list of abbreviated weekday names. The list starts with Sunday or its translation.
day
followed by a list of weekday names. The list starts with Sunday.
abmon
followed by a list of abbreviated month names.
mon
followed by a list of month names.
am_pm
The appropriate representation of the am and pm strings.
d_t_fmt
The appropriate date and time format.
d_fmt
The appropriate date format.
t_fmt
The appropriate time format.
t_fmt_ampm
The appropriate time format when using 12h clock format.

The LC_TIME definition ends with the string END LC_TIME.

LC_MESSAGES

The definition starts with the string LC_MESSAGES in the first column.

The following keywords are allowed:

yesexpr
followed by a regular expression that describes possible yes-responses.
noexpr
followed by a regular expression that describes possible no-responses.

The LC_MESSAGES definition ends with the string END LC_MESSAGES.

See the POSIX.2 standard for details.

FILES

/usr/lib/locale/ --- database for the current locale setting of that category
/usr/lib/nls/charmap/* --- charmap-files

CONFORMING TO

POSIX.2

BUGS

This manual page isn't complete.

SEE ALSO

locale(1), localedef(1), localeconv(3), setlocale(3), charmap(5)


nologin(5)

NOLOGIN

Section: Linux Programmer's Manual (5)
Updated: 1992-12-29 Return to Main Contents

NAME

nologin - prevent non-root users from logging into the system

DESCRIPTION

If the file /etc/nologin exists, login(1) will allow access only to root. Other users will be shown the contents of this file and their logins will be refused.

FILES

/etc/nologin

SEE ALSO

login(1), shutdown(8)


services(5)

SERVICES

Section: Linux Programmer's Manual (5)
Updated: 1996-01-11 Return to Main Contents

NAME

services - Internet network services list

DESCRIPTION

services is a plain ASCII file providing a mapping between friendly textual names for internet services, and their underlying assigned port numbers and protocol types. Every networking program should look into this file to get the port number (and protocol) for its service. The C library routines getservent(3), getservbyname(3), getservbyport(3), setservent(3), and endservent(3) support querying this file from programs.

Port numbers are assigned by the IANA (Internet Assigned Numbers Authority), and their current policy is to assign both TCP and UDP protocols when assigning a port number. Therefore, most entries will have two entries, even for TCP only services.

Port numbers below 1024 (so-called 'low numbered' ports) can only be bound to by root (see bind(2), tcp(7), and udp(7)). This is so clients connecting to low numbered ports can trust that the service running on the port is the standard implementation, and not a rogue service run by a user of the machine. Well-known port numbers specified by the IANA are normally located in this root-only space.

The presence of an entry for a service in the services file does not necessarily mean that the service is currently running on the machine. See inetd.conf(5) for the configuration of Internet services offered. Note that not all networking services are started by inetd(8), and so won't appear in inetd.conf(5). In particular, news (NNTP) and mail (SMTP) servers are often initialized from the system boot scripts.

The location of the services file is defined by _PATH_SERVICES in /usr/include/netdb.h. This is usually set to /etc/services.

Each line describes one service, and is of the form:

service-name port/protocol [aliases ...]
where:
service-name
is the friendly name the service is known by and looked up under. It is case sensitive. Often, the client program is named after the service-name.
port
is the port number (in decimal) to use for this service.
protocol
is the type of protocol to be used. This field should match an entry in the protocols(5) file. Typical values include tcp and udp.
aliases
is an optional space or tab separated list of other names for this service (but see the BUGS section below). Again, the names are case sensitive.

Either spaces or tabs may be used to separate the fields.

Comments are started by the hash sign (#) and continue until the end of the line. Blank lines are skipped.

The service-name should begin in the first column of the file, since leading spaces are not stripped. service-names can be any printable characters excluding space and tab. However, a conservative choice of characters should be used to minimize inter-operability problems. E.g., a-z, 0-9, and hyphen (-) would seem a sensible choice.

Lines not matching this format should not be present in the file. (Currently, they are silently skipped by getservent(3), getservbyname(3), and getservbyport(3). However, this behavior should not be relied on.)

As a backwards compatibility feature, the slash (/) between the port number and protocol name can in fact be either a slash or a comma (,). Use of the comma in modern installations is depreciated.

This file might be distributed over a network using a network-wide naming service like Yellow Pages/NIS or BIND/Hesiod.

A sample services file might look like this:

netstat         15/tcp
qotd            17/tcp          quote
msp             18/tcp          # message send protocol
msp             18/udp          # message send protocol
chargen         19/tcp          ttytst source
chargen         19/udp          ttytst source
ftp             21/tcp
# 22 - unassigned
telnet          23/tcp

FILES

/etc/services
The Internet network services list
/usr/include/netdb.h
Definition of _PATH_SERVICES

BUGS

There is a maximum of 35 aliases, due to the way the getservent(3) code is written.

Lines longer than BUFSIZ (currently 1024) characters will be ignored by getservent(3), getservbyname(3), and getservbyport(3). However, this will also cause the next line to be mis-parsed.

SEE ALSO

listen(2), endservent(3), getservbyname(3), getservbyport(3), getservent(3), setservent(3), inetd.conf(5), protocols(5), inetd(8)

Assigned Numbers RFC, most recently RFC 1700, (AKA STD0002)

Guide to Yellow Pages Service

Guide to BIND/Hesiod Service


nscd.conf(5)

NSCD.CONF

Section: Linux Programmer's Manual (5)
Updated: 1999-10-01 Return to Main Contents

NAME

/etc/nscd.conf - name service cache daemon configuration file

DESCRIPTION

The file /etc/nscd.conf is read from nscd(8) at startup. Each line specifies either an attribute and a value, or an attribute, service, and a value. Fields are separated either by SPACE or TAB characters. A `#' (number sign) indicates the beginning of a comment; following characters, up to the end of the line, are not interpreted by nscd.

Valid services are passwd, group, or hosts.

logfile debug-file-name

Specifies name of the file to which debug info should be written.

debug-level value

Sets the desired debug level.

threads number

This is the number of threads that are started to wait for requests. At least five threads will always be created.

server-user user

If this option is set, nscd will run as this user and not as root. If a separate cache for every user is used (-S parameter), this option is ignored.

enable-cache service <yes|no>

Enables or disables the specified service cache.

positive-time-to-live service value

Sets the TTL (time-to-live) for positive entries (successful queries) in the specified cache for service. Value is in seconds. Larger values increase cache hit rates and reduce mean response times, but increase problems with cache coherence.

negative-time-to-live service value

Sets the TTL (time-to-live) for negative entries (unsuccessful queries) in the specified cache for service. Value is in seconds. Can result in significant performance improvements if there are several files owned by UIDs (user IDs) not in system databases (for example untarring the linux kernel sources as root); should be kept small to reduce cache coherency problems.

suggested-size service value

This is the internal hash table size, value should remain a prime number for optimum efficiency.

check-files service <yes|no>

Enables or disables checking the file belonging to the specified service for changes. The files are /etc/passwd, /etc/group, and /etc/hosts.

max-threads threads

Specifies the maximum number of threads to be started.

stat-user username

Specifies the user who is allowed to request statistics.

reload-count unlimited | number

Limit on the number of times a cached entry gets reloaded without being used before it gets removed. The default is 5.

paranoia <yes|no>

Enabling paranoia mode causes nscd to restart itself periodically.

restart-interval time

Sets the restart interval to time seconds if periodic restart is enabled by enabling paranoia mode.

persistent service <yes|no>

Keep the content of the cache for service over server restarts; useful when paranoia mode is set.

shared service <yes|no>

The memory mapping of the nscd databases for service is shared with the clients so that they can directly search in them instead of having to ask the daemon over the socket each time a lookup is performed.

SEE ALSO

nscd(8)


hosts(5)

HOSTS

Section: Linux Programmer's Manual (5)
Updated: 2002-06-16 Return to Main Contents

NAME

hosts - The static table lookup for host names

SYNOPSIS

/etc/hosts

DESCRIPTION

This manual page describes the format of the /etc/hosts file. This file is a simple text file that associates IP addresses with hostnames, one line per IP address. For each host a single line should be present with the following information:

IP_address canonical_hostname [aliases...]

Fields of the entry are separated by any number of blanks and/or tab characters. Text from a "#" character until the end of the line is a comment, and is ignored. Host names may contain only alphanumeric characters, minus signs ("-"), and periods ("."). They must begin with an alphabetic character and end with an alphanumeric character. Optional aliases provide for name changes, alternate spellings, shorter hostnames, or generic hostnames (for example, localhost).

The Berkeley Internet Name Domain (BIND) Server implements the Internet name server for UNIX systems. It augments or replaces the /etc/hosts file or host name lookup, and frees a host from relying on /etc/hosts being up to date and complete.

In modern systems, even though the host table has been superseded by DNS, it is still widely used for:

bootstrapping
Most systems have a small host table containing the name and address information for important hosts on the local network. This is useful when DNS is not running, for example during system bootup.
NIS
Sites that use NIS use the host table as input to the NIS host database. Even though NIS can be used with DNS, most NIS sites still use the host table with an entry for all local hosts as a backup.
isolated nodes
Very small sites that are isolated from the network use the host table instead of DNS. If the local information rarely changes, and the network is not connected to the Internet, DNS offers little advantage.

FILES

/etc/hosts

NOTES

Modifications to this file normally take effect immediately, except in cases where the file is cached by applications.

Historical Notes

RFC 952 gave the original format for the host table, though it has since changed.

Before the advent of DNS, the host table was the only way of resolving hostnames on the fledgling Internet. Indeed, this file could be created from the official host data base maintained at the Network Information Control Center (NIC), though local changes were often required to bring it up to date regarding unofficial aliases and/or unknown hosts. The NIC no longer maintains the hosts.txt files, though looking around at the time of writing (circa 2000), there are historical hosts.txt files on the WWW. I just found three, from 92, 94, and 95.

EXAMPLE

127.0.0.1       localhost
192.168.1.10    foo.mydomain.org       foo
192.168.1.13    bar.mydomain.org       bar
146.82.138.7    master.debian.org      master
209.237.226.90  www.opensource.org

SEE ALSO

hostname(1), resolver(3), resolver(5), hostname(7), named(8), Internet RFC 952


hosts.equiv(5)

HOSTS.EQUIV

Section: Linux Programmer's Manual (5)
Updated: 2003-08-24 Return to Main Contents

NAME

/etc/hosts.equiv - list of hosts and users that are granted "trusted" r command access to your system

DESCRIPTION

The hosts.equiv file allows or denies hosts and users to use the r-commands (e.g., rlogin, rsh or rcp) without supplying a password.

The file uses the following format:

[ + | - ] [hostname] [username]

The hostname is the name of a host which is logically equivalent to the local host. Users logged into that host are allowed to access like-named user accounts on the local host without supplying a password. The hostname may be (optionally) preceded by a plus (+) sign. If the plus sign is used alone it allows any host to access your system. You can explicitly deny access to a host by preceding the hostname by a minus (-) sign. Users from that host must always supply a password. For security reasons you should always use the FQDN of the hostname and not the short hostname.

The username entry grants a specific user access to all user accounts (except root) without supplying a password. That means the user is NOT restricted to like-named accounts. The username may be (optionally) preceded by a plus (+) sign. You can also explicitly deny access to a specific user by preceding the username with a minus (-) sign. This says that the user is not trusted no matter what other entries for that host exist.

Netgroups can be specified by preceding the netgroup by an @ sign.

Be extremely careful when using the plus (+) sign. A simple typographical error could result in a standalone plus sign. A standalone plus sign is a wildcard character that means "any host"!

FILES

/etc/hosts.equiv

NOTES

Some systems will only honor the contents of this file when it has owner root and no write permission for anybody else. Some exceptionally paranoid systems even require that there be no other hard links to the file.

Modern systems use the Pluggable Authentication Modules library (PAM). With PAM a standalone plus sign is only considered a wildcard character which means "any host" when the word promiscuous is added to the auth component line in your PAM file for the particular service (e.g., rlogin).

SEE ALSO

rhosts(5), rlogind(8), rshd(8)


host.conf(5)

HOST.CONF

Section: Linux System Administration (5)
Updated: 2003-08-23 Return to Main Contents

NAME

host.conf - resolver configuration file

DESCRIPTION

The file /etc/host.conf contains configuration information specific to the resolver library. It should contain one configuration keyword per line, followed by appropriate configuration information. The keywords recognized are order, trim, multi, nospoof, spoof, and reorder. These keywords are described below.
order
This keyword specifies how host lookups are to be performed. It should be followed by one or more lookup methods, separated by commas. Valid methods are bind, hosts, and nis.
trim
This keyword may be listed more than once. Each time it should be followed by a list of domains, separated by colons (`:'), semicolons (`;') or commas (`,'), with the leading dot. When set, the resolv+ library will automatically trim the given domain name from the end of any hostname resolved via DNS. This is intended for use with local hosts and domains. (Related note: trim will not affect hostnames gathered via NIS or the hosts file. Care should be taken to ensure that the first hostname for each entry in the hosts file is fully qualified or non-qualified, as appropriate for the local installation.)
multi
Valid values are on and off. If set to on, the resolv+ library will return all valid addresses for a host that appears in the /etc/hosts file, instead of only the first. This is off by default, as it may cause a substantial performance loss at sites with large hosts files.
nospoof
Valid values are on and off. If set to on, the resolv+ library will attempt to prevent hostname spoofing to enhance the security of rlogin and rsh. It works as follows: after performing a host address lookup, resolv+ will perform a hostname lookup for that address. If the two hostnames do not match, the query will fail. The default value is off.
spoofalert
Valid values are on and off. If this option is set to on and the nospoof option is also set, resolv+ will log a warning of the error via the syslog facility. The default value is off.
spoof
Valid values are off, nowarn and warn. If this option is set to off, spoofed addresses are permitted and no warnings will be emitted via the syslog facility. If this option is set to warn, resolv+ will attempt to prevent hostname spoofing to enhance the security and log a warning of the error via the syslog facility. If this option is set to nowarn, the resolv+ library will attempt to prevent hostname spoofing to enhance the security but not emit warnings via the syslog facility. Setting this option to anything else is equal to setting it to nowarn.
reorder
Valid values are on and off. If set to on, resolv+ will attempt to reorder host addresses so that local addresses (i.e., on the same subnet) are listed first when a gethostbyname(3) is performed. Reordering is done for all lookup methods. The default value is off.

ENVIRONMENT

There are six environment variables that can be used to allow users to override the behavior which is configured in /etc/host.conf.
RESOLV_HOST_CONF
If set this variable points to a file that should be read instead of /etc/host.conf.
RESOLV_SERV_ORDER
Overrides the order command.
RESOLV_SPOOF_CHECK
Overrides the nospoof, spoofalert and spoof commands in the same way as the spoof command is parsed. Valid values are off, nowarn and warn.
RESOLV_MULTI
Overrides the multi command.
RESOLV_REORDER
Overrides the reorder command.
RESOLV_ADD_TRIM_DOMAINS
A list of domains, separated by colons (`:'), semicolons (`;') or commas (`,'), with the leading dot, which will be added to the list of domains that should be trimmed.
RESOLV_OVERRIDE_TRIM_DOMAINS
A list of domains, separated by colons (`:'), semicolons (`;') or commas (`,'), with the leading dot, which will replace the list of domains that should be trimmed. Overrides the trim command.

FILES

/etc/host.conf
Resolver configuration file
/etc/resolv.conf
Resolver configuration file
/etc/hosts
Local hosts database

NOTES

The following differences exist compared to the original implementation. A new command spoof and a new environment variable RESOLV_SPOOF_CHECK can take arguments like off, nowarn and warn. Line comments can appear anywhere and not only at the beginning of a line.

SEE ALSO

gethostbyname(3), hostname(7), named(8), resolv+(8)


resolv.conf(5)

RESOLV.CONF

Section: Linux Programmer's Manual (5)
Updated: 2004-10-31 Return to Main Contents

NAME

resolv.conf - resolver configuration file

SYNOPSIS

/etc/resolv.conf

DESCRIPTION

The resolver is a set of routines in the C library that provide access to the Internet Domain Name System (DNS). The resolver configuration file contains information that is read by the resolver routines the first time they are invoked by a process. The file is designed to be human readable and contains a list of keywords with values that provide various types of resolver information.

On a normally configured system this file should not be necessary. The only name server to be queried will be on the local machine; the domain name is determined from the host name and the domain search path is constructed from the domain name.

The different configuration options are:

nameserver Name server IP address
Internet address (in dot notation) of a name server that the resolver should query. Up to MAXNS (currently 3, see <resolv.h>) name servers may be listed, one per keyword. If there are multiple servers, the resolver library queries them in the order listed. If no nameserver entries are present, the default is to use the name server on the local machine. (The algorithm used is to try a name server, and if the query times out, try the next, until out of name servers, then repeat trying all the name servers until a maximum number of retries are made.)
domain Local domain name.
Most queries for names within this domain can use short names relative to the local domain. If no domain entry is present, the domain is determined from the local host name returned by gethostname(2); the domain part is taken to be everything after the first `.'. Finally, if the host name does not contain a domain part, the root domain is assumed.
search Search list for host-name lookup.
The search list is normally determined from the local domain name; by default, it contains only the local domain name. This may be changed by listing the desired domain search path following the search keyword with spaces or tabs separating the names. Resolver queries having fewer than ndots dots (default is 1) in them will be attempted using each component of the search path in turn until a match is found. For environments with multiple subdomains please read options ndots:n below to avoid man-in-the-middle attacks and unnecessary traffic for the root-dns-servers. Note that this process may be slow and will generate a lot of network traffic if the servers for the listed domains are not local, and that queries will time out if no server is available for one of the domains.
The search list is currently limited to six domains with a total of 256 characters.
sortlist
Sortlist allows addresses returned by gethostbyname(3) to be sorted. A sortlist is specified by IP address netmask pairs. The netmask is optional and defaults to the natural netmask of the net. The IP address and optional network pairs are separated by slashes. Up to 10 pairs may be specified. E.g.,
sortlist 130.155.160.0/255.255.240.0 130.155.0.0
options
Options allows certain internal resolver variables to be modified. The syntax is
options option ...

where option is one of the following:

debug
sets RES_DEBUG in _res.options.
ndots:n
sets a threshold for the number of dots which must appear in a name given to res_query(3) (see resolver(3)) before an initial absolute query will be made. The default for n is ``1'', meaning that if there are any dots in a name, the name will be tried first as an absolute name before any search list elements are appended to it.
timeout:n
sets the amount of time the resolver will wait for a response from a remote name server before retrying the query via a different name server. Measured in seconds, the default is RES_TIMEOUT (currently 5, see <resolv.h>).
attempts:n
sets the number of times the resolver will send a query to its name servers before giving up and returning an error to the calling application. The default is RES_DFLRETRY (currently 2, see <resolv.h>).
rotate
sets RES_ROTATE in _res.options, which causes round robin selection of nameservers from among those listed. This has the effect of spreading the query load among all listed servers, rather than having all clients try the first listed server first every time.
no-check-names
sets RES_NOCHECKNAME in _res.options, which disables the modern BIND checking of incoming host names and mail names for invalid characters such as underscore (_), non-ASCII, or control characters.
inet6
sets RES_USE_INET6 in _res.options. This has the effect of trying a AAAA query before an A query inside the gethostbyname(3) function, and of mapping IPv4 responses in IPv6 ``tunneled form'' if no AAAA records are found but an A record set exists.

The domain and search keywords are mutually exclusive. If more than one instance of these keywords is present, the last instance wins.

The search keyword of a system's resolv.conf file can be overridden on a per-process basis by setting the environment variable ``LOCALDOMAIN'' to a space-separated list of search domains.

The options keyword of a system's resolv.conf file can be amended on a per-process basis by setting the environment variable ``RES_OPTIONS'' to a space-separated list of resolver options as explained above under options.

The keyword and value must appear on a single line, and the keyword (e.g., nameserver) must start the line. The value follows the keyword, separated by white space.

FILES

/etc/resolv.conf, <resolv.h>

SEE ALSO

gethostbyname(3), resolver(3), hostname(7), named(8)
Name Server Operations Guide for BIND


slabinfo(5)

SLABINFO

Section: Linux Programmer's Manual (5)
Updated: 2001-06-19 Return to Main Contents

NAME

/proc/slabinfo - Kernel slab allocator statistics

SYNOPSIS

cat /proc/slabinfo

DESCRIPTION

Frequently used objects in the Linux kernel (buffer heads, inodes, dentries, etc.) have their own cache. The file /proc/slabinfo gives statistics. For example:

% cat /proc/slabinfo
slabinfo - version: 1.1
kmem_cache            60     78    100    2    2    1
blkdev_requests     5120   5120     96  128  128    1
mnt_cache             20     40     96    1    1    1
inode_cache         7005  14792    480 1598 1849    1
dentry_cache        5469   5880    128  183  196    1
filp                 726    760     96   19   19    1
buffer_head        67131  71240     96 1776 1781    1
vm_area_struct      1204   1652     64   23   28    1
...
size-8192              1     17   8192    1   17    2
size-4096             41     73   4096   41   73    1
...

For each slab cache, the cache name, the number of currently active objects, the total number of available objects, the size of each object in bytes, the number of pages with at least one active object, the total number of allocated pages, and the number of pages per slab are given.

Note that because of object alignment and slab cache overhead, objects are not normally packed tightly into pages. Pages with even one in-use object are considered in-use and cannot be freed.

Kernels compiled with slab cache statistics will also have "(statistics)" in the first line of output, and will have 5 additional columns, namely: the high water mark of active objects; the number of times objects have been allocated; the number of times the cache has grown (new pages added to this cache); the number of times the cache has been reaped (unused pages removed from this cache); and the number of times there was an error allocating new pages to this cache. If slab cache statistics are not enabled for this kernel, these columns will not be shown.

SMP systems will also have "(SMP)" in the first line of output, and will have two additional columns for each slab, reporting the slab allocation policy for the CPU-local cache (to reduce the need for inter-CPU synchronization when allocating objects from the cache). The first column is the per-CPU limit: the maximum number of objects that will be cached for each CPU. The second column is the batchcount: the maximum number of free objects in the global cache that will be transferred to the per-CPU cache if it is empty, or the number of objects to be returned to the global cache if the per-CPU cache is full.

If both slab cache statistics and SMP are defined, there will be four additional columns, reporting the per-CPU cache statistics. The first two are the per-CPU cache allocation hit and miss counts: the number of times an object was or was not available in the per-CPU cache for allocation. The next two are the per-CPU cache free hit and miss counts: the number of times a freed object could or could not fit within the per-CPU cache limit, before flushing objects to the global cache.

It is possible to tune the SMP per-CPU slab cache limit and batchcount via:

echo "cache_name limit batchcount" > /proc/slabinfo

FILES

<linux/slab.h>

VERSIONS

/proc/slabinfo exists since Linux 2.1.23. SMP per-CPU caches exist since Linux 2.4.0-test3.


resolver(5)

Status: 403 Forbidden resolver(5)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man5/resolver.5 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


ftpusers(5)

FTPUSERS

Section: Linux Programmer's Manual (5)
Updated: 2000-08-27 Return to Main Contents

NAME

ftpusers - list of users that may not log in via the FTP daemon

DESCRIPTION

The text file ftpusers contains a list of users that may not log in using the File Transfer Protocol (FTP) server daemon. This file is used not merely for system administration purposes but for improving security within a TCP/IP networked environment. It will typically contain a list of the users that either have no business using ftp or have too many privileges to be allowed to log in through the FTP server daemon. Such users usually include root, daemon, bin, uucp, and news. If your FTP server daemon doesn't use ftpusers then it is suggested that you read its documentation to find out how to block access for certain users. Washington University FTP server Daemon (wuftpd) and Professional FTP Daemon (proftpd) are known to make use of ftpusers.

FORMAT

The format of ftpusers is very simple. There is one account name (or user name) per line. Lines starting with a # are ignored.

FILES

/etc/ftpusers

SEE ALSO

passwd(5), proftpd(8), wuftpd(8)


proc(5)

PROC

Section: Linux Programmer's Manual (5)
Updated: 2005-05-12 Return to Main Contents

NAME

proc - process information pseudo-filesystem

DESCRIPTION

The proc filesystem is a pseudo-filesystem which is used as an interface to kernel data structures. It is commonly mounted at /proc. Most of it is read-only, but some files allow kernel variables to be changed.

The following outline gives a quick tour through the /proc hierarchy.

/proc/[number]
There is a numerical subdirectory for each running process; the subdirectory is named by the process ID. Each such subdirectory contains the following pseudo-files and directories.
/proc/[number]/auxv (since 2.6.0-test7)
This contains the contents of the ELF interpreter information passed to the process at exec time. The format is one unsigned long ID plus one unsigned long value for each entry. The last entry contains two zeros.
/proc/[number]/cmdline
This holds the complete command line for the process, unless the whole process has been swapped out or the process is a zombie. In either of these latter cases, there is nothing in this file: that is, a read on this file will return 0 characters. The command line arguments appear in this file as a set of null-separated strings, with a further null byte after the last string.
/proc/[number]/cwd
This is a symbolic link to the current working directory of the process. To find out the cwd of process 20, for instance, you can do this:

cd /proc/20/cwd; /bin/pwd

Note that the pwd command is often a shell builtin, and might not work properly. In bash, you may use pwd -P.

In a multithreaded process, the contents of this symbolic link are not available if the main thread has already terminated (typically by calling pthread_exit(3).

/proc/[number]/environ
This file contains the environment for the process. The entries are separated by null bytes ('\0'), and there may be a null bytes at the end. Thus, to print out the environment of process 1, you would do:

(cat /proc/1/environ; echo) | tr "\000" "\n"

(For a reason why one should want to do this, see lilo(8).)

/proc/[number]/exe
Under Linux 2.2 and later, this file is a symbolic link containing the actual pathname of the executed command. This symbolic link can be dereferenced normally; attempting to open it will open the executable. You can even type /proc/[number]/exe to run another copy of the same executable as is being run by process [number]. In a multithreaded process, the contents of this symbolic link are not available if the main thread has already terminated (typically by calling pthread_exit(3)).

Under Linux 2.0 and earlier /proc/[number]/exe is a pointer to the binary which was executed, and appears as a symbolic link. A readlink(2) call on this file under Linux 2.0 returns a string in the format:

[device]:inode

For example, [0301]:1502 would be inode 1502 on device major 03 (IDE, MFM, etc. drives) minor 01 (first partition on the first drive).

find(1) with the -inum option can be used to locate the file.

/proc/[number]/fd
This is a subdirectory containing one entry for each file which the process has open, named by its file descriptor, and which is a symbolic link to the actual file. Thus, 0 is standard input, 1 standard output, 2 standard error, etc.

In a multithreaded process, the contents of this directory are not available if the main thread has already terminated (typically by calling pthread_exit(3)).

Programs that will take a filename, but will not take the standard input, and which write to a file, but will not send their output to standard output, can be effectively foiled this way, assuming that -i is the flag designating an input file and -o is the flag designating an output file:

foobar -i /proc/self/fd/0 -o /proc/self/fd/1 ...

and you have a working filter.

/proc/self/fd/N is approximately the same as /dev/fd/N in some UNIX and UNIX-like systems. Most Linux MAKEDEV scripts symbolically link /dev/fd to /proc/self/fd, in fact.

/proc/[number]/maps
A file containing the currently mapped memory regions and their access permissions.

The format is:

address           perms offset  dev   inode      pathname
08048000-08056000 r-xp 00000000 03:0c 64593      /usr/sbin/gpm
08056000-08058000 rw-p 0000d000 03:0c 64593      /usr/sbin/gpm
08058000-0805b000 rwxp 00000000 00:00 0
40000000-40013000 r-xp 00000000 03:0c 4165       /lib/ld-2.2.4.so
40013000-40015000 rw-p 00012000 03:0c 4165       /lib/ld-2.2.4.so
4001f000-40135000 r-xp 00000000 03:0c 45494      /lib/libc-2.2.4.so
40135000-4013e000 rw-p 00115000 03:0c 45494      /lib/libc-2.2.4.so
4013e000-40142000 rw-p 00000000 00:00 0
bffff000-c0000000 rwxp 00000000 00:00 0

where address is the address space in the process that it occupies, perms is a set of permissions:

r = read
w = write
x = execute
s = shared
p = private (copy on write)

offset is the offset into the file/whatever, dev is the device (major:minor), and inode is the inode on that device. 0 indicates that no inode is associated with the memory region, as the case would be with bss.

Under Linux 2.0 there is no field giving pathname.

/proc/[number]/mem
This file can be used to access the pages of a process's memory through open(2), read(2), and lseek(2).
/proc/[number]/root
Unix and Linux support the idea of a per-process root of the filesystem, set by the chroot(2) system call. This file is a symbolic link that points to the process's root directory, and behaves as exe, fd/*, etc. do.

In a multithreaded process, the contents of this symbolic link are not available if the main thread has already terminated (typically by calling pthread_exit(3)).

/proc/[number]/smaps (since Linux 2.6.14)
This file shows memory consumption for each of the process's mappings. For each of mappings there is a series of lines as follows:

08048000-080bc000 r-xp 00000000 03:02 13130      /bin/bash
Size:               464 kB
Rss:                424 kB
Shared_Clean:       424 kB
Shared_Dirty:         0 kB
Private_Clean:        0 kB
Private_Dirty:        0 kB
The first of these lines shows the same information as is displayed for the mapping in /proc/[number]/maps. The remaining lines show the size of the mapping, the amount of the mapping that is currently resident in RAM, the number clean and dirty shared pages in the mapping, and the number clean and dirty private pages in the mapping.

This file is only present if the CONFIG_MMU kernel configuration option is enabled.

/proc/[number]/stat
Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c.

The fields, in order, with their proper scanf(3) format specifiers, are:

pid %d
The process ID.
comm %s
The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out.
state %c
One character from the string "RSDZTW" where R is running, S is sleeping in an interruptible wait, D is waiting in uninterruptible disk sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging.
ppid %d
The PID of the parent.
pgrp %d
The process group ID of the process.
session %d
The session ID of the process.
tty_nr %d The tty the process uses.
tpgid %d
The process group ID of the process which currently owns the tty that the process is connected to.
flags %lu
The kernel flags word of the process. For bit meanings, see the PF_* defines in <linux/sched.h>. Details depend on the kernel version.
minflt %lu
The number of minor faults the process has made which have not required loading a memory page from disk.
cminflt %lu
The number of minor faults that the process's waited-for children have made.
majflt %lu
The number of major faults the process has made which have required loading a memory page from disk.
cmajflt %lu
The number of major faults that the process's waited-for children have made.
utime %lu
The number of jiffies that this process has been scheduled in user mode.
stime %lu
The number of jiffies that this process has been scheduled in kernel mode.
cutime %ld
The number of jiffies that this process's waited-for children have been scheduled in user mode. (See also times(2).)
cstime %ld
The number of jiffies that this process's waited-for children have been scheduled in kernel mode.
priority %ld
The standard nice value, plus fifteen. The value is never negative in the kernel.
nice %ld
The nice value ranges from 19 (nicest) to -19 (not nice to others).
0 %ld This value is hard coded to 0 as a placeholder for a removed field.
itrealvalue %ld
The time in jiffies before the next SIGALRM is sent to the process due to an interval timer.
starttime %lu
The time in jiffies the process started after system boot.
vsize %lu
Virtual memory size in bytes.
rss %ld
Resident Set Size: number of pages the process has in real memory, minus 3 for administrative purposes. This is just the pages which count towards text, data, or stack space. This does not include pages which have not been demand-loaded in, or which are swapped out.
rlim %lu
Current limit in bytes on the rss of the process (usually 4294967295 on i386).
startcode %lu
The address above which program text can run.
endcode %lu
The address below which program text can run.
startstack %lu
The address of the start of the stack.
kstkesp %lu
The current value of esp (stack pointer), as found in the kernel stack page for the process.
kstkeip %lu
The current EIP (instruction pointer).
signal %lu
The bitmap of pending signals.
blocked %lu
The bitmap of blocked signals.
sigignore %lu
The bitmap of ignored signals.
sigcatch %lu
The bitmap of caught signals.
wchan %lu
This is the "channel" in which the process is waiting. It is the address of a system call, and can be looked up in a namelist if you need a textual name. (If you have an up-to-date /etc/psdatabase, then try ps -l to see the WCHAN field in action.)
nswap %lu
Number of pages swapped (not maintained).
cnswap %lu
Cumulative nswap for child processes (not maintained).
exit_signal %d
Signal to be sent to parent when we die.
processor %d
CPU number last executed on.
rt_priority %lu (since kernel 2.5.19)
Real-time scheduling priority (see sched_setscheduler(2)).
policy %lu (since kernel 2.5.19)
Scheduling policy (see sched_setscheduler(2)).
delayacct_blkio_ticks (since kernel 2.6.18)
Aggregated block I/O delays (measured in clock ticks (centiseconds)).
/proc/[number]/statm
Provides information about memory status in pages. The columns are:
size total program size
resident resident set size
share shared pages
text text (code)
lib library
data data/stack
dt dirty pages (unused in Linux 2.6)
/proc/[number]/status
Provides much of the information in /proc/[number]/stat and /proc/[number]/statm in a format that's easier for humans to parse.
/proc/[number]/task (since kernel 2.6.0-test6)
This is a directory that contains one subdirectory for each thread in the process. The name of each subdirectory is the numerical thread ID of the thread (see gettid(2)). Within each of these subdirectories, there is a set of files with the same names and contents as under the /proc/[number] directories. For attributes that are shared by all threads, the contents for each of the files under the task/[thread-ID] subdirectories will be the same as in the corresponding file in the parent /proc/[number] directory (e.g., in a multithreaded process, all of the task/[thread-ID]/cwd files will have the same value as the /proc/[number]/cwd file in the parent directory, since all of the threads in a process share a working directory). For attributes that are distinct for each thread, the corresponding files under task/[thread-ID] may have different values (e.g., various fields in each of the task/[thread-ID]/status files may be different for each thread).

In a multithreaded process, the contents of the /proc/[number]/task directory are not available if the main thread has already terminated (typically by calling pthread_exit(3)).

/proc/apm
Advanced power management version and battery information when CONFIG_APM is defined at kernel compilation time.
/proc/bus
Contains subdirectories for installed busses.
/proc/bus/pccard
Subdirectory for pcmcia devices when CONFIG_PCMCIA is set at kernel compilation time.
/proc/bus/pccard/drivers
/proc/bus/pci
Contains various bus subdirectories and pseudo-files containing information about pci busses, installed devices, and device drivers. Some of these files are not ASCII.
/proc/bus/pci/devices
Information about pci devices. They may be accessed through lspci(8) and setpci(8).
/proc/cmdline
Arguments passed to the Linux kernel at boot time. Often done via a boot manager such as lilo(1).
/proc/cpuinfo
This is a collection of CPU and system architecture dependent items, for each supported architecture a different list. Two common entries are processor which gives CPU number and bogomips; a system constant that is calculated during kernel initialization. SMP machines have information for each CPU.
/proc/devices
Text listing of major numbers and device groups. This can be used by MAKEDEV scripts for consistency with the kernel.
/proc/diskstats (since Linux 2.5.69)
This file contains disk I/O statistics for each disk device. See the kernel source file Documentation/iostats.txt for further information.
/proc/dma
This is a list of the registered ISA DMA (direct memory access) channels in use.
/proc/driver
Empty subdirectory.
/proc/execdomains
List of the execution domains (ABI personalities).
/proc/fb
Frame buffer information when CONFIG_FB is defined during kernel compilation.
/proc/filesystems
A text listing of the filesystems which were compiled into the kernel. Incidentally, this is used by mount(1) to cycle through different filesystems when none is specified.
/proc/fs
Empty subdirectory.
/proc/ide
This directory exists on systems with the ide bus. There are directories for each ide channel and attached device. Files include:

cache              buffer size in KB
capacity           number of sectors
driver             driver version
geometry           physical and logical geometry
identify           in hexadecimal
media              media type
model              manufacturer's model number
settings           drive settings
smart_thresholds   in hexadecimal
smart_values       in hexadecimal

The hdparm(8) utility provides access to this information in a friendly format.

/proc/interrupts
This is used to record the number of interrupts per each IRQ on (at least) the i386 architecture. Very easy to read formatting, done in ASCII.
/proc/iomem
I/O memory map in Linux 2.4.
/proc/ioports
This is a list of currently registered Input-Output port regions that are in use.
/proc/kallsyms (since Linux 2.5.71)
This holds the kernel exported symbol definitions used by the modules(X) tools to dynamically link and bind loadable modules. In Linux 2.5.47 and earlier, a similar file with slightly different syntax was named ksyms.
/proc/kcore
This file represents the physical memory of the system and is stored in the ELF core file format. With this pseudo-file, and an unstripped kernel (/usr/src/linux/vmlinux) binary, GDB can be used to examine the current state of any kernel data structures.

The total length of the file is the size of physical memory (RAM) plus 4KB.

/proc/kmsg
This file can be used instead of the syslog(2) system call to read kernel messages. A process must have superuser privileges to read this file, and only one process should read this file. This file should not be read if a syslog process is running which uses the syslog(2) system call facility to log kernel messages.

Information in this file is retrieved with the dmesg(8) program.

/proc/ksyms (Linux 1.1.23-2.5.47)
See /proc/kallsyms.
/proc/loadavg
The first three fields in this file are load average figures giving the number of jobs in the run queue (state R) or waiting for disk I/O (state D) averaged over 1, 5, and 15 minutes. They are the same as the load average numbers given by uptime(1) and other programs. The fourth field consists of two numbers separated by a slash (/). The first of these is the number of currently executing kernel scheduling entities (processes, threads); this will be less than or equal to the number of CPUs. The value after the slash is the number of kernel scheduling entities that currently exist on the system. The fifth field is the PID of the process that was most recently created on the system.
/proc/locks
This file shows current file locks (flock(2) and fcntl(2)) and leases (fcntl(2)).
/proc/malloc
This file is only present if CONFIGDEBUGMALLOC was defined during compilation.
/proc/meminfo
This is used by free(1) to report the amount of free and used memory (both physical and swap) on the system as well as the shared memory and buffers used by the kernel.

It is in the same format as free(1), except in bytes rather than KB.

/proc/mounts
This is a list of all the file systems currently mounted on the system. The format of this file is documented in fstab(5). Since kernel version 2.6.15, this file is pollable: after opening the file for reading, a change in this file (i.e., a file system mount or unmount) causes select(2) to mark the file descriptor as readable, and poll(2) and epoll_wait(2) mark the file as having an error condition.
/proc/modules
A text list of the modules that have been loaded by the system. See also lsmod(8).
/proc/mtrr
Memory Type Range Registers. See /usr/src/linux/Documentation/mtrr.txt for details.
/proc/net
various net pseudo-files, all of which give the status of some part of the networking layer. These files contain ASCII structures and are, therefore, readable with cat. However, the standard netstat(8) suite provides much cleaner access to these files.
/proc/net/arp
This holds an ASCII readable dump of the kernel ARP table used for address resolutions. It will show both dynamically learned and pre-programmed ARP entries. The format is:

IP address     HW type   Flags     HW address          Mask   Device
192.168.0.50   0x1       0x2       00:50:BF:25:68:F3   *      eth0
192.168.0.250  0x1       0xc       00:00:00:00:00:00   *      eth0

Here 'IP address' is the IPv4 address of the machine and the 'HW type' is the hardware type of the address from RFC 826. The flags are the internal flags of the ARP structure (as defined in /usr/include/linux/if_arp.h) and the 'HW address' is the data link layer mapping for that IP address if it is known.

/proc/net/dev
The dev pseudo-file contains network device status information. This gives the number of received and sent packets, the number of errors and collisions and other basic statistics. These are used by the ifconfig(8) program to report device status. The format is:

Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo: 2776770   11307    0    0    0     0          0         0  2776770   11307    0    0    0     0       0          0
  eth0: 1215645    2751    0    0    0     0          0         0  1782404    4324    0    0    0   427       0          0
  ppp0: 1622270    5552    1    0    0     0          0         0   354130    5669    0    0    0     0       0          0
  tap0:    7714      81    0    0    0     0          0         0     7714      81    0    0    0     0       0          0
/proc/net/dev_mcast
Defined in /usr/src/linux/net/core/dev_mcast.c:
indx interface_name  dmi_u dmi_g dmi_address
2    eth0            1     0     01005e000001
3    eth1            1     0     01005e000001
4    eth2            1     0     01005e000001
/proc/net/igmp
Internet Group Management Protocol. Defined in /usr/src/linux/net/core/igmp.c.
/proc/net/rarp
This file uses the same format as the arp file and contains the current reverse mapping database used to provide rarp(8) reverse address lookup services. If RARP is not configured into the kernel, this file will not be present.
/proc/net/raw
Holds a dump of the RAW socket table. Much of the information is not of use apart from debugging. The 'sl' value is the kernel hash slot for the socket, the 'local address' is the local address and protocol number pair."St" is the internal status of the socket. The "tx_queue" and "rx_queue" are the outgoing and incoming data queue in terms of kernel memory usage. The "tr", "tm->when", and "rexmits" fields are not used by RAW. The "uid" field holds the effective UID of the creator of the socket.
/proc/net/snmp
This file holds the ASCII data needed for the IP, ICMP, TCP, and UDP management information bases for an snmp agent.
/proc/net/tcp
Holds a dump of the TCP socket table. Much of the information is not of use apart from debugging. The "sl" value is the kernel hash slot for the socket, the "local address" is the local address and port number pair. The "remote address" is the remote address and port number pair (if connected). 'St' is the internal status of the socket. The 'tx_queue' and 'rx_queue' are the outgoing and incoming data queue in terms of kernel memory usage. The "tr", "tm->when", and "rexmits" fields hold internal information of the kernel socket state and are only useful for debugging. The "uid" field holds the effective UID of the creator of the socket.
/proc/net/udp
Holds a dump of the UDP socket table. Much of the information is not of use apart from debugging. The "sl" value is the kernel hash slot for the socket, the "local address" is the local address and port number pair. The "remote address" is the remote address and port number pair (if connected). "St" is the internal status of the socket. The "tx_queue" and "rx_queue" are the outgoing and incoming data queue in terms of kernel memory usage. The "tr", "tm->when", and "rexmits" fields are not used by UDP. The "uid" field holds the effective UID of the creator of the socket. The format is:

sl  local_address rem_address   st tx_queue rx_queue tr rexmits  tm->when uid
 1: 01642C89:0201 0C642C89:03FF 01 00000000:00000001 01:000071BA 00000000 0
 1: 00000000:0801 00000000:0000 0A 00000000:00000000 00:00000000 6F000100 0
 1: 00000000:0201 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0
/proc/net/unix
Lists the UNIX domain sockets present within the system and their status. The format is:

Num RefCount Protocol Flags    Type St Path
 0: 00000002 00000000 00000000 0001 03
 1: 00000001 00000000 00010000 0001 01 /dev/printer

Here 'Num' is the kernel table slot number, 'RefCount' is the number of users of the socket, 'Protocol' is currently always 0, 'Flags' represent the internal kernel flags holding the status of the socket. Currently, type is always '1' (Unix domain datagram sockets are not yet supported in the kernel). 'St' is the internal state of the socket and Path is the bound path (if any) of the socket.

/proc/partitions
Contains major and minor numbers of each partition as well as number of blocks and partition name.
/proc/pci
This is a listing of all PCI devices found during kernel initialization and their configuration.
/proc/scsi
A directory with the scsi mid-level pseudo-file and various SCSI lowlevel driver directories, which contain a file for each SCSI host in this system, all of which give the status of some part of the SCSI IO subsystem. These files contain ASCII structures and are, therefore, readable with cat.

You can also write to some of the files to reconfigure the subsystem or switch certain features on or off.

/proc/scsi/scsi
This is a listing of all SCSI devices known to the kernel. The listing is similar to the one seen during bootup. scsi currently supports only the add-single-device command which allows root to add a hotplugged device to the list of known devices.

An echo 'scsi add-single-device 1 0 5 0' > /proc/scsi/scsi will cause host scsi1 to scan on SCSI channel 0 for a device on ID 5 LUN 0. If there is already a device known on this address or the address is invalid, an error will be returned.

/proc/scsi/[drivername]
[drivername] can currently be NCR53c7xx, aha152x, aha1542, aha1740, aic7xxx, buslogic, eata_dma, eata_pio, fdomain, in2000, pas16, qlogic, scsi_debug, seagate, t128, u15-24f, ultrastore, or wd7000. These directories show up for all drivers that registered at least one SCSI HBA. Every directory contains one file per registered host. Every host-file is named after the number the host was assigned during initialization.

Reading these files will usually show driver and host configuration, statistics etc.

Writing to these files allows different things on different hosts. For example, with the latency and nolatency commands, root can switch on and off command latency measurement code in the eata_dma driver. With the lockup and unlock commands, root can control bus lockups simulated by the scsi_debug driver.

/proc/self
This directory refers to the process accessing the /proc filesystem, and is identical to the /proc directory named by the process ID of the same process.
/proc/slabinfo
Information about kernel caches. The columns are:
cache-name
num-active-objs
total-objs
object-size
num-active-slabs
total-slabs
num-pages-per-slab
See slabinfo(5) for details.
/proc/stat
kernel/system statistics. Varies with architecture. Common entries include:
cpu 3357 0 4313 1362393
The amount of time, measured in units of USER_HZ (1/100ths of a second on most architectures), that the system spent in user mode, user mode with low priority (nice), system mode, and the idle task, respectively. The last value should be USER_HZ times the second entry in the uptime pseudo-file.

In Linux 2.6 this line includes three additional columns: iowait - time waiting for I/O to complete (since 2.5.41); irq - time servicing interrupts (since 2.6.0-test4); softirq - time servicing softirqs (since 2.6.0-test4).

page 5741 1808
The number of pages the system paged in and the number that were paged out (from disk).
swap 1 0
The number of swap pages that have been brought in and out.
intr 1462898 This line shows counts of interrupts serviced since boot time, for each of the possible system interrupts. The first column is the total of all interrupts serviced; each subsequent column is the total for a particular interrupt.
disk_io: (2,0):(31,30,5764,1,2) (3,0):...
(major,minor):(noinfo, read_io_ops, blks_read, write_io_ops, blks_written)
(Linux 2.4 only)
ctxt 115315
The number of context switches that the system underwent.
btime 769041601
boot time, in seconds since the epoch (January 1, 1970).
processes 86031
Number of forks since boot.
procs_running 6
Number of processes in runnable state. (Linux 2.5.45 onwards.)
procs_blocked 2
Number of processes blocked waiting for I/O to complete. (Linux 2.5.45 onwards.)
/proc/swaps
Swap areas in use. See also swapon(8).
/proc/sys
This directory (present since 1.3.57) contains a number of files and subdirectories corresponding to kernel variables. These variables can be read and sometimes modified using the proc file system, and the sysctl(2) system call. Presently, there are subdirectories abi, debug, dev, fs, kernel, net, proc, rxrpc, sunrpc and vm that each contain more files and subdirectories.
/proc/sys/abi
This directory may contain files with application binary information. On some systems, it is not present.
/proc/sys/debug
This directory may be empty.
/proc/sys/dev
This directory contains device specific information (eg dev/cdrom/info). On some systems, it may be empty.
/proc/sys/fs
This contains the subdirectories binfmt_misc, inotify, and mqueue, and files dentry-state, dir-notify-enable, dquot-nr, file-max, file-nr, inode-max, inode-nr, inode-state, lease-break-time, leases-enable, overflowgid, overflowuid, suid_dumpable, super-max, and super-nr.
/proc/sys/fs/binfmt_misc
Documentation for files in this directory can be found in the kernel sources in Documentation/binfmt_misc.txt.
/proc/sys/fs/dentry-state
This file contains six numbers, nr_dentry, nr_unused, age_limit (age in seconds), want_pages (pages requested by system) and two dummy values. nr_dentry seems to be 0 all the time. nr_unused seems to be the number of unused dentries. age_limit is the age in seconds after which dcache entries can be reclaimed when memory is short and want_pages is non-zero when the kernel has called shrink_dcache_pages() and the dcache isn't pruned yet.
/proc/sys/fs/dir-notify-enable
This file can be used to disable or enable the dnotify interface described in fcntl(2) on a system-wide basis. A value of 0 in this file disables the interface, and a value of 1 enables it.
/proc/sys/fs/dquot-max
This file shows the maximum number of cached disk quota entries. On some (2.4) systems, it is not present. If the number of free cached disk quota entries is very low and you have some awesome number of simultaneous system users, you might want to raise the limit.
/proc/sys/fs/dquot-nr
This file shows the number of allocated disk quota entries and the number of free disk quota entries.
/proc/sys/fs/file-max
This file defines a system-wide limit on the number of open files for all processes. (See also setrlimit(2), which can be used by a process to set the per-process limit, RLIMIT_NOFILE, on the number of files it may open.) If you get lots of error messages about running out of file handles, try increasing this value:

echo 100000 > /proc/sys/fs/file-max

The kernel constant NR_OPEN imposes an upper limit on the value that may be placed in file-max.

If you increase /proc/sys/fs/file-max, be sure to increase /proc/sys/fs/inode-max to 3-4 times the new value of /proc/sys/fs/file-max, or you will run out of inodes.

/proc/sys/fs/file-nr
This (read-only) file gives the number of files presently opened. It contains three numbers: The number of allocated file handles, the number of free file handles and the maximum number of file handles. The kernel allocates file handles dynamically, but it doesn't free them again. If the number of allocated files is close to the

maximum, you should consider increasing the maximum. When the number of free file handles is large, you've encountered a peak in your usage of file handles and you probably don't need to increase the maximum.

/proc/sys/fs/inode-max
This file contains the maximum number of in-memory inodes. On some (2.4) systems, it may not be present. This value should be 3-4 times larger than the value in file-max, since stdin, stdout and network sockets also need an inode to handle them. When you regularly run out of inodes, you need to increase this value.
/proc/sys/fs/inode-nr
This file contains the first two values from inode-state.
/proc/sys/fs/inode-state
This file contains seven numbers: nr_inodes, nr_free_inodes, preshrink and four dummy values. nr_inodes is the number of inodes the system has allocated. This can be slightly more than inode-max because Linux allocates them one page full at a time. nr_free_inodes represents the number of free inodes. preshrink is non-zero when the nr_inodes > inode-max and the system needs to prune the inode list instead of allocating more.
/proc/sys/fs/inotify (since Linux 2.6.13)
This directory contains files max_queued_events, max_user_instances, and max_user_watches, that can be used to limit the amount of kernel memory consumed by the inotify interface. For further details, see inotify(7).
/proc/sys/fs/lease-break-time
This file specifies the grace period that the kernel grants to a process holding a file lease (fcntl(2)) after it has sent a signal to that process notifying it that another process is waiting to open the file. If the lease holder does not remove or downgrade the lease within this grace period, the kernel forcibly breaks the lease.
/proc/sys/fs/leases-enable
This file can be used to enable or disable file leases (fcntl(2)) on a system-wide basis. If this file contains the value 0, leases are disabled. A non-zero value enables leases.
/proc/sys/fs/mqueue (since Linux 2.6.6)
This directory contains files msg_max, msgsize_max, and queues_max, controlling the resources used by POSIX message queues. See mq_overview(7) for details.
/proc/sys/fs/overflowgid and /proc/sys/fs/overflowuid
These files allow you to change the value of the fixed UID and GID. The default is 65534. Some filesystems only support 16-bit UIDs and GIDs, although in Linux UIDs and GIDs are 32 bits. When one of these filesystems is mounted with writes enabled, any UID or GID that would exceed 65535 is translated to the overflow value before being written to disk.
/proc/sys/fs/suid_dumpable (since Linux 2.6.13)
The value in this file determines whether core dump files are produced for set-user-ID or otherwise protected/tainted binaries. Three different integer values can be specified:

0 (default) This provides the traditional (pre-Linux 2.6.13) behavior. A core dump will not be produced for a process which has changed credentials (by calling seteuid(2), setgid(2), or similar, or by executing a set-user-ID or set-group-ID program) or whose binary does not have read permission enabled.

1 ("debug") All processes dump core when possible. The core dump is owned by the file system user ID of the dumping process and no security is applied. This is intended for system debugging situations only. Ptrace is unchecked.

2 ("suidsafe") Any binary which normally would not be dumped (see "0" above) is dumped readable by root only. This allows the user to remove the core dump file but not to read it. For security reasons core dumps in this mode will not overwrite one another or other files. This mode is appropriate when administrators are attempting to debug problems in a normal environment.

/proc/sys/fs/super-max
This file controls the maximum number of superblocks, and thus the maximum number of mounted filesystems the kernel can have. You only need to increase super-max if you need to mount more filesystems than the current value in super-max allows you to.
/proc/sys/fs/super-nr
This file contains the number of filesystems currently mounted.
/proc/sys/kernel
This directory contains files acct, cad_pid, cap-bound, core_pattern, core_uses_pid, ctrl-alt-del, dentry-state, domainname, hotplug, hostname, htab-reclaim (PowerPC only), java-appletviewer (binfmt_java, obsolete), java-interpreter (binfmt_java, obsolete), l2cr (PowerPC only), modprobe, msgmax, msgmnb, msgmni, osrelease, ostype, overflowgid, overflowuid, panic, panic_on_oops, pid_max, powersave-nap (PowerPC only), printk, pty, random, real-root-dev, reboot-cmd (SPARC only), rtsig-max, rtsig-nr, sem, sg-big-buff, shmall, shmmax, shmmni, sysrq, tainted, threads-max, version, and zero-paged (PowerPC only).
/proc/sys/kernel/acct
This file contains three numbers: highwater, lowwater and frequency. If BSD-style process accounting is enabled these values control its behavior. If free space on filesystem where the log lives goes below lowwater percent accounting suspends. If free space gets above highwater percent accounting resumes. Frequency determines how often the kernel checks the amount of free space (value is in seconds). Default values are 4, 2 and 30. That is, suspend accounting if <= 2% of space is free; resume it if >= 4% of space is free; consider information about amount of free space valid for 30 seconds.
/proc/sys/kernel/cap-bound
This file holds the value of the kernel capability bounding set (expressed as a signed decimal number). This set is ANDed against the capabilities permitted to a process during execve(2).
/proc/sys/kernel/core_pattern
See core(5). /proc/sys/kernel/core_uses_pid See core(5).
/proc/sys/kernel/ctrl-alt-del
This file controls the handling of Ctrl-Alt-Del from the keyboard. When the value in this file is 0, Ctrl-Alt-Del is trapped and sent to the init(1) program to handle a graceful restart. When the value is > 0, Linux's reaction to a Vulcan Nerve Pinch (tm) will be an immediate reboot, without even syncing its dirty buffers. Note: when a program (like dosemu) has the keyboard in 'raw' mode, the ctrl-alt-del is intercepted by the program before it ever reaches the kernel tty layer, and it's up to the program to decide what to do with it.
/proc/sys/kernel/hotplug
This file contains the path for the hotplug policy agent. The default value in this file "/sbin/hotplug".
/proc/sys/kernel/domainname and /proc/sys/kernel/hostname
can be used to set the NIS/YP domainname and the hostname of your box in exactly the same way as the commands domainname and hostname, that is:

# echo "darkstar" > /proc/sys/kernel/hostname
# echo "mydomain" > /proc/sys/kernel/domainname

has the same effect as

# hostname "darkstar"
# domainname "mydomain"

Note, however, that the classic darkstar.frop.org has the hostname "darkstar" and DNS (Internet Domain Name Server) domainname "frop.org", not to be confused with the NIS (Network Information Service) or YP (Yellow Pages) domainname. These two domain names are in general different. For a detailed discussion see the hostname(1) man page.

/proc/sys/kernel/htab-reclaim
(PowerPC only) If this file is set to a non-zero value, the PowerPC htab (see kernel file Documentation/powerpc/ppc_htab.txt) is pruned each time the system hits the idle loop.
/proc/sys/kernel/l2cr
(PowerPC only) This file contains a flag that controls the L2 cache of G3 processor boards. If 0, the cache is disabled. Enabled if non-zero.
/proc/sys/kernel/modprobe
This file is described by the kernel source file Documentation/kmod.txt.
/proc/sys/kernel/msgmax
This file defines a system-wide limit specifying the maximum number of bytes in a single message written on a System V message queue.
/proc/sys/kernel/msgmni
This file defines the system-wide limit on the number of message queue identifiers. (This file is only present in Linux 2.4 onwards.)
/proc/sys/kernel/msgmnb
This file defines a system-wide parameter used to initialize the msg_qbytes setting for subsequently created message queues. The msg_qbytes setting specifies the maximum number of bytes that may be written to the message queue.
/proc/sys/kernel/ostype and /proc/sys/kernel/osrelease
These files give substrings of /proc/version.
/proc/sys/kernel/overflowgid and /proc/sys/kernel/overflowuid
These files duplicate the files /proc/sys/fs/overflowgid and /proc/sys/fs/overflowuid.
/proc/sys/kernel/panic
gives read/write access to the kernel variable panic_timeout. If this is zero, the kernel will loop on a panic; if non-zero it indicates that the kernel should autoreboot after this number of seconds. When you use the software watchdog device driver, the recommended setting is 60.
/proc/sys/kernel/panic_on_oops
This file (new in Linux 2.5) controls the kernel's behavior when an oops or BUG is encountered. If this file contains 0, then the system tries to continue operation. If it contains 1, then the system delays a few seconds (to give klogd time to record the oops output) and then panics. If the /proc/sys/kernel/panic file is also non-zero then the machine will be rebooted.
/proc/sys/kernel/pid_max
This file (new in Linux 2.5) specifies the value at which PIDs wrap around (i.e., the value in this file is one greater than the maximum PID). The default value for this file, 32768, results in the same range of PIDs as on earlier kernels. On 32-bit platforms, 32768 is the maximum value for pid_max. On 64-bit systems, pid_max can be set to any value up to 2^22 (PID_MAX_LIMIT, approximately 4 million).
/proc/sys/kernel/powersave-nap (PowerPC only)
This file contains a flag. If set, Linux-PPC will use the 'nap' mode of powersaving, otherwise the 'doze' mode will be used.
/proc/sys/kernel/printk
The four values in this file are console_loglevel, default_message_loglevel, minimum_console_level and default_console_loglevel. These values influence printk() behavior when printing or logging error messages. See syslog(2) for more info on the different loglevels. Messages with a higher priority than console_loglevel will be printed to the console. Messages without an explicit priority will be printed with priority default_message_level. minimum_console_loglevel is the minimum (highest) value to which console_loglevel can be set. default_console_loglevel is the default value for console_loglevel.
/proc/sys/kernel/pty (since Linux 2.6.4)
This directory contains two files relating to the number of Unix 98 pseudo-terminals (see pts(4)) on the system.
/proc/sys/kernel/pty/max
This file defines the maximum number of pseudo-terminals.
/proc/sys/kernel/pty/nr
This read-only file indicates how many pseudo-terminals are currently in use.
/proc/sys/kernel/random
This directory contains various parameters controlling the operation of the file /dev/random. See random(4) for further information.
/proc/sys/kernel/real-root-dev
This file is documented in the kernel source file Documentation/initrd.txt.
/proc/sys/kernel/reboot-cmd (Sparc only)
This file seems to be a way to give an argument to the SPARC ROM/Flash boot loader. Maybe to tell it what to do after rebooting?
/proc/sys/kernel/rtsig-max
(Only in kernels up to and including 2.6.7; see setrlimit(2)) This file can be used to tune the maximum number of POSIX realtime (queued) signals that can be outstanding in the system.
/proc/sys/kernel/rtsig-nr
(Only in kernels up to and including 2.6.7.) This file shows the number POSIX realtime signals currently queued.
/proc/sys/kernel/sem (since Linux 2.4)
This file contains 4 numbers defining limits for System V IPC semaphores. These fields are, in order:
SEMMSL
The maximum semaphores per semaphore set.
SEMMNS
A system-wide limit on the number of semaphores in all semaphore sets.
SEMOPM
The maximum number of operations that may be specified in a semop(2) call.
SEMMNI
A system-wide limit on the maximum number of semaphore identifiers.
/proc/sys/kernel/sg-big-buff
This file shows the size of the generic SCSI device (sg) buffer. You can't tune it just yet, but you could change it on compile time by editing include/scsi/sg.h and changing the value of SG_BIG_BUFF. However, there shouldn't be any reason to change this value.
/proc/sys/kernel/shmall
This file contains the system-wide limit on the total number of pages of System V shared memory.
/proc/sys/kernel/shmmax
This file can be used to query and set the run time limit on the maximum (System V IPC) shared memory segment size that can be created. Shared memory segments up to 1Gb are now supported in the kernel. This value defaults to SHMMAX.
/proc/sys/kernel/shmmni
(available in Linux 2.4 and onwards) This file specifies the system-wide maximum number of System V shared memory segments that can be created.
/proc/sys/kernel/version
contains a string like:

#5 Wed Feb 25 21:49:24 MET 1998.TP

The '#5' means that this is the fifth kernel built from this source base and the date behind it indicates the time the kernel was built.

/proc/sys/kernel/zero-paged (PowerPC only)
This file contains a flag. When enabled (non-zero), Linux-PPC will pre-zero pages in the idle loop, possibly speeding up get_free_pages.
/proc/sys/net
This directory contains networking stuff. Explanations for some of the files under this directory can be found in tcp(7) and ip(7).
/proc/sys/net/core/somaxconn
This file defines a ceiling value for the backlog argument of listen(2); see the listen(2) manual page for details.
/proc/sys/proc
This directory may be empty.
/proc/sys/sunrpc
This directory supports Sun remote procedure call for network file system (NFS). On some systems, it is not present.
/proc/sys/vm
This directory contains files for memory management tuning, buffer and cache management.
/proc/sys/vm/drop_caches (since Linux 2.6.16)
Writing to this file causes the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.

To free pagecache, use echo 1 > /proc/sys/vm/drop_caches; to free dentries and inodes, use echo 2 > /proc/sys/vm/drop_caches; to free pagecache, dentries and inodes, use echo 3 > /proc/sys/vm/drop_caches.

Because this is a non-destructive operation and dirty objects are not freeable, the user should run sync(8) first.

/proc/sys/vm/legacy_va_layout (since Linux 2.6.9)
If non-zero, this disable the new 32-bit memory-mapping layout; the kernel will use the legacy (2.4) layout for all processes.
/proc/sys/vm/overcommit_memory
This file contains the kernel virtual memory accounting mode. Values are:
0: heuristic overcommit (this is the default)
1: always overcommit, never check
2: always check, never overcommit
In mode 0, calls of mmap(2) with MAP_NORESERVE set are not checked, and the default check is very weak, leading to the risk of getting a process "OOM-killed". Under Linux 2.4 any non-zero value implies mode 1. In mode 2 (available since Linux 2.6), the total virtual address space on the system is limited to (SS + RAM*(r/100)), where SS is the size of the swap space, and RAM is the size of the physical memory, and r is the contents of the file /proc/sys/vm/overcommit_ratio.
/proc/sys/vm/overcommit_ratio
See the description of /proc/sys/vm/overcommit_memory.
/proc/sysvipc
Subdirectory containing the pseudo-files msg, sem and shm. These files list the System V Interprocess Communication (IPC) objects (respectively: message queues, semaphores, and shared memory) that currently exist on the system, providing similar information to that available via ipcs(1). These files have headers and are formatted (one IPC object per line) for easy understanding. svipc(7) provides further background on the information shown by these files.
/proc/tty
Subdirectory containing the pseudo-files and subdirectories for tty drivers and line disciplines.
/proc/uptime
This file contains two numbers: the uptime of the system (seconds), and the amount of time spent in idle process (seconds).
/proc/version
This string identifies the kernel version that is currently running. It includes the contents of /proc/sys/ostype, /proc/sys/osrelease and /proc/sys/version. For example:
Linux version 1.0.9 (quinlan@phaze) #1 Sat May 14 01:51:54 EDT 1994
/proc/vmstat (since Linux 2.6)
This file displays various virtual memory statistics.
/proc/zoneinfo (since Linux 2.6.13)
This file display information about memory zones. This is useful for analyzing virtual memory behavior.

NOTES

Many strings (i.e., the environment and command line) are in the internal format, with sub-fields terminated by null bytes ('\0'), so you may find that things are more readable if you use od -c or tr "\000" "\n" to read them. Alternatively, echo `cat <file>` works well.

This manual page is incomplete, possibly inaccurate, and is the kind of thing that needs to be updated very often.

SEE ALSO

cat(1), find(1), free(1), mount(1), ps(1), tr(1), uptime(1), chroot(2), mmap(2), readlink(2), syslog(2), slabinfo(5), hier(7), arp(8), dmesg(8), hdparm(8), ifconfig(8), init(8), lsmod(8), lspci(8), netstat(8), procinfo(8), route(8)
/usr/src/linux/Documentation/filesystems/proc.txt


elf(5)

ELF

Section: File Formats (5) Return to Main Contents

BSD mandoc

NAME

elf - format of Executable and Linking Format (ELF) files

SYNOPSIS

Fd #include <elf.h>

DESCRIPTION

The header file Aq Pa elf.h defines the format of ELF executable binary files. Amongst these files are normal executable files, relocatable object files, core files and shared libraries.

An executable file using the ELF file format consists of an ELF header, followed by a program header table or a section header table, or both. The ELF header is always at offset zero of the file. The program header table and the section header table's offset in the file are defined in the ELF header. The two tables describe the rest of the particularities of the file.

This header file describes the above mentioned headers as C structures and also includes structures for dynamic sections, relocation sections and symbol tables.

The following types are used for N-bit architectures (N=32,64, ElfN stands for Elf32 or Elf64, uintN_t stands for uint32_t or uint64_t):

ElfN_Addr       Unsigned program address, uintN_t
ElfN_Off        Unsigned file offset, uintN_t
ElfN_Section    Unsigned section index, uint16_t
ElfN_Versym     Unsigned version symbol information, uint16_t
Elf_Byte        unsigned char
ElfN_Half       uint16_t
ElfN_Sword      int32_t
ElfN_Word       uint32_t
ElfN_Sxword     int64_t
ElfN_Xword      uint64_t

(Note: The *BSD terminology is a bit different. There Elf64_Half is twice as large as Elf32_Half, and Elf64Quarter is used for uint16_t. In order to avoid confusion these types are replaced by explicit ones in the below.)

All data structures that the file format defines follow the ``natural'' size and alignment guidelines for the relevant class. If necessary, data structures contain explicit padding to ensure 4-byte alignment for 4-byte objects, to force structure sizes to a multiple of 4, etc.

The ELF header is described by the type Elf32_Ehdr or Elf64_Ehdr:

#define EI_NIDENT 16

typedef struct {
        unsigned char  e_ident[EI_NIDENT];
        uint16_t       e_type;
        uint16_t       e_machine;
        uint32_t       e_version;
        ElfN_Addr      e_entry;
        ElfN_Off       e_phoff;
        ElfN_Off       e_shoff;
        uint32_t       e_flags;
        uint16_t       e_ehsize;
        uint16_t       e_phentsize;
        uint16_t       e_phnum;
        uint16_t       e_shentsize;
        uint16_t       e_shnum;
        uint16_t       e_shstrndx;
} ElfN_Ehdr;

The fields have the following meanings:

e_ident
This array of bytes specifies to interpret the file, independent of the processor or the file's remaining contents. Within this array everything is named by macros, which start with the prefix EI_ and may contain values which start with the prefix ELF The following macros are defined:

EI_MAG0
The first byte of the magic number. It must be filled with ELFMAG0 (0: 0x7f)
EI_MAG1
The second byte of the magic number. It must be filled with ELFMAG1 (1: 'E')
EI_MAG2
The third byte of the magic number. It must be filled with ELFMAG2 (2: 'L')
EI_MAG3
The fourth byte of the magic number. It must be filled with ELFMAG3 (3: 'F')
EI_CLASS
The fifth byte identifies the architecture for this binary:

ELFCLASSNONE
This class is invalid.
ELFCLASS32
This defines the 32-bit architecture. It supports machines with files and virtual address spaces up to 4 Gigabytes.
ELFCLASS64
This defines the 64-bit architecture.

EI_DATA
The sixth byte specifies the data encoding of the processor-specific data in the file. Currently these encodings are supported:

ELFDATANONE
Unknown data format.
ELFDATA2LSB
Two's complement, little-endian.
ELFDATA2MSB
Two's complement, big-endian.

EI_VERSION
The version number of the ELF specification:

EV_NONE
Invalid version.
EV_CURRENT
Current version.

EI_OSABI
This byte identifies the operating system and ABI to which the object is targeted. Some fields in other ELF structures have flags and values that have platform specific meanings; the interpretation of those fields is determined by the value of this byte. E.g.:

ELFOSABI_NONE
Same as ELFOSABI_SYSV
ELFOSABI_SYSV
UNIX System V ABI.
ELFOSABI_HPUX
HP-UX ABI.
ELFOSABI_NETBSD
NetBSD ABI.
ELFOSABI_LINUX
Linux ABI.
ELFOSABI_SOLARIS
Solaris ABI.
ELFOSABI_IRIX
IRIX ABI.
ELFOSABI_FREEBSD
FreeBSD ABI.
ELFOSABI_TRU64
TRU64 UNIX ABI.
ELFOSABI_ARM
ARM architecture ABI.
ELFOSABI_STANDALONE
Stand-alone (embedded) ABI.

EI_ABIVERSION
This byte identifies the version of the ABI to which the object is targeted. This field is used to distinguish among incompatible versions of an ABI. The interpretation of this version number is dependent on the ABI identified by the EI_OSABI field. Applications conforming to this specification use the value 0.
EI_PAD
Start of padding. These bytes are reserved and set to zero. Programs which read them should ignore them. The value for EI_PAD will change in the future if currently unused bytes are given meanings.
EI_BRAND
Start of architecture identification.
EI_NIDENT
The size of the e_ident array.

e_type
This member of the structure identifies the object file type:

ET_NONE
An unknown type.
ET_REL
A relocatable file.
ET_EXEC
An executable file.
ET_DYN
A shared object.
ET_CORE
A core file.

e_machine
This member specifies the required architecture for an individual file. E.g.:

EM_NONE
An unknown machine.
EM_M32
AT&T WE 32100.
EM_SPARC
Sun Microsystems SPARC.
EM_386
Intel 80386.
EM_68K
Motorola 68000.
EM_88K
Motorola 88000.
EM_860
Intel 80860.
EM_MIPS
MIPS RS3000 (big-endian only).
EM_PARISC
HP/PA.
EM_SPARC32PLUS
SPARC with enhanced instruction set.
EM_PPC
PowerPC.
EM_PPC64
PowerPC 64-bit.
EM_S390
IBM S/390
EM_ARM
Advanced RISC Machines
EM_SH
Renesas SuperH
EM_SPARCV9
SPARC v9 64-bit.
EM_IA_64
Intel Itanium
EM_X86_64
AMD x86-64
EM_VAX
DEC Vax.

e_version
This member identifies the file version:

EV_NONE
Invalid version.
EV_CURRENT
Current version.

e_entry
This member gives the virtual address to which the system first transfers control, thus starting the process. If the file has no associated entry point, this member holds zero.
e_phoff
This member holds the program header table's file offset in bytes. If the file has no program header table, this member holds zero.
e_shoff
This member holds the section header table's file offset in bytes. If the file has no section header table this member holds zero.
e_flags
This member holds processor-specific flags associated with the file. Flag names take the form EF_`machine_flag'. Currently no flags have been defined.
e_ehsize
This member holds the ELF header's size in bytes.
e_phentsize
This member holds the size in bytes of one entry in the file's program header table; all entries are the same size.
e_phnum
This member holds the number of entries in the program header table. Thus the product of e_phentsize and e_phnum gives the table's size in bytes. If a file has no program header, e_phnum holds the value zero.
e_shentsize
This member holds a sections header's size in bytes. A section header is one entry in the section header table; all entries are the same size.
e_shnum
This member holds the number of entries in the section header table. Thus the product of e_shentsize and e_shnum gives the section header table's size in bytes. If a file has no section header table, e_shnum holds the value of zero.
e_shstrndx
This member holds the section header table index of the entry associated with the section name string table. If the file has no section name string table, this member holds the value SHN_UNDEF

SHN_UNDEF
This value marks an undefined, missing, irrelevant, or otherwise meaningless section reference. For example, a symbol ``defined'' relative to section number SHN_UNDEF is an undefined symbol.
SHN_LORESERVE
This value specifies the lower bound of the range of reserved indices.
SHN_LOPROC
Values greater than or equal to SHN_HIPROC are reserved for processor-specific semantics.
SHN_HIPROC
Values less than or equal to SHN_LOPROC are reserved for processor-specific semantics.
SHN_ABS
This value specifies absolute values for the corresponding reference. For example, symbols defined relative to section number SHN_ABS have absolute values and are not affected by relocation.
SHN_COMMON
Symbols defined relative to this section are common symbols, such as Fortran COMMON or unallocated C external variables.
SHN_HIRESERVE
This value specifies the upper bound of the range of reserved indices between SHN_LORESERVE and SHN_HIRESERVE inclusive; the values do not reference the section header table. That is, the section header table does not contain entries for the reserved indices.

An executable or shared object file's program header table is an array of structures, each describing a segment or other information the system needs to prepare the program for execution. An object file segment contains one or more sections Program headers are meaningful only for executable and shared object files. A file specifies its own program header size with the ELF header's e_phentsize and e_phnum members. The ELF program header is described by the type Elf32_Phdr or Elf64_Phdr depending on the architecture:

typedef struct {
        uint32_t        p_type;
        Elf32_Off       p_offset;
        Elf32_Addr      p_vaddr;
        Elf32_Addr      p_paddr;
        uint32_t        p_filesz;
        uint32_t        p_memsz;
        uint32_t        p_flags;
        uint32_t        p_align;
} Elf32_Phdr;

typedef struct {
        uint32_t        p_type;
        uint32_t        p_flags;
        Elf64_Off       p_offset;
        Elf64_Addr      p_vaddr;
        Elf64_Addr      p_paddr;
        uint64_t        p_filesz;
        uint64_t        p_memsz;
        uint64_t        p_align;
} Elf64_Phdr;

The main difference between the 32-bit and the 64-bit program header lies in the location of the p_flags member in the total struct.

p_type
This member of the Phdr struct tells what kind of segment this array element describes or how to interpret the array element's information.

PT_NULL
The array element is unused and the other members' values are undefined. This lets the program header have ignored entries.
PT_LOAD
The array element specifies a loadable segment, described by p_filesz and p_memsz The bytes from the file are mapped to the beginning of the memory segment. If the segment's memory size (p_memsz ) is larger than the file size (p_filesz ) the ``extra'' bytes are defined to hold the value 0 and to follow the segment's initialized area. The file size may not be larger than the memory size. Loadable segment entries in the program header table appear in ascending order, sorted on the p_vaddr member.
PT_DYNAMIC
The array element specifies dynamic linking information.
PT_INTERP
The array element specifies the location and size of a null-terminated pathname to invoke as an interpreter. This segment type is meaningful only for executable files (though it may occur for shared objects). However it may not occur more than once in a file. If it is present, it must precede any loadable segment entry.
PT_NOTE
The array element specifies the location and size for auxiliary information.
PT_SHLIB
This segment type is reserved but has unspecified semantics. Programs that contain an array element of this type do not conform to the ABI.
PT_PHDR
The array element, if present, specifies the location and size of the program header table itself, both in the file and in the memory image of the program. This segment type may not occur more than once in a file. Moreover, it may only occur if the program header table is part of the memory image of the program. If it is present, it must precede any loadable segment entry.
PT_LOPROC
Values greater than or equal to PT_HIPROC are reserved for processor-specific semantics.
PT_HIPROC
Values less than or equal to PT_LOPROC are reserved for processor-specific semantics.

p_offset
This member holds the offset from the beginning of the file at which the first byte of the segment resides.
p_vaddr
This member holds the virtual address at which the first byte of the segment resides in memory.
p_paddr
On systems for which physical addressing is relevant, this member is reserved for the segment's physical address. Under BSD this member is not used and must be zero.
p_filesz
This member holds the number of bytes in the file image of the segment. It may be zero.
p_memsz
This member holds the number of bytes in the memory image of the segment. It may be zero.
p_flags
This member holds flags relevant to the segment:

PF_X
An executable segment.
PF_W
A writable segment.
PF_R
A readable segment.

A text segment commonly has the flags PF_X and PF_R A data segment commonly has PF_X PF_W and PF_R

p_align
This member holds the value to which the segments are aligned in memory and in the file. Loadable process segments must have congruent values for p_vaddr and p_offset modulo the page size. Values of zero and one mean no alignment is required. Otherwise, p_align should be a positive, integral power of two, and p_vaddr should equal p_offset modulo p_align

A file's section header table lets one locate all the file's sections. The section header table is an array of Elf32_Shdr or Elf64_Shdr structures. The ELF header's e_shoff member gives the byte offset from the beginning of the file to the section header table. e_shnum holds the number of entries the section header table contains. e_shentsize holds the size in bytes of each entry.

A section header table index is a subscript into this array. Some section header table indices are reserved. An object file does not have sections for these special indices:

SHN_UNDEF
This value marks an undefined, missing, irrelevant or otherwise meaningless section reference.
SHN_LORESERVE
This value specifies the lower bound of the range of reserved indices.
SHN_LOPROC
Values greater than or equal to SHN_HIPROC are reserved for processor-specific semantics.
SHN_HIPROC
Values less than or equal to SHN_LOPROC are reserved for processor-specific semantics.
SHN_ABS
This value specifies the absolute value for the corresponding reference. For example, a symbol defined relative to section number SHN_ABS has an absolute value and is not affected by relocation.
SHN_COMMON
Symbols defined relative to this section are common symbols, such as FORTRAN COMMON or unallocated C external variables.
SHN_HIRESERVE
This value specifies the upper bound of the range of reserved indices. The system reserves indices between SHN_LORESERVE and SHN_HIRESERVE inclusive. The section header table does not contain entries for the reserved indices.

The section header has the following structure:

typedef struct {
        uint32_t        sh_name;
        uint32_t        sh_type;
        uint32_t        sh_flags;
        Elf32_Addr      sh_addr;
        Elf32_Off       sh_offset;
        uint32_t        sh_size;
        uint32_t        sh_link;
        uint32_t        sh_info;
        uint32_t        sh_addralign;
        uint32_t        sh_entsize;
} Elf32_Shdr;

typedef struct {
        uint32_t        sh_name;
        uint32_t        sh_type;
        uint64_t        sh_flags;
        Elf64_Addr      sh_addr;
        Elf64_Off       sh_offset;
        uint64_t        sh_size;
        uint32_t        sh_link;
        uint32_t        sh_info;
        uint64_t        sh_addralign;
        uint64_t        sh_entsize;
} Elf64_Shdr;

No real differences exist between the 32-bit and 64-bit section headers.

sh_name
This member specifies the name of the section. Its value is an index into the section header string table section, giving the location of a null-terminated string.
sh_type
This member categorizes the section's contents and semantics.

SHT_NULL
This value marks the section header as inactive. It does not have an associated section. Other members of the section header have undefined values.
SHT_PROGBITS
This section holds information defined by the program, whose format and meaning are determined solely by the program.
SHT_SYMTAB
This section holds a symbol table. Typically, SHT_SYMTAB provides symbols for link editing, though it may also be used for dynamic linking. As a complete symbol table, it may contain many symbols unnecessary for dynamic linking. An object file can also contain a SHT_DYNSYM section.
SHT_STRTAB
This section holds a string table. An object file may have multiple string table sections.
SHT_RELA
This section holds relocation entries with explicit addends, such as type Elf32_Rela for the 32-bit class of object files. An object may have multiple relocation sections.
SHT_HASH
This section holds a symbol hash table. An object participating in dynamic linking must contain a symbol hash table. An object file may have only one hash table.
SHT_DYNAMIC
This section holds information for dynamic linking. An object file may have only one dynamic section.
SHT_NOTE
This section holds information that marks the file in some way.
SHT_NOBITS
A section of this type occupies no space in the file but otherwise resembles SHT_PROGBITS Although this section contains no bytes, the sh_offset member contains the conceptual file offset.
SHT_REL
This section holds relocation offsets without explicit addends, such as type Elf32_Rel for the 32-bit class of object files. An object file may have multiple relocation sections.
SHT_SHLIB
This section is reserved but has unspecified semantics.
SHT_DYNSYM
This section holds a minimal set of dynamic linking symbols. An object file can also contain a SHT_SYMTAB section.
SHT_LOPROC
This value up to and including SHT_HIPROC is reserved for processor-specific semantics.
SHT_HIPROC
This value down to and including SHT_LOPROC is reserved for processor-specific semantics.
SHT_LOUSER
This value specifies the lower bound of the range of indices reserved for application programs.
SHT_HIUSER
This value specifies the upper bound of the range of indices reserved for application programs. Section types between SHT_LOUSER and SHT_HIUSER may be used by the application, without conflicting with current or future system-defined section types.

sh_flags
Sections support one-bit flags that describe miscellaneous attributes. If a flag bit is set in sh_flags the attribute is ``on'' for the section. Otherwise, the attribute is ``off'' or does not apply. Undefined attributes are set to zero.

SHF_WRITE
This section contains data that should be writable during process execution.
SHF_ALLOC
This section occupies memory during process execution. Some control sections do not reside in the memory image of an object file. This attribute is off for those sections.
SHF_EXECINSTR
This section contains executable machine instructions.
SHF_MASKPROC
All bits included in this mask are reserved for processor-specific semantics.

sh_addr
If this section appears in the memory image of a process, this member holds the address at which the section's first byte should reside. Otherwise, the member contains zero.
sh_offset
This member's value holds the byte offset from the beginning of the file to the first byte in the section. One section type, SHT_NOBITS occupies no space in the file, and its sh_offset member locates the conceptual placement in the file.
sh_size
This member holds the section's size in bytes. Unless the section type is SHT_NOBITS the section occupies sh_size bytes in the file. A section of type SHT_NOBITS may have a non-zero size, but it occupies no space in the file.
sh_link
This member holds a section header table index link, whose interpretation depends on the section type.
sh_info
This member holds extra information, whose interpretation depends on the section type.
sh_addralign
Some sections have address alignment constraints. If a section holds a doubleword, the system must ensure doubleword alignment for the entire section. That is, the value of sh_addr must be congruent to zero, modulo the value of sh_addralign Only zero and positive integral powers of two are allowed. Values of zero or one mean the section has no alignment constraints.
sh_entsize
Some sections hold a table of fixed-sized entries, such as a symbol table. For such a section, this member gives the size in bytes for each entry. This member contains zero if the section does not hold a table of fixed-size entries.

Various sections hold program and control information:

.bss
This section holds uninitialized data that contributes to the program's memory image. By definition, the system initializes the data with zeros when the program begins to run. This section is of type SHT_NOBITS The attribute types are SHF_ALLOC and SHF_WRITE
.comment
This section holds version control information. This section is of type SHT_PROGBITS No attribute types are used.
.ctors
This section holds initialized pointers to the C++ constructor functions. This section is of type SHT_PROGBITS The attribute types are SHF_ALLOC and SHF_WRITE
.data
This section holds initialized data that contribute to the program's memory image. This section is of type SHT_PROGBITS The attribute types are SHF_ALLOC and SHF_WRITE
.data1
This section holds initialized data that contribute to the program's memory image. This section is of type SHT_PROGBITS The attribute types are SHF_ALLOC and SHF_WRITE
.debug
This section holds information for symbolic debugging. The contents are unspecified. This section is of type SHT_PROGBITS No attribute types are used.
.dtors
This section holds initialized pointers to the C++ destructor functions. This section is of type SHT_PROGBITS The attribute types are SHF_ALLOC and SHF_WRITE
.dynamic
This section holds dynamic linking information. The section's attributes will include the SHF_ALLOC bit. Whether the SHF_WRITE bit is set is processor-specific. This section is of type SHT_DYNAMIC See the attributes above.
.dynstr
This section holds strings needed for dynamic linking, most commonly the strings that represent the names associated with symbol table entries. This section is of type SHT_STRTAB The attribute type used is SHF_ALLOC
.dynsym
This section holds the dynamic linking symbol table. This section is of type SHT_DYNSYM The attribute used is SHF_ALLOC
.fini
This section holds executable instructions that contribute to the process termination code. When a program exits normally the system arranges to execute the code in this section. This section is of type SHT_PROGBITS The attributes used are SHF_ALLOC and SHF_EXECINSTR
.got
This section holds the global offset table. This section is of type SHT_PROGBITS The attributes are processor-specific.
.hash
This section holds a symbol hash table. This section is of type SHT_HASH The attribute used is SHF_ALLOC
.init
This section holds executable instructions that contribute to the process initialization code. When a program starts to run the system arranges to execute the code in this section before calling the main program entry point. This section is of type SHT_PROGBITS The attributes used are SHF_ALLOC and SHF_EXECINSTR
.interp
This section holds the pathname of a program interpreter. If the file has a loadable segment that includes the section, the section's attributes will include the SHF_ALLOC bit. Otherwise, that bit will be off. This section is of type SHT_PROGBITS
.line
This section holds line number information for symbolic debugging, which describes the correspondence between the program source and the machine code. The contents are unspecified. This section is of type SHT_PROGBITS No attribute types are used.
.note
This section holds information in the ``Note Section'' format described below. This section is of type SHT_NOTE No attribute types are used. Ox native executables usually contain a .note.openbsd.ident section to identify themselves, for the kernel to bypass any compatibility ELF binary emulation tests when loading the file.
.plt
This section holds the procedure linkage table. This section is of type SHT_PROGBITS The attributes are processor-specific.
.relNAME
This section holds relocation information as described below. If the file has a loadable segment that includes relocation, the section's attributes will include the SHF_ALLOC bit. Otherwise the bit will be off. By convention, ``NAME'' is supplied by the section to which the relocations apply. Thus a relocation section for .text normally would have the name .rel.text This section is of type SHT_REL
.relaNAME
This section holds relocation information as described below. If the file has a loadable segment that includes relocation, the section's attributes will include the SHF_ALLOC bit. Otherwise the bit will be off. By convention, ``NAME'' is supplied by the section to which the relocations apply. Thus a relocation section for .text normally would have the name .rela.text This section is of type SHT_RELA
.rodata
This section holds read-only data that typically contributes to a non-writable segment in the process image. This section is of type SHT_PROGBITS The attribute used is SHF_ALLOC
.rodata1
This section holds read-only data that typically contributes to a non-writable segment in the process image. This section is of type SHT_PROGBITS The attribute used is SHF_ALLOC
.shstrtab
This section holds section names. This section is of type SHT_STRTAB No attribute types are used.
.strtab
This section holds strings, most commonly the strings that represent the names associated with symbol table entries. If the file has a loadable segment that includes the symbol string table, the section's attributes will include the SHF_ALLOC bit. Otherwise the bit will be off. This section is of type SHT_STRTAB
.symtab
This section holds a symbol table. If the file has a loadable segment that includes the symbol table, the section's attributes will include the SHF_ALLOC bit. Otherwise the bit will be off. This section is of type SHT_SYMTAB
.text
This section holds the ``text'' or executable instructions, of a program. This section is of type SHT_PROGBITS The attributes used are SHF_ALLOC and SHF_EXECINSTR

String table sections hold null-terminated character sequences, commonly called strings. The object file uses these strings to represent symbol and section names. One references a string as an index into the string table section. The first byte, which is index zero, is defined to hold a null byte ('\0'). Similarly, a string table's last byte is defined to hold a null byte, ensuring null termination for all strings.

An object file's symbol table holds information needed to locate and relocate a program's symbolic definitions and references. A symbol table index is a subscript into this array.

typedef struct {
        uint32_t        st_name;
        Elf32_Addr      st_value;
        uint32_t        st_size;
        unsigned char   st_info;
        unsigned char   st_other;
        uint16_t        st_shndx;
} Elf32_Sym;

typedef struct {
        uint32_t        st_name;
        unsigned char   st_info;
        unsigned char   st_other;
        uint16_t        st_shndx;
        Elf64_Addr      st_value;
        uint64_t        st_size;
} Elf64_Sym;

The 32-bit and 64-bit versions have the same members, just in a different order.

st_name
This member holds an index into the object file's symbol string table, which holds character representations of the symbol names. If the value is non-zero, it represents a string table index that gives the symbol name. Otherwise, the symbol table has no name.
st_value
This member gives the value of the associated symbol.
st_size
Many symbols have associated sizes. This member holds zero if the symbol has no size or an unknown size.
st_info
This member specifies the symbol's type and binding attributes:

STT_NOTYPE
The symbol's type is not defined.
STT_OBJECT
The symbol is associated with a data object.
STT_FUNC
The symbol is associated with a function or other executable code.
STT_SECTION
The symbol is associated with a section. Symbol table entries of this type exist primarily for relocation and normally have STB_LOCAL bindings.
STT_FILE
By convention, the symbol's name gives the name of the source file associated with the object file. A file symbol has STB_LOCAL bindings, its section index is SHN_ABS and it precedes the other STB_LOCAL symbols of the file, if it is present.
STT_LOPROC
This value up to and including STT_HIPROC is reserved for processor-specific semantics.
STT_HIPROC
This value down to and including STT_LOPROC is reserved for processor-specific semantics.

STB_LOCAL
Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other.
STB_GLOBAL
Global symbols are visible to all object files being combined. One file's definition of a global symbol will satisfy another file's undefined reference to the same symbol.
STB_WEAK
Weak symbols resemble global symbols, but their definitions have lower precedence.
STB_LOPROC
This value up to and including STB_HIPROC is reserved for processor-specific semantics.
STB_HIPROC
This value down to and including STB_LOPROC is reserved for processor-specific semantics.

There are macros for packing and unpacking the binding and type fields:

Fn ELF32_ST_BIND info or Fn ELF64_ST_BIND info extract a binding from an st_info value.

Fn ELF32_ST_TYPE info or Fn ELF64_ST_TYPE info
extract a type from an st_info value.

Fn ELF32_ST_INFO bind type or Fn ELF64_ST_INFO bind type
convert a binding and a type into an st_info value.

st_other
This member currently holds zero and has no defined meaning.
st_shndx
Every symbol table entry is ``defined'' in relation to some section. This member holds the relevant section header table index.

Relocation is the process of connecting symbolic references with symbolic definitions. Relocatable files must have information that describes how to modify their section contents, thus allowing executable and shared object files to hold the right information for a process' program image. Relocation entries are these data.

Relocation structures that do not need an addend:

typedef struct {
        Elf32_Addr     r_offset;
        uint32_t       r_info;
} Elf32_Rel;

typedef struct {
        Elf64_Addr     r_offset;
        uint64_t       r_info;
} Elf64_Rel;

Relocation structures that need an addend:

typedef struct {
        Elf32_Addr      r_offset;
        uint32_t        r_info;
        int32_t         r_addend;
} Elf32_Rela;

typedef struct {
        Elf64_Addr      r_offset;
        uint64_t        r_info;
        int64_t         r_addend;
} Elf64_Rela;

r_offset
This member gives the location at which to apply the relocation action. For a relocatable file, the value is the byte offset from the beginning of the section to the storage unit affected by the relocation. For an executable file or shared object, the value is the virtual address of the storage unit affected by the relocation.
r_info
This member gives both the symbol table index with respect to which the relocation must be made and the type of relocation to apply. Relocation types are processor-specific. When the text refers to a relocation entry's relocation type or symbol table index, it means the result of applying ELF_[32|64]_R_TYPE or ELF[32|64]_R_SYM respectively, to the entry's r_info member.
r_addend
This member specifies a constant addend used to compute the value to be stored into the relocatable field.

The .dynamic section contains a series of structures that hold relevant dynamic linking information. The d_tag member controls the interpretation of d_un.

typedef struct {
        Elf32_Sword     d_tag;
        union {
           Elf32_Word   d_val;
           Elf32_Addr   d_ptr;
        } d_un;
} Elf32_Dyn;
extern Elf32_Dyn _DYNAMIC[];

typedef struct {
        Elf64_Sxword    d_tag;
        union {
           Elf64_Xword  d_val;
           Elf64_Addr   d_ptr;
        } d_un;
} Elf64_Dyn;
extern Elf64_Dyn _DYNAMIC[];

d_tag
This member may have any of the following values:

DT_NULL
Marks end of dynamic section
DT_NEEDED
String table offset to name of a needed library
DT_PLTRELSZ
Size in bytes of PLT relocs
DT_PLTGOT
Address of PLT and/or GOT
DT_HASH
Address of symbol hash table
DT_STRTAB
Address of string table
DT_SYMTAB
Address of symbol table
DT_RELA
Address of Rela relocs table
DT_RELASZ
Size in bytes of Rela table
DT_RELAENT
Size in bytes of a Rela table entry
DT_STRSZ
Size in bytes of string table
DT_SYMENT
Size in bytes of a symbol table entry
DT_INIT
Address of the initialization function
DT_FINI
Address of the termination function
DT_SONAME
String table offset to name of shared object
DT_RPATH
String table offset to library search path (deprecated)
DT_SYMBOLIC
Alert linker to search this shared object before the executable for symbols
DT_REL
Address of Rel relocs table
DT_RELSZ
Size in bytes of Rel table
DT_RELENT
Size in bytes of a Rel table entry
DT_PLTREL
Type of reloc the PLT refers (Rela or Rel)
DT_DEBUG
Undefined use for debugging
DT_TEXTREL
Absence of this indicates no relocs should apply to a non-writable segment
DT_JMPREL
Address of reloc entries solely for the PLT
DT_BIND_NOW
Instruct dynamic linker to process all relocs before transferring control to the executable
DT_RUNPATH
String table offset to library search path
DT_LOPROC
Start of processor-specific semantics
DT_HIPROC
End of processor-specific semantics

d_val
This member represents integer values with various interpretations.
d_ptr
This member represents program virtual addresses. When interpreting these addresses, the actual address should be computed based on the original file value and memory base address. Files do not contain relocation entries to fixup these addresses.
_DYNAMIC
Array containing all the dynamic structures in the .dynamic section. This is automatically populated by the linker.

HISTORY

Ox ELF support first appeared in Ox 1.2 , although not all supported platforms use it as the native binary file format. ELF in itself first appeared in AT&T System V . The ELF format is an adopted standard.

SEE ALSO

as(1), gdb(1), ld(1), objdump(1), execve(2), core(5)
Hewlett-Packard Elf-64 Object File Format
Santa Cruz Operation System V Application Binary Interface
Unix System Laboratories Object Files "Executable and Linking Format (ELF)"


complex (5)

 Continue to this page.


core(5)

CORE

Section: Linux Programmer's Manual (5)
Updated: 2006-04-03 Return to Main Contents

NAME

core - core dump file

DESCRIPTION

The default action of certain signals is to cause a process to terminate and produce a core dump file, a disk file containing an image of the process's memory at the time of termination. A list of the signals which cause a process to dump core can be found in signal(7).

A process can set its soft RLIMIT_CORE resource limit to place an upper limit on the size of the core dump file that will be produced if it receives a "core dump" signal; see getrlimit(2) for details.

There are various circumstances in which a core dump file is not produced:

*
The process does not have permission to write the core file. (By default the core file is called core, and is created in the current working directory. See below for details on naming.) Writing the core file will fail if the directory in which it is to be created is non-writable, or if a file with the same name exists and is not writable or is not a regular file (e.g., it is a directory or a symbolic link).
*
A (writable, regular) file with the same name as would be used for the core dump already exists, but there is more than one hard link to that file.
*
The file system where the core dump file would be created is full; or has run out of i-nodes; or is mounted read only; or the user has reached their quota for the file system.
*
The directory in which the core dump file is to be created does not exist.
*
RLIMIT_CORE or RLIMIT_FSIZE resource limits for a process are set to zero (see getrlimit(2)).
*
The binary being executed by the process does not have read permission enabled.
*
The process is executing a set-user-ID (set-group-ID) program that is owned by a user (group) other than the real user (group) ID of the process. (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, and the description of the /proc/sys/fs/suid_dumpable file in proc(5).)

Naming of core dump files

By default, a core dump file is named core, but the /proc/sys/kernel/core_pattern file (since Linux 2.6 and 2.4.21) can be set to define a template that is used to name core dump files. The template can contain % specifiers which are substituted by the following values when a core file is created:

  %%  A single % character
  %p  PID of dumped process
  %u  real UID of dumped process
  %g  real GID of dumped process
  %s  number of signal causing dump
  %t  time of dump (seconds since 0:00h, 1 Jan 1970)
  %h  hostname (same as 'nodename' returned by uname(2))
  %e  executable filename
A single % at the end of the template is dropped from the core filename, as is the combination of a % followed by any character other than those listed above. All other characters in the template become a literal part of the core filename. The template may include `/' characters, which are interpreted as delimiters for directory names. The maximum size of the resulting core filename is 64 bytes. The default value in this file is "core". For backward compatibility, if /proc/sys/kernel/core_pattern does not include "%p" and /proc/sys/kernel/core_uses_pid (see below) is non-zero, then .PID will be appended to the core filename.

Since version 2.4, Linux has also provided a more primitive method of controlling the name of the core dump file. If the /proc/sys/kernel/core_uses_pid file contains the value 0, then a core dump file is simply named core. If this file contains a non-zero value, then the core dump file includes the process ID in a name of the form core.PID.

NOTES

The gdb(1) gcore command can be used to obtain a core dump of a running process.

If a multithreaded process (or, more precisely, a process that shares its memory with another process by being created with the CLONE_VM flag of clone(2)) dumps core, then the process ID is always appended to the core filename, unless the process ID was already included elsewhere in the filename via a %p specification in /proc/sys/kernel/core_pattern.

SEE ALSO

gdb(1), getrlimit(2), prctl(2), sigaction(2), elf(5), proc(5), signal(7)


intro(6)

INTRO

Section: Linux Programmer's Manual (6)
Updated: 1993-07-24 Return to Main Contents

NAME

intro - Introduction to games

DESCRIPTION

This chapter describes all the games and funny little programs available on the system.

Authors and Copyright Conditions

Look at the header of the manual page for the author(s) and copyright conditions. Note that these can be different from page to page!


packet(7)

PACKET

Section: Linux Programmer's Manual (7)
Updated: 1999-04-29 Return to Main Contents

NAME

packet, PF_PACKET - packet interface on device level.

SYNOPSIS

#include <sys/socket.h>

#include <netpacket/packet.h>

#include <net/ethernet.h>     /* the L2 protocols */

packet_socket = socket(PF_PACKET, int socket_type, int protocol);

DESCRIPTION

Packet sockets are used to receive or send raw packets at the device driver (OSI Layer 2) level. They allow the user to implement protocol modules in user space on top of the physical layer.

The socket_type is either SOCK_RAW for raw packets including the link level header or SOCK_DGRAM for cooked packets with the link level header removed. The link level header information is available in a common format in a sockaddr_ll. protocol is the IEEE 802.3 protocol number in network order. See the <linux/if_ether.h> include file for a list of allowed protocols. When protocol is set to htons(ETH_P_ALL) then all protocols are received. All incoming packets of that protocol type will be passed to the packet socket before they are passed to the protocols implemented in the kernel.

Only processes with effective UID 0 or the CAP_NET_RAW capability may open packet sockets.

SOCK_RAW packets are passed to and from the device driver without any changes in the packet data. When receiving a packet, the address is still parsed and passed in a standard sockaddr_ll address structure. When transmitting a packet, the user supplied buffer should contain the physical layer header. That packet is then queued unmodified to the network driver of the interface defined by the destination address. Some device drivers always add other headers. SOCK_RAW is similar to but not compatible with the obsolete PF_INET/SOCK_PACKET of Linux 2.0.

SOCK_DGRAM operates on a slightly higher level. The physical header is removed before the packet is passed to the user. Packets sent through a SOCK_DGRAM packet socket get a suitable physical layer header based on the information in the sockaddr_ll destination address before they are queued.

By default all packets of the specified protocol type are passed to a packet socket. To only get packets from a specific interface use bind(2) specifying an address in a struct sockaddr_ll to bind the packet socket to an interface. Only the sll_protocol and the sll_ifindex address fields are used for purposes of binding.

The connect(2) operation is not supported on packet sockets.

When the MSG_TRUNC flag is passed to recvmsg(2), recv(2), recvfrom(2) the real length of the packet on the wire is always returned, even when it is longer than the buffer.

Address Types

The sockaddr_ll is a device independent physical layer address.

struct sockaddr_ll {
    unsigned short sll_family;   /* Always AF_PACKET */
    unsigned short sll_protocol; /* Physical layer protocol */
    int            sll_ifindex;  /* Interface number */
    unsigned short sll_hatype;   /* Header type */
    unsigned char  sll_pkttype;  /* Packet type */
    unsigned char  sll_halen;    /* Length of address */
    unsigned char  sll_addr[8];  /* Physical layer address */
};

sll_protocol is the standard ethernet protocol type in network order as defined in the <linux/if_ether.h> include file. It defaults to the socket's protocol. sll_ifindex is the interface index of the interface (see netdevice(7)); 0 matches any interface (only legal for binding). sll_hatype is a ARP type as defined in the <linux/if_arp.h> include file. sll_pkttype contains the packet type. Valid types are PACKET_HOST for a packet addressed to the local host, PACKET_BROADCAST for a physical layer broadcast packet, PACKET_MULTICAST for a packet sent to a physical layer multicast address, PACKET_OTHERHOST for a packet to some other host that has been caught by a device driver in promiscuous mode, and PACKET_OUTGOING for a packet originated from the local host that is looped back to a packet socket. These types make only sense for receiving. sll_addr and sll_halen contain the physical layer (e.g., IEEE 802.3) address and its length. The exact interpretation depends on the device.

When you send packets it is enough to specify sll_family, sll_addr, sll_halen, sll_ifindex. The other fields should be 0. sll_hatype and sll_pkttype are set on received packets for your information. For bind only sll_protocol and sll_ifindex are used.

Socket Options

Packet sockets can be used to configure physical layer multicasting and promiscuous mode. It works by calling setsockopt(2) on a packet socket for SOL_PACKET and one of the options PACKET_ADD_MEMBERSHIP to add a binding or PACKET_DROP_MEMBERSHIP to drop it. They both expect a packet_mreq structure as argument:

struct packet_mreq {
    int            mr_ifindex;    /* interface index */
    unsigned short mr_type;       /* action */
    unsigned short mr_alen;       /* address length */
    unsigned char  mr_address[8]; /* physical layer address */
};

mr_ifindex contains the interface index for the interface whose status should be changed. The mr_type parameter specifies which action to perform. PACKET_MR_PROMISC enables receiving all packets on a shared medium (often known as ``promiscuous mode''), PACKET_MR_MULTICAST binds the socket to the physical layer multicast group specified in mr_address and mr_alen, and PACKET_MR_ALLMULTI sets the socket up to receive all multicast packets arriving at the interface.

In addition the traditional ioctls SIOCSIFFLAGS, SIOCADDMULTI, SIOCDELMULTI can be used for the same purpose.

Ioctls

SIOCGSTAMP can be used to receive the time stamp of the last received packet. Argument is a struct timeval.

In addition all standard ioctls defined in netdevice(7) and socket(7) are valid on packet sockets.

Error Handling

Packet sockets do no error handling other than errors occurred while passing the packet to the device driver. They don't have the concept of a pending error.

ERRORS

ENETDOWN
Interface is not up.
ENOTCONN
No interface address passed.
ENODEV
Unknown device name or interface index specified in interface address.
EMSGSIZE
Packet is bigger than interface MTU.
ENOBUFS
Not enough memory to allocate the packet.
EFAULT
User passed invalid memory address.
EINVAL
Invalid argument.
ENXIO
Interface address contained illegal interface index.
EPERM
User has insufficient privileges to carry out this operation.
EADDRNOTAVAIL
Unknown multicast group address passed.
ENOENT
No packet received.

In addition other errors may be generated by the low-level driver.

VERSIONS

PF_PACKET is a new feature in Linux 2.2. Earlier Linux versions supported only SOCK_PACKET.

The include file <netpacket/packet.h> is present since glibc 2.1. Older systems need:

#include <asm/types.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>  /* The L2 protocols */

NOTES

For portable programs it is suggested to use PF_PACKET via pcap(3); although this only covers a subset of the PF_PACKET features.

The SOCK_DGRAM packet sockets make no attempt to create or parse the IEEE 802.2 LLC header for a IEEE 802.3 frame. When ETH_P_802_3 is specified as protocol for sending the kernel creates the 802.3 frame and fills out the length field; the user has to supply the LLC header to get a fully conforming packet. Incoming 802.3 packets are not multiplexed on the DSAP/SSAP protocol fields; instead they are supplied to the user as protocol ETH_P_802_2 with the LLC header prepended. It is thus not possible to bind to ETH_P_802_3; bind to ETH_P_802_2 instead and do the protocol multiplex yourself. The default for sending is the standard Ethernet DIX encapsulation with the protocol filled in.

Packet sockets are not subject to the input or output firewall chains.

Compatibility

In Linux 2.0, the only way to get a packet socket was by calling socket(PF_INET, SOCK_PACKET, protocol). This is still supported but strongly deprecated. The main difference between the two methods is that SOCK_PACKET uses the old struct sockaddr_pkt to specify an interface, which doesn't provide physical layer independence.

struct sockaddr_pkt {
    unsigned short spkt_family;
    unsigned char  spkt_device[14];
    unsigned short spkt_protocol;
};

spkt_family contains the device type, spkt_protocol is the IEEE 802.3 protocol type as defined in <sys/if_ether.h> and spkt_device is the device name as a null terminated string, for example, eth0.

This structure is obsolete and should not be used in new code.

BUGS

glibc 2.1 does not have a define for SOL_PACKET. The suggested workaround is to use:

#ifndef SOL_PACKET
#define SOL_PACKET 263
#endif
This is fixed in later glibc versions and also does not occur on libc5 systems.

The IEEE 802.2/803.3 LLC handling could be considered as a bug.

Socket filters are not documented.

The MSG_TRUNC recvmsg(2) extension is an ugly hack and should be replaced by a control message. There is currently no way to get the original destination address of packets via SOCK_DGRAM.

SEE ALSO

socket(2), pcap(3), capabilities(7), ip(7), raw(7), socket(7)

RFC 894 for the standard IP Ethernet encapsulation.

RFC 1700 for the IEEE 802.3 IP encapsulation.

The <linux/if_ether.h> include file for physical layer protocols.


udp(7)

UDP

Section: Linux Programmer's Manual (7)
Updated: 1998-10-02 Return to Main Contents

NAME

udp - User Datagram Protocol for IPv4

SYNOPSIS

#include <sys/socket.h>
#include <netinet/in.h>
udp_socket = socket(PF_INET, SOCK_DGRAM, 0);

DESCRIPTION

This is an implementation of the User Datagram Protocol described in RFC 768. It implements a connectionless, unreliable datagram packet service. Packets may be reordered or duplicated before they arrive. UDP generates and checks checksums to catch transmission errors.

When a UDP socket is created, its local and remote addresses are unspecified. Datagrams can be sent immediately using sendto(2) or sendmsg(2) with a valid destination address as an argument. When connect(2) is called on the socket the default destination address is set and datagrams can now be sent using send(2) or write(2) without specifying an destination address. It is still possible to send to other destinations by passing an address to sendto(2) or sendmsg(2). In order to receive packets the socket can be bound to an local address first by using bind(2). Otherwise the socket layer will automatically assign a free local port out of the range defined by net.ipv4.ip_local_port_range and bind the socket to INADDR_ANY.

All receive operations return only one packet. When the packet is smaller than the passed buffer only that much data is returned, when it is bigger the packet is truncated and the MSG_TRUNC flag is set. MSG_WAITALL is not supported.

IP options may be sent or received using the socket options described in ip(7). They are only processed by the kernel when the appropriate sysctl is enabled (but still passed to the user even when it is turned off). See ip(7).

When the MSG_DONTROUTE flag is set on sending the destination address must refer to an local interface address and the packet is only sent to that interface.

By default Linux UDP does path MTU (Maximum Transmission Unit) discovery. This means the kernel will keep track of the MTU to a specific target IP address and return EMSGSIZE when a UDP packet write exceeds it. When this happens the application should decrease the packet size. Path MTU discovery can be also turned off using the IP_MTU_DISCOVER socket option or the ip_no_pmtu_disc sysctl, see ip(7) for details. When turned off UDP will fragment outgoing UDP packets that exceed the interface MTU. However disabling it is not recommended for performance and reliability reasons.

Address Format

UDP uses the IPv4 sockaddr_in address format described in ip(7).

Error Handling

All fatal errors will be passed to the user as an error return even when the socket is not connected. This includes asynchronous errors received from the network. You may get an error for an earlier packet that was sent on the same socket. This behavior differs from many other BSD socket implementations which don't pass any errors unless the socket is connected. Linux's behavior is mandated by RFC 1122.

For compatibility with legacy code in Linux 2.0 and 2.2 it was possible to set the SO_BSDCOMPAT SOL_SOCKET option to receive remote errors only when the socket has been connected (except for EPROTO and EMSGSIZE). Locally generated errors are always passed. Support for this socket option was removed in later kernels; see socket(7) for further information.

When the IP_RECVERR option is enabled all errors are stored in the socket error queue and can be received by recvmsg(2) with the MSG_ERRQUEUE flag set.

Socket Options

To set or get a UDP socket option, call getsockopt(2) to read or setsockopt(2) to write the option with the option level argument set to IPPROTO_UDP.
UDP_CORK (since Linux 2.5.44)
If this option is enabled, then all data output on this socket is accumulated into a single datagram that is transmitted when the option is disabled. This option should not be used in code intended to be portable.

Ioctls

These ioctls can be accessed using ioctl(2). The correct syntax is:

int value;
error = ioctl(udp_socket, ioctl_type, &value);
FIONREAD (SIOCINQ)
Gets a pointer to an integer as argument. Returns the size of the next pending datagram in the integer in bytes, or 0 when no datagram is pending.
TIOCOUTQ (SIOCOUTQ)
Returns the number of data bytes in the local send queue. Only supported with Linux 2.4 and above.

In addition all ioctls documented in ip(7) and socket(7) are supported.

ERRORS

All errors documented for socket(7) or ip(7) may be returned by a send or receive on a UDP socket.

ECONNREFUSED No receiver was associated with the destination address. This might be caused by a previous packet sent over the socket.

VERSIONS

IP_RECVERR is a new feature in Linux 2.2.

SEE ALSO

ip(7), raw(7), socket(7)

RFC 768 for the User Datagram Protocol.
RFC 1122 for the host requirements.
RFC 1191 for a description of path MTU discovery.


regex(7)

REGEX

Section: Linux Programmer's Manual (7)
Updated: 1994-02-07 Return to Main Contents

NAME

regex - POSIX.2 regular expressions

DESCRIPTION

Regular expressions (``RE''s), as defined in POSIX.2, come in two forms: modern REs (roughly those of egrep; POSIX.2 calls these ``extended'' REs) and obsolete REs (roughly those of ed(1); POSIX.2 ``basic'' REs). Obsolete REs mostly exist for backward compatibility in some old programs; they will be discussed at the end. POSIX.2 leaves some aspects of RE syntax and semantics open; `(!)' marks decisions on these aspects that may not be fully portable to other POSIX.2 implementations.

A (modern) RE is one(!) or more non-empty(!) branches, separated by `|'. It matches anything that matches one of the branches.

A branch is one(!) or more pieces, concatenated. It matches a match for the first, followed by a match for the second, etc.

A piece is an atom possibly followed by a single(!) `*', `+', `?', or bound. An atom followed by `*' matches a sequence of 0 or more matches of the atom. An atom followed by `+' matches a sequence of 1 or more matches of the atom. An atom followed by `?' matches a sequence of 0 or 1 matches of the atom.

A bound is `{' followed by an unsigned decimal integer, possibly followed by `,' possibly followed by another unsigned decimal integer, always followed by `}'. The integers must lie between 0 and RE_DUP_MAX (255(!)) inclusive, and if there are two of them, the first may not exceed the second. An atom followed by a bound containing one integer i and no comma matches a sequence of exactly i matches of the atom. An atom followed by a bound containing one integer i and a comma matches a sequence of i or more matches of the atom. An atom followed by a bound containing two integers i and j matches a sequence of i through j (inclusive) matches of the atom.

An atom is a regular expression enclosed in `()' (matching a match for the regular expression), an empty set of `()' (matching the null string)(!), a bracket expression (see below), `.' (matching any single character), `^' (matching the null string at the beginning of a line), `$' (matching the null string at the end of a line), a `\' followed by one of the characters `^.[$()|*+?{\' (matching that character taken as an ordinary character), a `\' followed by any other character(!) (matching that character taken as an ordinary character, as if the `\' had not been present(!)), or a single character with no other significance (matching that character). A `{' followed by a character other than a digit is an ordinary character, not the beginning of a bound(!). It is illegal to end an RE with `\'.

A bracket expression is a list of characters enclosed in `[]'. It normally matches any single character from the list (but see below). If the list begins with `^', it matches any single character (but see below) not from the rest of the list. If two characters in the list are separated by `-', this is shorthand for the full range of characters between those two (inclusive) in the collating sequence, for example, `[0-9]' in ASCII matches any decimal digit. It is illegal(!) for two ranges to share an endpoint, for example, `a-c-e'. Ranges are very collating-sequence-dependent, and portable programs should avoid relying on them.

To include a literal `]' in the list, make it the first character (following a possible `^'). To include a literal `-', make it the first or last character, or the second endpoint of a range. To use a literal `-' as the first endpoint of a range, enclose it in `[.' and `.]' to make it a collating element (see below). With the exception of these and some combinations using `[' (see next paragraphs), all other special characters, including `\', lose their special significance within a bracket expression.

Within a bracket expression, a collating element (a character, a multi-character sequence that collates as if it were a single character, or a collating-sequence name for either) enclosed in `[.' and `.]' stands for the sequence of characters of that collating element. The sequence is a single element of the bracket expression's list. A bracket expression containing a multi-character collating element can thus match more than one character, for example, if the collating sequence includes a `ch' collating element, then the RE `[[.ch.]]*c' matches the first five characters of `chchcc'.

Within a bracket expression, a collating element enclosed in `[=' and `=]' is an equivalence class, standing for the sequences of characters of all collating elements equivalent to that one, including itself. (If there are no other equivalent collating elements, the treatment is as if the enclosing delimiters were `[.' and `.]'.) For example, if o and are the members of an equivalence class, then `[[=o=]]', `[[==]]', and `[o]' are all synonymous. An equivalence class may not(!) be an endpoint of a range.

Within a bracket expression, the name of a character class enclosed in `[:' and `:]' stands for the list of all characters belonging to that class. Standard character class names are:

alnum digitpunct
alpha graphspace
blank lowerupper
cntrl printxdigit

These stand for the character classes defined in wctype(3). A locale may provide others. A character class may not be used as an endpoint of a range.

In the event that an RE could match more than one substring of a given string, the RE matches the one starting earliest in the string. If the RE could match more than one substring starting at that point, it matches the longest. Subexpressions also match the longest possible substrings, subject to the constraint that the whole match be as long as possible, with subexpressions starting earlier in the RE taking priority over ones starting later. Note that higher-level subexpressions thus take priority over their lower-level component subexpressions.

Match lengths are measured in characters, not collating elements. A null string is considered longer than no match at all. For example, `bb*' matches the three middle characters of `abbbc', `(wee|week)(knights|nights)' matches all ten characters of `weeknights', when `(.*).*' is matched against `abc' the parenthesized subexpression matches all three characters, and when `(a*)*' is matched against `bc' both the whole RE and the parenthesized subexpression match the null string.

If case-independent matching is specified, the effect is much as if all case distinctions had vanished from the alphabet. When an alphabetic that exists in multiple cases appears as an ordinary character outside a bracket expression, it is effectively transformed into a bracket expression containing both cases, for example, `x' becomes `[xX]'. When it appears inside a bracket expression, all case counterparts of it are added to the bracket expression, so that, for example, `[x]' becomes `[xX]' and `[^x]' becomes `[^xX]'.

No particular limit is imposed on the length of REs(!). Programs intended to be portable should not employ REs longer than 256 bytes, as an implementation can refuse to accept such REs and remain POSIX-compliant.

Obsolete (``basic'') regular expressions differ in several respects. `|', `+', and `?' are ordinary characters and there is no equivalent for their functionality. The delimiters for bounds are `\{' and `\}', with `{' and `}' by themselves ordinary characters. The parentheses for nested subexpressions are `\(' and `\)', with `(' and `)' by themselves ordinary characters. `^' is an ordinary character except at the beginning of the RE or(!) the beginning of a parenthesized subexpression, `$' is an ordinary character except at the end of the RE or(!) the end of a parenthesized subexpression, and `*' is an ordinary character if it appears at the beginning of the RE or the beginning of a parenthesized subexpression (after a possible leading `^'). Finally, there is one new type of atom, a back reference: `\' followed by a non-zero decimal digit d matches the same sequence of characters matched by the dth parenthesized subexpression (numbering subexpressions by the positions of their opening parentheses, left to right), so that, for example, `\([bc]\)\1' matches `bb' or `cc' but not `bc'.

BUGS

Having two kinds of REs is a botch.

The current POSIX.2 spec says that `)' is an ordinary character in the absence of an unmatched `('; this was an unintentional result of a wording error, and change is likely. Avoid relying on it.

Back references are a dreadful botch, posing major problems for efficient implementations. They are also somewhat vaguely defined (does `a\(\(b\)*\2\)*d' match `abbbd'?). Avoid using them.

POSIX.2's specification of case-independent matching is vague. The ``one case implies all cases'' definition given above is current consensus among implementors as to the right interpretation.

The syntax for word boundaries is incredibly ugly.

SEE ALSO

regex(3)

POSIX.2, section 2.8 (Regular Expression Notation).


glob(7)

GLOB

Section: Linux Programmer's Manual (7)
Updated: 2003-08-24 Return to Main Contents

NAME

glob - Globbing pathnames

DESCRIPTION

Long ago, in Unix V6, there was a program /etc/glob that would expand wildcard patterns. Soon afterwards this became a shell built-in.

These days there is also a library routine glob(3) that will perform this function for a user program.

The rules are as follows (POSIX.2, 3.13).

WILDCARD MATCHING

A string is a wildcard pattern if it contains one of the characters `?', `*' or `['. Globbing is the operation that expands a wildcard pattern into the list of pathnames matching the pattern. Matching is defined by:

A `?' (not between brackets) matches any single character.

A `*' (not between brackets) matches any string, including the empty string.

Character classes

An expression `[...]' where the first character after the leading `[' is not an `!' matches a single character, namely any of the characters enclosed by the brackets. The string enclosed by the brackets cannot be empty; therefore `]' can be allowed between the brackets, provided that it is the first character. (Thus, `[][!]' matches the three characters `[', `]' and `!'.)

Ranges

There is one special convention: two characters separated by `-' denote a range. (Thus, `[A-Fa-f0-9]' is equivalent to `[ABCDEFabcdef0123456789]'.) One may include `-' in its literal meaning by making it the first or last character between the brackets. (Thus, `[]-]' matches just the two characters `]' and `-', and `[--0]' matches the three characters `-', `.', `0', since `/' cannot be matched.)

Complementation

An expression `[!...]' matches a single character, namely any character that is not matched by the expression obtained by removing the first `!' from it. (Thus, `[!]a-]' matches any single character except `]', `a' and `-'.)

One can remove the special meaning of `?', `*' and `[' by preceding them by a backslash, or, in case this is part of a shell command line, enclosing them in quotes. Between brackets these characters stand for themselves. Thus, `[[?*\]' matches the four characters `[', `?', `*' and `\'.

PATHNAMES

Globbing is applied on each of the components of a pathname separately. A `/' in a pathname cannot be matched by a `?' or `*' wildcard, or by a range like `[.-0]'. A range cannot contain an explicit `/' character; this would lead to a syntax error.

If a filename starts with a `.', this character must be matched explicitly. (Thus, `rm *' will not remove .profile, and `tar c *' will not archive all your files; `tar c .' is better.)

EMPTY LISTS

The nice and simple rule given above: `expand a wildcard pattern into the list of matching pathnames' was the original Unix definition. It allowed one to have patterns that expand into an empty list, as in
    xv -wait 0 *.gif *.jpg
where perhaps no *.gif files are present (and this is not an error). However, POSIX requires that a wildcard pattern is left unchanged when it is syntactically incorrect, or the list of matching pathnames is empty. With bash one can force the classical behavior by setting allow_null_glob_expansion=true.

(Similar problems occur elsewhere. E.g., where old scripts have

    rm `find . -name "*~"`
new scripts require
    rm -f nosuchfile `find . -name "*~"`
to avoid error messages from rm called with an empty argument list.)

NOTES

Regular expressions

Note that wildcard patterns are not regular expressions, although they are a bit similar. First of all, they match filenames, rather than text, and secondly, the conventions are not the same: for example, in a regular expression `*' means zero or more copies of the preceding thing.

Now that regular expressions have bracket expressions where the negation is indicated by a `^', POSIX has declared the effect of a wildcard pattern `[^...]' to be undefined.

Character classes and Internationalization

Of course ranges were originally meant to be ASCII ranges, so that `[ -%]' stands for `[ !"#$%]' and `[a-z]' stands for "any lowercase letter". Some Unix implementations generalized this so that a range X-Y stands for the set of characters with code between the codes for X and for Y. However, this requires the user to know the character coding in use on the local system, and moreover, is not convenient if the collating sequence for the local alphabet differs from the ordering of the character codes. Therefore, POSIX extended the bracket notation greatly, both for wildcard patterns and for regular expressions. In the above we saw three types of items that can occur in a bracket expression: namely (i) the negation, (ii) explicit single characters, and (iii) ranges. POSIX specifies ranges in an internationally more useful way and adds three more types:

(iii) Ranges X-Y comprise all characters that fall between X and Y (inclusive) in the current collating sequence as defined by the LC_COLLATE category in the current locale.

(iv) Named character classes, like

[:alnum:]  [:alpha:]  [:blank:]  [:cntrl:]
[:digit:]  [:graph:]  [:lower:]  [:print:]
[:punct:]  [:space:]  [:upper:]  [:xdigit:]
so that one can say `[[:lower:]]' instead of `[a-z]', and have things work in Denmark, too, where there are three letters past `z' in the alphabet. These character classes are defined by the LC_CTYPE category in the current locale.

(v) Collating symbols, like `[.ch.]' or `[.a-acute.]', where the string between `[.' and `.]' is a collating element defined for the current locale. Note that this may be a multi-character element.

(vi) Equivalence class expressions, like `[=a=]', where the string between `[=' and `=]' is any collating element from its equivalence class, as defined for the current locale. For example, `[[=a=]]' might be equivalent to `[aáàäâ]' (warning: Latin-1 here), that is, to `[a[.a-acute.][.a-grave.][.a-umlaut.][.a-circumflex.]]'.

SEE ALSO

sh(1), fnmatch(3), glob(3), locale(7), regex(7)


suffixes(7)

SUFFIXES

Section: Linux Programmer's Manual (7)
Updated: 2000-11-16 Return to Main Contents

NAME

suffixes - list of file suffixes

DESCRIPTION

It is customary to indicate the contents of a file with the file suffix, which consists of a period, followed by one or more letters. Many standard utilities, such as compilers, use this to recognize the type of file they are dealing with. The make(1) utility is driven by rules based on file suffix.

Following is a list of suffixes which are likely to be found on a Linux system.

Suffix | File type
- | backup file
.C | C++ source code, equivalent to .cc
.F | Fortran source with cpp(1) directives
 | or file compressed using freeze
.S | assembler source with cpp(1) directives
.Y | file compressed using yabba
.Z | file compressed using compress(1)
.[0-9]+gf | TeX generic font files
.[0-9]+pk | TeX packed font files
.[1-9] | manual page for the corresponding section
.[1-9][a-z] | manual page for section plus subsection
.a | static object code library
.ad | X application default resource file
.ada | Ada source (may be body, spec, or combination)
.adb | Ada body source
.ads | Ada spec source
.afm | PostScript font metrics
.al | Perl autoload file
.am | automake(1) input file
.arc | arc(1) archive
.arj | arj(1) archive
.asc | PGP ASCII-armored data
.asm | (GNU) assembler source file
.au | Audio sound file
.aux | LaTeX auxiliary file
.avi | (msvideo) movie
.awk | AWK language program
.b | LILO boot loader image
.bak | backup file
.bash | bash(1) shell script
.bb | basic block list data produced by
 | gcc -ftest-coverage
.bbg | basic block graph data produced by
 | gcc -ftest-coverage
.bbl | BibTeX output
.bdf | X font file
.bib | TeX bibliographic database, BibTeX input
.bm | bitmap source
.bmp | bitmap
.bz2 | file compressed using bzip2(1)
.c | C source
.cat | message catalog files
.cc | C++ source
.cf | configuration file
.cfg | configuration file
.cgi | WWW content generating script or program
.cls | LaTeX Class definition
.class | Java compiled byte-code
.conf | configuration file
.config | configuration file
.cpp | equivalent to .cc
.csh | csh(1) shell script
.cxx | equivalent to .cc
.dat | data file
.deb | Debian software package
.def | Modula-2 source for definition modules
.def | other definition files
.desc | initial part of mail message unpacked with
 | munpack(1)
.diff | file differences (diff(1) command output)
.dir | dbm data base directory file
.doc | documentation file
.dsc | Debian Source Control (source package)
.dtx | LaTeX package source file
.dvi | TeX's device independent output
.el | Emacs-Lisp source
.elc | compiled Emacs-Lisp source
.eps | encapsulated PostScript
.exp | Expect source code
.f | Fortran source
.f77 | Fortran 77 source
.f90 | Fortran 90 source
.fas | pre-compiled Common-Lisp
.fi | Fortran include files
.fig | FIG image file (used by xfig(1))
.fmt | TeX format file
.gif | Compuserve Graphics Image File format
.gmo | GNU format message catalog
.gsf | Ghostscript fonts
.gz | file compressed using gzip(1)
.h | C or C++ header files
.help | help file
.hf | equivalent to .help
.hlp | equivalent to .help
.htm | poor man's .html
.html | HTML document used with the World Wide Web
.hqx | 7-bit encoded Macintosh file
.i | C source after preprocessing
.icon | bitmap source
.idx | reference or datum-index file for hypertext
 | or database system
.image | bitmap source
.in | configuration template, especially for GNU Autoconf
.info | files for the Emacs info browser
.info-[0-9]+ | split info files
.ins | LaTeX package install file for docstrip
.itcl | itcl source code;
 | itcl ([incr Tcl]) is an OO extension of tcl
.java | a Java source file
.jpeg | Joint Photographic Experts Group format
.jpg | poor man's .jpeg
.kmap | lyx(1) keymap
.l | equivalent to .lex or .lisp
.lex | lex(1) or flex(1) files
.lha | lharc archive
.lib | Common-Lisp library
.lisp | Lisp source
.ln | files for use with lint(1)
.log | log file, in particular produced by TeX
.lsm | Linux Software Map entry
.lsp | Common-Lisp source
.lzh | lharc archive
.m | Objective-C source code
.m4 | m4(1) source
.mac | macro files for various programs
.man | manual page (usually source rather than formatted)
.map | map files for various programs
.me | Nroff source using the me macro package
.mf | Metafont (font generator for TeX) source
.mgp | MagicPoint file
.mm | sources for groff(1) in mm - format
.mo | Message catalog binary file
.mod | Modula-2 source for implementation modules
.mov | (quicktime) movie
.mp | Metapost source
.mp2 | MPEG Layer 2 (audio) file
.mp3 | MPEG Layer 3 (audio) file
.mpeg | movie file
.o | object file
.old | old or backup file
.orig | backup (original) version of a file, from patch(1)
.out | output file, often executable program (a.out)
.p | Pascal source
.pag | dbm data base data file
.patch | file differences for patch(1)
.pbm | portable bitmap format
.pcf | X11 font files
.pdf | Adobe Portable Data Format
 | (use Acrobat/acroread or xpdf)
.perl | Perl source (see .ph, .pl and .pm)
.pfa | PostScript font definition files, ASCII format
.pfb | PostScript font definition files, binary format
.pgm | portable greymap format
.pgp | PGP binary data
.ph | Perl header file
.php | PHP program file
.php3 | PHP3 program file
.pid | File to store daemon PID (e.g., crond.pid)
.pl | TeX property list file or Perl library file
.pm | Perl module
.png | Portable Network Graphics file
.po | Message catalog source
.pod | perldoc(1) file
.ppm | portable pixmap format
.pr | bitmap source
.ps | PostScript file
.py | Python source
.pyc | compiled python
.qt | quicktime movie
.r | RATFOR source (obsolete)
.rej | patches that patch(1) couldn't apply
.rpm | RedHat software package
.rtf | Rich Text Format file
.rules | rules for something
.s | assembler source
.sa | stub libraries for a.out shared libraries
.sc | sc(1) spreadsheet commands
.scm | Scheme source code
.sed | sed source file
.sgml | SGML source file
.sh | sh(1) scripts
.shar | archive created by the shar(1) utility
.so | Shared library or dynamically loadable object
.sql | SQL source
.sqml | SQML schema or query program
.sty | LaTeX style files
.sym | Modula-2 compiled definition modules
.tar | archive created by the tar(1) utility
.tar.Z | tar(1) archive compressed with compress(1)
.tar.bz2 | tar(1) archive compressed with bzip2(1)
.tar.gz | tar(1) archive compressed with gzip(1)
.taz | tar(1) archive compressed with compress(1)
.tcl | tcl source code
.tex | TeX or LaTeX source
.texi | equivalent to .texinfo
.texinfo | Texinfo documentation source
.text | text file
.tfm | TeX font metric file
.tgz | tar archive compressed with gzip(1)
.tif | poor man's .tiff
.tiff | Tagged Image File Format
.tk | tcl/tk script
.tmp | temporary file
.tmpl | template files
.txt | equivalent to .text
.uu | equivalent to .uue
.uue | binary file encoded with uuencode(1)
.vf | TeX virtual font file
.vpl | TeX virtual property list file
.w | Silvio Levi's CWEB
.wav | wave sound file
.web | Donald Knuth's WEB
.wml | Source file for Web Meta Language
.xbm | X11 bitmap source
.xcf | GIMP graphic
.xml | eXtended Markup Language file
.xsl | XSL stylesheet
.xpm | X11 pixmap source
.xs | Perl xsub file produced by h2xs
.y | yacc(1) or bison(1) (parser generator) files
.z | File compressed using pack(1) (or an old gzip(1))
.zip | zip(1) archive
.zoo | zoo(1) archive
~ | Emacs or patch(1) backup file
rc | startup (`run control') file, e.g., .newsrc

CONFORMING TO

General UNIX conventions.

BUGS

This list is not exhaustive.

SEE ALSO

file(1), make(1)


latin1(7)

Status: 403 Forbidden latin1(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/latin1.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


unix(7)

UNIX

Section: Linux Programmer's Manual (7)
Updated: 2004-05-27 Return to Main Contents

NAME

unix, PF_UNIX, AF_UNIX, PF_LOCAL, AF_LOCAL - Sockets for local interprocess communication

SYNOPSIS

#include <sys/socket.h>
#include <sys/un.h>

unix_socket = socket(PF_UNIX, type, 0);
error = socketpair(PF_UNIX, type, 0, int *sv);

DESCRIPTION

The PF_UNIX (also known as PF_LOCAL) socket family is used to communicate between processes on the same machine efficiently. Unix sockets can be either anonymous (created by socketpair(2)) or associated with a file of type socket. Linux also supports an abstract namespace which is independent of the file system.

Valid types are: SOCK_STREAM, for a stream-oriented socket and SOCK_DGRAM, for a datagram-oriented socket that preserves message boundaries (as on most Unix implementations, Unix domain datagram sockets are always reliable and don't reorder datagrams); and (since kernel 2.6.4) SOCK_SEQPACKET, for a connection-oriented socket that preserves message boundaries and delivers messages in the order that they were sent.

Unix sockets support passing file descriptors or process credentials to other processes using ancillary data.

Address Format

A Unix address is defined as a filename in the filesystem or as a unique string in the abstract namespace. Sockets created by socketpair(2) are anonymous. For non-anonymous sockets the target address can be set using connect(2). The local address can be set using bind(2). When a socket is connected and it doesn't already have a local address a unique address in the abstract namespace will be generated automatically.

#define UNIX_PATH_MAX    108

struct sockaddr_un {
    sa_family_t    sun_family;               /* AF_UNIX */
    char           sun_path[UNIX_PATH_MAX];  /* pathname */
};

sun_family always contains AF_UNIX. sun_path contains the zero-terminated pathname of the socket in the file system. If sun_path starts with a null byte ('' '), then it refers to the abstract namespace maintained by the Unix protocol module. The socket's address in this namespace is given by the rest of the bytes in sun_path. Note that names in the abstract namespace are not zero-terminated.

Socket Options

For historical reasons these socket options are specified with a SOL_SOCKET type even though they are PF_UNIX specific. They can be set with setsockopt(2) and read with getsockopt(2) by specifying SOL_SOCKET as the socket family.
SO_PASSCRED
Enables the receiving of the credentials of the sending process ancillary message. When this option is set and the socket is not yet connected a unique name in the abstract namespace will be generated automatically. Expects an integer boolean flag.

(Un)supported Features

The following paragraphs describe domain-specific details and unsupported features of the sockets API for Unix domain sockets on Linux.

Unix domain sockets do not support the transmission of out-of-band data (the MSG_OOB flag for send(2) and recv(2)).

The send(2) MSG_MORE flag is not supported by Unix domain sockets.

The SO_SNDBUF socket option does have an effect for Unix domain sockets, but the SO_RCVBUF option does not. For datagram sockets, the SO_SNDBUF value imposes an upper limit on the size of outgoing datagrams. This limit is calculated as the doubled (see socket(7)) option value less 32 bytes used for overhead.

Ancillary Messages

Ancillary data is sent and received using sendmsg(2) and recvmsg(2). For historical reasons the ancillary message types listed below are specified with a SOL_SOCKET type even though they are PF_UNIX specific. To send them set the cmsg_level field of the struct cmsghdr to SOL_SOCKET and the cmsg_type field to the type. For more information see cmsg(3).
SCM_RIGHTS
Send or receive a set of open file descriptors from another process. The data portion contains an integer array of the file descriptors. The passed file descriptors behave as though they have been created with dup(2).
SCM_CREDENTIALS
Send or receive Unix credentials. This can be used for authentication. The credentials are passed as a struct ucred ancillary message.

struct ucred {
    pid_t pid;    /* process ID of the sending process */
    uid_t uid;    /* user ID of the sending process */
    gid_t gid;    /* group ID of the sending process */
};

The credentials which the sender specifies are checked by the kernel. A process with effective user ID 0 is allowed to specify values that do not match its own. The sender must specify its own process ID (unless it has the capability CAP_SYS_ADMIN), its user ID, effective user ID, or saved set-user-ID (unless it has CAP_SETUID), and its group ID, effective group ID, or saved set-group-ID (unless it has CAP_SETGID). To receive a struct ucred message the SO_PASSCRED option must be enabled on the socket.

ERRORS

ENOMEM
Out of memory.
ECONNREFUSED
connect(2) called with a socket object that isn't listening. This can happen when the remote socket does not exist or the filename is not a socket.
EINVAL
Invalid argument passed. A common cause is the missing setting of AF_UNIX in the sun_type field of passed addresses or the socket being in an invalid state for the applied operation.
EOPNOTSUPP
Stream operation called on non-stream oriented socket or tried to use the out-of-band data option.
EPROTONOSUPPORT
Passed protocol is not PF_UNIX.
ESOCKTNOSUPPORT
Unknown socket type.
EPROTOTYPE
Remote socket does not match the local socket type (SOCK_DGRAM vs. SOCK_STREAM)
EADDRINUSE
Selected local address is already taken or filesystem socket object already exists.
EISCONN
connect(2) called on an already connected socket or a target address was specified on a connected socket.
ENOTCONN
Socket operation needs a target address, but the socket is not connected.
ECONNRESET
Remote socket was unexpectedly closed.
EPIPE
Remote socket was closed on a stream socket. If enabled, a SIGPIPE is sent as well. This can be avoided by passing the MSG_NOSIGNAL flag to sendmsg(2) or recvmsg(2).
EFAULT
User memory address was not valid.
EPERM
The sender passed invalid credentials in the struct ucred.

Other errors can be generated by the generic socket layer or by the filesystem while generating a filesystem socket object. See the appropriate manual pages for more information.

VERSIONS

SCM_CREDENTIALS and the abstract namespace were introduced with Linux 2.2 and should not be used in portable programs. (Some BSD-derived systems also support credential passing, but the implementation details differ.)

NOTES

In the Linux implementation, sockets which are visible in the filesystem honor the permissions of the directory they are in. Their owner, group and their permissions can be changed. Creation of a new socket will fail if the process does not have write and search (execute) permission on the directory the socket is created in. Connecting to the socket object requires read/write permission. This behavior differs from many BSD-derived systems which ignore permissions for Unix sockets. Portable programs should not rely on this feature for security.

Binding to a socket with a filename creates a socket in the file system that must be deleted by the caller when it is no longer needed (using unlink(2)). The usual Unix close-behind semantics apply; the socket can be unlinked at any time and will be finally removed from the file system when the last reference to it is closed.

To pass file descriptors or credentials over a SOCK_STREAM, you need to send or receive at least one byte of non-ancillary data in the same sendmsg(2) or recvmsg(2) call.

Unix domain stream sockets do not support the notion of out-of-band data.

EXAMPLE

See bind(2).

SEE ALSO

recvmsg(2), sendmsg(2), socket(2), socketpair(2), cmsg(3), capabilities(7), credentials(7), socket(7)


utf-8(7)

UTF-8

Section: Linux Programmer's Manual (7)
Updated: 2001-05-11 Return to Main Contents

NAME

UTF-8 - an ASCII compatible multi-byte Unicode encoding

DESCRIPTION

The Unicode 3.0 character set occupies a 16-bit code space. The most obvious Unicode encoding (known as UCS-2) consists of a sequence of 16-bit words. Such strings can contain as parts of many 16-bit characters bytes like '\0' or '/' which have a special meaning in filenames and other C library function parameters. In addition, the majority of UNIX tools expects ASCII files and can't read 16-bit words as characters without major modifications. For these reasons, UCS-2 is not a suitable external encoding of Unicode in filenames, text files, environment variables, etc. The .BR "ISO 10646 Universal Character Set (UCS)" , a superset of Unicode, occupies even a 31-bit code space and the obvious UCS-4 encoding for it (a sequence of 32-bit words) has the same problems.

The UTF-8 encoding of Unicode and UCS does not have these problems and is the common way in which Unicode is used on Unix-style operating systems.

PROPERTIES

The UTF-8 encoding has the following nice properties:
*
UCS characters 0x00000000 to 0x0000007f (the classic US-ASCII characters) are encoded simply as bytes 0x00 to 0x7f (ASCII compatibility). This means that files and strings which contain only 7-bit ASCII characters have the same encoding under both ASCII and UTF-8.
*
All UCS characters > 0x7f are encoded as a multi-byte sequence consisting only of bytes in the range 0x80 to 0xfd, so no ASCII byte can appear as part of another character and there are no problems with, for example, '\0' or '/'.
*
The lexicographic sorting order of UCS-4 strings is preserved.
*
All possible 2^31 UCS codes can be encoded using UTF-8.
*
The bytes 0xfe and 0xff are never used in the UTF-8 encoding.
*
The first byte of a multi-byte sequence which represents a single non-ASCII UCS character is always in the range 0xc0 to 0xfd and indicates how long this multi-byte sequence is. All further bytes in a multi-byte sequence are in the range 0x80 to 0xbf. This allows easy resynchronization and makes the encoding stateless and robust against missing bytes.
*
UTF-8 encoded UCS characters may be up to six bytes long, however the Unicode standard specifies no characters above 0x10ffff, so Unicode characters can only be up to four bytes long in UTF-8.

ENCODING

The following byte sequences are used to represent a character. The sequence to be used depends on the UCS code number of the character:
0x00000000 - 0x0000007F:
0xxxxxxx
0x00000080 - 0x000007FF:
110xxxxx 10xxxxxx
0x00000800 - 0x0000FFFF:
1110xxxx 10xxxxxx 10xxxxxx
0x00010000 - 0x001FFFFF:
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
0x00200000 - 0x03FFFFFF:
111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
0x04000000 - 0x7FFFFFFF:
1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

The xxx bit positions are filled with the bits of the character code number in binary representation. Only the shortest possible multi-byte sequence which can represent the code number of the character can be used.

The UCS code values 0xd800-0xdfff (UTF-16 surrogates) as well as 0xfffe and 0xffff (UCS non-characters) should not appear in conforming UTF-8 streams.

EXAMPLE

The Unicode character 0xa9 = 1010 1001 (the copyright sign) is encoded in UTF-8 as

11000010 10101001 = 0xc2 0xa9

and character 0x2260 = 0010 0010 0110 0000 (the "not equal" symbol) is encoded as:

11100010 10001001 10100000 = 0xe2 0x89 0xa0

APPLICATION NOTES

Users have to select a UTF-8 locale, for example with

export LANG=en_GB.UTF-8

in order to activate the UTF-8 support in applications.

Application software that has to be aware of the used character encoding should always set the locale with for example

setlocale(LC_CTYPE, "")

and programmers can then test the expression

strcmp(nl_langinfo(CODESET), "UTF-8") == 0

to determine whether a UTF-8 locale has been selected and whether therefore all plaintext standard input and output, terminal communication, plaintext file content, filenames and environment variables are encoded in UTF-8.

Programmers accustomed to single-byte encodings such as US-ASCII or ISO 8859 have to be aware that two assumptions made so far are no longer valid in UTF-8 locales. Firstly, a single byte does not necessarily correspond any more to a single character. Secondly, since modern terminal emulators in UTF-8 mode also support Chinese, Japanese, and Korean double-width characters as well as non-spacing combining characters, outputting a single character does not necessarily advance the cursor by one position as it did in ASCII. Library functions such as mbsrtowcs(3) and wcswidth(3) should be used today to count characters and cursor positions.

The official ESC sequence to switch from an ISO 2022 encoding scheme (as used for instance by VT100 terminals) to UTF-8 is ESC % G ("\x1b%G"). The corresponding return sequence from UTF-8 to ISO 2022 is ESC % @ ("\x1b%@"). Other ISO 2022 sequences (such as for switching the G0 and G1 sets) are not applicable in UTF-8 mode.

It can be hoped that in the foreseeable future, UTF-8 will replace ASCII and ISO 8859 at all levels as the common character encoding on POSIX systems, leading to a significantly richer environment for handling plain text.

SECURITY

The Unicode and UCS standards require that producers of UTF-8 shall use the shortest form possible, for example, producing a two-byte sequence with first byte 0xc0 is non-conforming. Unicode 3.1 has added the requirement that conforming programs must not accept non-shortest forms in their input. This is for security reasons: if user input is checked for possible security violations, a program might check only for the ASCII version of "/../" or ";" or NUL and overlook that there are many non-ASCII ways to represent these things in a non-shortest UTF-8 encoding.

STANDARDS

ISO/IEC 10646-1:2000, Unicode 3.1, RFC 2279, Plan 9.

SEE ALSO

nl_langinfo(3), setlocale(3), charsets(7), unicode(7)


locale(7)

LOCALE

Section: Linux Programmer's Manual (7)
Updated: 1993-04-24 Return to Main Contents

NAME

locale - Description of multi-language support

SYNOPSIS

#include <locale.h>

DESCRIPTION

A locale is a set of language and cultural rules. These cover aspects such as language for messages, different character sets, lexicographic conventions, etc. A program needs to be able to determine its locale and act accordingly to be portable to different cultures.

The header <locale.h> declares data types, functions and macros which are useful in this task.

The functions it declares are setlocale(3) to set the current locale, and localeconv(3) to get information about number formatting.

There are different categories for local information a program might need; they are declared as macros. Using them as the first argument to the setlocale(3) function, it is possible to set one of these to the desired locale:

LC_COLLATE
This is used to change the behavior of the functions strcoll(3) and strxfrm(3), which are used to compare strings in the local alphabet. For example, the German sharp s is sorted as "ss".
LC_CTYPE
This changes the behavior of the character handling and classification functions, such as isupper(3) and toupper(3), and the multi-byte character functions such as mblen(3) or wctomb(3).
LC_MONETARY
changes the information returned by localeconv(3) which describes the way numbers are usually printed, with details such as decimal point versus decimal comma. This information is internally used by the function strfmon(3).
LC_MESSAGES
changes the language messages are displayed in and how an affirmative or negative answer looks like. The GNU C-library contains the gettext(3), ngettext(3), and rpmatch(3) functions to ease the use of these information. The GNU gettext family of functions also obey the environment variable LANGUAGE.
LC_NUMERIC
changes the information used by the printf(3) and scanf(3) family of functions, when they are advised to use the locale-settings. This information can also be read with the localeconv(3) function.
LC_TIME
changes the behavior of the strftime(3) function to display the current time in a locally acceptable form; for example, most of Europe uses a 24-hour clock versus the 12-hour clock used in the United States.
LC_ALL
All of the above.

If the second argument to setlocale(3) is empty string, , for the default locale, it is determined using the following steps:

1.
If there is a non-null environment variable LC_ALL, the value of LC_ALL is used.
2.
If an environment variable with the same name as one of the categories above exists and is non-null, its value is used for that category.
3.
If there is a non-null environment variable LANG, the value of LANG is used.

Values about local numeric formatting is made available in a struct lconv returned by the localeconv(3) function, which has the following declaration:

struct lconv {

  /* Numeric (non-monetary) information */

  char *decimal_point;     /* Radix character */
  char *thousands_sep;     /* Separator for digit groups to left
                              of radix character */
  char *grouping; /* Each element is the number of digits in a
                     group; elements with higher indices are
                     further left.  An element with value CHAR_MAX
                     means that no further grouping is done.  An
                     element with value 0 means that the previous
                     element is used for all groups further left. */

  /* Remaining fields are for monetary information */

  char *int_curr_symbol;   /* First three chars are a currency symbol
                               from ISO 4217.  Fourth char is the
                               separator.  Fifth char is ' '. */
  char *currency_symbol;   /* Local currency symbol */
  char *mon_decimal_point; /* Radix character */
  char *mon_thousands_sep; /* Like `thousands_sep' above */
  char *mon_grouping;      /* Like `grouping' above */
  char *positive_sign;     /* Sign for positive values */
  char *negative_sign;     /* Sign for negative values */
  char  int_frac_digits;   /* Int'l fractional digits */
  char  frac_digits;       /* Local fractional digits */
  char  p_cs_precedes;     /* 1 if currency_symbol precedes a
                              positive value, 0 if succeeds */
  char  p_sep_by_space;    /* 1 if a space separates currency_symbol
                              from a positive value */
  char  n_cs_precedes;     /* 1 if currency_symbol precedes a
                              negative value, 0 if succeeds */
  char  n_sep_by_space;    /* 1 if a space separates currency_symbol
                              from a negative value */
  /* Positive and negative sign positions:
     0 Parentheses surround the quantity and currency_symbol.
     1 The sign string precedes the quantity and currency_symbol.
     2 The sign string succeeds the quantity and currency_symbol.
     3 The sign string immediately precedes the currency_symbol.
     4 The sign string immediately succeeds the currency_symbol. */
  char  p_sign_posn;
  char  n_sign_posn;
};

CONFORMING TO

POSIX.1-2001.

The GNU gettext functions are specified in LI18NUX2000.

SEE ALSO

locale(1), localedef(1), gettext(3), localeconv(3), ngettext(3), nl_langinfo(3), rpmatch(3), setlocale(3), strcoll(3), strfmon(3), strftime(3), strxfrm(3)


mailaddr(7)

MAILADDR

Section: Linux User's Manual (7)
Updated: 2004-09-15 Return to Main Contents

NAME

mailaddr - mail addressing description

DESCRIPTION

This manual page gives a brief introduction to SMTP mail addresses, as used on the Internet. These addresses are in the general format

        user@domain

where a domain is a hierarchical dot-separated list of subdomains. These examples are valid forms of the same address:

        eric@monet.berkeley.edu

       Eric Allman <eric@monet.berkeley.edu>

        eric@monet.berkeley.edu (Eric Allman)

The domain part ("monet.berkeley.edu") is a mail-accepting domain. It can be a host and in the past it usually was, but it doesn't have to be. The domain part is not case sensitive.

The local part ("eric") is often a user name, but its meaning is defined by the local software. Sometimes it is case sensitive, although that is unusual. If you see a local-part that looks like garbage, it is usually because of a gateway between an internal e-mail system and the net, here are some examples:

       "surname/admd=telemail/c=us/o=hp/prmd=hp"@some.where

        USER%SOMETHING@some.where

       machine!machine!name@some.where

        I2461572@some.where

(These are, respectively, an X.400 gateway, a gateway to an arbitrary internal mail system that lacks proper internet support, an UUCP gateway, and the last one is just boring username policy.)

The real-name part ("Eric Allman") can either be placed before <>, or in () at the end. (Strictly speaking the two aren't the same, but the difference is beyond the scope of this page.) The name may have to be quoted using "", for example, if it contains ".":

       "Eric P. Allman" <eric@monet.berkeley.edu>

Abbreviation.

Many mail systems let users abbreviate the domain name. For instance, users at berkeley.edu may get away with "eric@monet" to send mail to Eric Allman. This behavior is deprecated. Sometimes it works, but you should not depend on it.

Route-addrs.

In the past, sometimes one had to route a message through several hosts to get it to its final destination. Addresses which show these relays are termed "route-addrs". These use the syntax:

       <@hosta,@hostb:user@hostc>

This specifies that the message should be sent to hosta, from there to hostb, and finally to hostc. Many hosts disregard route-addrs and send directly to hostc.

Route-addrs are very unusual now. They occur sometimes in old mail archives. It is generally possible to ignore all but the "user@hostc" part of the address to determine the actual address.

Postmaster.

Every site is required to have a user or user alias designated "postmaster" to which problems with the mail system may be addressed. The "postmaster" address is not case sensitive.

FILES

/etc/aliases
~/.forward

SEE ALSO

binmail(1), mail(1), mconnect(1), aliases(5), forward(5), sendmail(8), vrfy(8)

RFC 2822 (Internet Message Format)


netlink(7)

NETLINK

Section: Linux Programmer's Manual (7)
Updated: 2005-12-27 Return to Main Contents

NAME

netlink - Communication between kernel and userspace (PF_NETLINK)

SYNOPSIS

#include <asm/types.h>

#include <sys/socket.h>

#include <linux/netlink.h>

netlink_socket = socket(PF_NETLINK, socket_type, netlink_family);

DESCRIPTION

Netlink is used to transfer information between kernel and userspace processes. It consists of a standard sockets-based interface for userspace processes and an internal kernel API for kernel modules. The internal kernel interface is not documented in this manual page. There is also an obsolete netlink interface via netlink character devices; this interface is not documented here and is only provided for backwards compatibility.

Netlink is a datagram-oriented service. Both SOCK_RAW and SOCK_DGRAM are valid values for socket_type. However, the netlink protocol does not distinguish between datagram and raw sockets.

netlink_family selects the kernel module or netlink group to communicate with. The currently assigned netlink families are:

NETLINK_ROUTE
Receives routing and link updates and may be used to modify the routing tables (both IPv4 and IPv6), IP addresses, link parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers (see rtnetlink(7)).
NETLINK_W1
Messages from 1-wire subsystem.
NETLINK_USERSOCK
Reserved for user-mode socket protocols.
NETLINK_FIREWALL
Transport IPv4 packets from netfilter to userspace. Used by ip_queue kernel module.
NETLINK_INET_DIAG
INET socket monitoring.
NETLINK_NFLOG
Netfilter/iptables ULOG.
NETLINK_XFRM
IPsec.
NETLINK_SELINUX
SELinux event notifications.
NETLINK_ISCSI
Open-iSCSI.
NETLINK_AUDIT
Auditing.
NETLINK_FIB_LOOKUP
Access to FIB lookup from userspace.
NETLINK_CONNECTOR
Kernel connector. See Documentation/connector/* in the kernel source for further information.
NETLINK_NETFILTER
Netfilter subsystem.
NETLINK_IP6_FW
Transport IPv6 packets from netfilter to userspace. Used by ip6_queue kernel module.
NETLINK_DNRTMSG
DECnet routing messages.
NETLINK_KOBJECT_UEVENT
Kernel messages to userspace.
NETLINK_GENERIC
Generic netlink family for simplified netlink usage.

Netlink messages consist of a byte stream with one or multiple nlmsghdr headers and associated payload. The byte stream should only be accessed with the standard NLMSG_* macros. See netlink(3) for further information.

In multipart messages (multiple nlmsghdr headers with associated payload in one byte stream) the first and all following headers have the NLM_F_MULTI flag set, except for the last header which has the type NLMSG_DONE.

After each nlmsghdr the payload follows.

struct nlmsghdr {
    __u32 nlmsg_len;    /* Length of message including header. */
    __u16 nlmsg_type;   /* Type of message content. */
    __u16 nlmsg_flags;  /* Additional flags. */
    __u32 nlmsg_seq;    /* Sequence number. */
    __u32 nlmsg_pid;    /* PID of the sending process. */
};

nlmsg_type can be one of the standard message types: NLMSG_NOOP message is to be ignored, NLMSG_ERROR message signals an error and the payload contains an nlmsgerr structure, NLMSG_DONE message terminates a multipart message.

struct nlmsgerr {
    int error;        /* Negative errno or 0 for acknowledgements */
    struct nlmsghdr msg;  /* Message header that caused the error */
};

A netlink family usually specifies more message types, see the appropriate manual pages for that, for example, rtnetlink(7) for NETLINK_ROUTE.

Standard flag bits in nlmsg_flags
---------------------------------
NLM_F_REQUEST | Must be set on all request messages.
NLM_F_MULTI | The message is part of a multipart message terminated by NLMSG_DONE.
NLM_F_ACK | Request for an acknowledgment on success.
NLM_F_ECHO | Echo this request.

Additional flag bits for GET requests
-------------------------------------
NLM_F_ROOT | Return the complete table instead of a single entry.
NLM_F_MATCH | Return all entries matching criteria passed in message content. Not implemented yet.
NLM_F_ATOMIC | Return an atomic snapshot of the table.
NLM_F_DUMP | Convenience macro; equivalent to (NLM_F_ROOT|NLM_F_MATCH).

Note that NLM_F_ATOMIC requires the CAP_NET_ADMIN capability or an effective UID of 0.

Additional flag bits for NEW requests
-------------------------------------
NLM_F_REPLACE | Replace existing matching object.
NLM_F_EXCL | Don't replace if the object already exists.
NLM_F_CREATE | Create object if it doesn't already exist.
NLM_F_APPEND | Add to the end of the object list.

nlmsg_seq and nlmsg_pid are used to track messages. nlmsg_pid shows the origin of the message. Note that there isn't a 1:1 relationship between nlmsg_pid and the PID of the process if the message originated from a netlink socket. See the ADDRESS FORMATS section for further information.

Both nlmsg_seq and nlmsg_pid are opaque to netlink core.

Netlink is not a reliable protocol. It tries its best to deliver a message to its destination(s), but may drop messages when an out-of-memory condition or other error occurs. For reliable transfer the sender can request an acknowledgement from the receiver by setting the NLM_F_ACK flag. An acknowledgment is an NLMSG_ERROR packet with the error field set to 0. The application must generate acknowledgements for received messages itself. The kernel tries to send an NLMSG_ERROR message for every failed packet. A user process should follow this convention too.

However, reliable transmissions from kernel to user are impossible in any case. The kernel can't send a netlink message if the socket buffer is full: the message will be dropped and the kernel and the userspace process will no longer have the same view of kernel state. It is up to the application to detect when this happens (via the ENOBUFS error returned by recvmsg(2)) and resynchronize.

Address Formats

The sockaddr_nl structure describes a netlink client in user space or in the kernel. A sockaddr_nl can be either unicast (only sent to one peer) or sent to netlink multicast groups (nl_groups not equal 0).

struct sockaddr_nl {
    sa_family_t     nl_family;  /* AF_NETLINK */
    unsigned short  nl_pad;     /* Zero. */
    pid_t           nl_pid;     /* Process ID. */
    __u32           nl_groups;  /* Multicast groups mask. */
};

nl_pid is the unicast address of netlink socket. It's always 0 if the destination is in the kernel. For a userspace process, nl_pid is usually the PID of the process owning the destination socket. However, nl_pid identifies a netlink socket, not a process. If a process owns several netlink sockets, then nl_pid can only be equal to the process ID for at most one socket. There are two ways to assign nl_pid to a netlink socket. If the application sets nl_pid before calling bind(2), then it is up to the application to make sure that nl_pid is unique. If the application sets it to 0, the kernel takes care of assigning it. The kernel assigns the process ID to the first netlink socket the process opens and assigns a unique nl_pid to every netlink socket that the process subsequently creates.

nl_groups is a bitmask with every bit representing a netlink group number. Each netlink family has a set of 32 multicast groups. When bind(2) is called on the socket, the nl_groups field in the sockaddr_nl should be set to a bitmask of the groups which it wishes to listen to. The default value for this field is zero which means that no multicasts will be received. A socket may multicast messages to any of the multicast groups by setting nl_groups to a bitmask of the groups it wishes to send to when it calls sendmsg(2) or does a connect(2). Only processes with an effective UID of 0 or the CAP_NET_ADMIN capability may send or listen to a netlink multicast group. Any replies to a message received for a multicast group should be sent back to the sending PID and the multicast group.

VERSIONS

The socket interface to netlink is a new feature of Linux 2.2.

Linux 2.0 supported a more primitive device based netlink interface (which is still available as a compatibility option). This obsolete interface is not described here.

NETLINK_SELINUX appeared in Linux 2.6.4.

NETLINK_AUDIT appeared in Linux 2.6.6.

NETLINK_KOBJECT_UEVENT appeared in Linux 2.6.10.

NETLINK_W1 and NETLINK_FIB_LOOKUP appeared in Linux 2.6.13.

NETLINK_INET_DIAG, NETLINK_CONNECTOR and NETLINK_NETFILTER appeared in Linux 2.6.14.

NETLINK_GENERIC and NETLINK_ISCSI appeared in Linux 2.6.15.

NOTES

It is often better to use netlink via libnetlink or libnl than via the low level kernel interface.

BUGS

This manual page is not complete.

EXAMPLE

The following example creates a NETLINK_ROUTE netlink socket which will listen to the RTMGRP_LINK (network interface create/delete/up/down events) and RTMGRP_IPV4_IFADDR (IPv4 addresses add/delete events) multicast groups.

struct sockaddr_nl sa;

memset(&sa, 0, sizeof(sa));
snl.nl_family = AF_NETLINK;
snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;

fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
bind(fd, (struct sockaddr*)&sa, sizeof(sa));

The next example demonstrates how to send a netlink message to the kernel (pid 0). Note that application must take care of message sequence numbers in order to reliably track acknowledgements.

struct nlmsghdr *nh;    /* The nlmsghdr with payload to send. */
struct sockaddr_nl sa;
struct iovec iov = { (void *) nh, nh->nlmsg_len };
struct msghdr msg;

msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
memset(&sa, 0, sizeof(sa));
sa.nl_family = AF_NETLINK;
nh->nlmsg_pid = 0;
nh->nlmsg_seq = ++sequence_number;
/* Request an ack from kernel by setting NLM_F_ACK. */
nh->nlmsg_flags |= NLM_F_ACK;

sendmsg(fd, &msg, 0);

And the last example is about reading netlink message.

int len;
char buf[4096];
struct iovec iov = { buf, sizeof(buf) };
struct sockaddr_nl sa;
struct msghdr msg;
struct nlmsghdr *nh;

msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
len = recvmsg(fd, &msg, 0);

for (nh = (struct nlmsghdr *) buf; NLMSG_OK (nh, len);
     nh = NLMSG_NEXT (nh, len)) {
    /* The end of multipart message. */
    if (nh->nlmsg_type == NLMSG_DONE)
        return;

    if (nh->nlmsg_type == NLMSG_ERROR)
        /* Do some error handling. */
    ...

    /* Continue with parsing payload. */
    ...
}

SEE ALSO

cmsg(3), netlink(3), capabilities(7), rtnetlink(7)

ftp://ftp.inr.ac.ru/ip-routing/iproute2* for information about libnetlink.

http://people.suug.ch/~tgr/libnl/ for information about libnl.

RFC 3549 "Linux Netlink as an IP Services Protocol"


signal(7)

SIGNAL

Section: Linux Programmer's Manual (7)
Updated: 2002-06-13 Return to Main Contents

NAME

signal - list of available signals

DESCRIPTION

Linux supports both POSIX reliable signals (hereinafter "standard signals") and POSIX real-time signals.

Signal Dispositions

Each signal has a current disposition, which determines how the process behaves when it is delivered the signal.

The entries in the "Action" column of the tables below specify the default disposition for each signal, as follows:

Term
Default action is to terminate the process.
Ign
Default action is to ignore the signal.
Core
Default action is to terminate the process and dump core (see core(5)).
Stop
Default action is to stop the process.
Cont
Default action is to continue the process if it is currently stopped.

A process can change the disposition of a signal using sigaction(2) or (less portably) signal(2). Using these system calls, a process can elect one of the following behavior to occur on delivery of the signal: perform the default action; ignore the signal; or catch the signal with a signal handler, a programmer-defined function that is automatically invoked when the signal is delivered.

The signal disposition is a per-process attribute: in a multithreaded application, the disposition of a particular signal is the same for all threads.

Signal Mask and Pending Signals

A signal may be blocked, which means that it will not be delivered until it is later unblocked. Between the time when it is generated and when it is delivered a signal is said to be pending.

Each thread in a process has an independent signal mask, which indicates the set of signals that the thread is currently blocking. A thread can manipulate its signal mask using pthread_sigmask(3). In a traditional single-threaded application, sigprocmask(2) can be used to manipulate the signal mask.

A signal may be generated (and thus pending) for a process as a whole (e.g., when sent using kill(2)) or for a specific thread (e.g., certain signals, such as SIGSEGV and SIGFPE, generated as a consequence of executing a specific machine-language instruction are thread directed, as are signals targeted at a specific thread using pthread_kill(2)). A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.

A thread can obtain the set of signals that it currently has pending using sigpending(2). This set will consist of the union of the set of pending process-directed signals and the set of signals pending for the calling thread.

Standard Signals

Linux supports the standard signals listed below. Several signal numbers are architecture dependent, as indicated in the "Value" column. (Where three values are given, the first one is usually valid for alpha and sparc, the middle one for i386, ppc and sh, and the last one for mips. A - denotes that a signal is absent on the corresponding architecture.)

First the signals described in the original POSIX.1-1990 standard.
Signal | Value | Action | Comment
 |  |  | or death of controlling process
SIGINT | 2 | Term | Interrupt from keyboard
SIGQUIT | 3 | Core | Quit from keyboard
SIGILL | 4 | Core | Illegal Instruction
SIGABRT | 6 | Core | Abort signal from abort(3)
SIGFPE | 8 | Core | Floating point exception
SIGKILL | 9 | Term | Kill signal
SIGSEGV | 11 | Core | Invalid memory reference
SIGPIPE | 13 | Term | Broken pipe: write to pipe with no readers
SIGALRM | 14 | Term | Timer signal from alarm(2)
SIGTERM | 15 | Term | Termination signal
SIGUSR1 | 30,10,16 | Term | User-defined signal 1
SIGUSR2 | 31,12,17 | Term | User-defined signal 2
SIGCHLD | 20,17,18 | Ign | Child stopped or terminated
SIGCONT | 19,18,25 | Cont | Continue if stopped
SIGSTOP | 17,19,23 | Stop | Stop process
SIGTSTP | 18,20,24 | Stop | Stop typed at tty
SIGTTIN | 21,21,26 | Stop | tty input for background process
SIGTTOU | 22,22,27 | Stop | tty output for background process

The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored.

Next the signals not in the POSIX.1-1990 standard but described in SUSv2 and POSIX.1-2001.
Signal | Value | Action | Comment
SIGPOLL |  | Term | Pollable event (Sys V). Synonym of SIGIO
SIGPROF | 27,27,29 | Term | Profiling timer expired
SIGSYS | 12,-,12 | Core | Bad argument to routine (SVr4)
SIGTRAP | 5 | Core | Trace/breakpoint trap
SIGURG | 16,23,21 | Ign | Urgent condition on socket (4.2BSD)
SIGVTALRM | 26,26,28 | Term | Virtual alarm clock (4.2BSD)
SIGXCPU | 24,24,30 | Core | CPU time limit exceeded (4.2BSD)
SIGXFSZ | 25,25,31 | Core | File size limit exceeded (4.2BSD)

Up to and including Linux 2.2, the default behavior for SIGSYS, SIGXCPU, SIGXFSZ, and (on architectures other than SPARC and MIPS) SIGBUS was to terminate the process (without a core dump). (On some other Unix systems the default action for SIGXCPU and SIGXFSZ is to terminate the process without a core dump.) Linux 2.4 conforms to the POSIX.1-2001 requirements for these signals, terminating the process with a core dump.

Next various other signals.
Signal | Value | Action | Comment
SIGEMT | 7,-,7 | Term |
SIGSTKFLT | -,16,- | Term | Stack fault on coprocessor (unused)
SIGIO | 23,29,22 | Term | I/O now possible (4.2BSD)
SIGCLD | -,-,18 | Ign | A synonym for SIGCHLD
SIGPWR | 29,30,19 | Term | Power failure (System V)
SIGINFO | 29,-,- |  | A synonym for SIGPWR
SIGLOST | -,-,- | Term | File lock lost
SIGWINCH | 28,28,20 | Ign | Window resize signal (4.3BSD, Sun)
SIGUNUSED | -,31,- | Term | Unused signal (will be SIGSYS)

(Signal 29 is SIGINFO / SIGPWR on an alpha but SIGLOST on a sparc.)

SIGEMT is not specified in POSIX.1-2001, but nevertheless appears on most other Unix systems, where its default action is typically to terminate the process with a core dump.

SIGPWR (which is not specified in POSIX.1-2001) is typically ignored by default on those other Unix systems where it appears.

SIGIO (which is not specified in POSIX.1-2001) is ignored by default on several other Unix systems.

Real-time Signals

Linux supports real-time signals as originally defined in the POSIX.1b real-time extensions (and now included in POSIX.1-2001). Linux supports 32 real-time signals, numbered from 32 (SIGRTMIN) to 63 (SIGRTMAX). (Programs should always refer to real-time signals using notation SIGRTMIN+n, since the range of real-time signal numbers varies across Unix systems.)

Unlike standard signals, real-time signals have no predefined meanings: the entire set of real-time signals can be used for application-defined purposes. (Note, however, that the LinuxThreads implementation uses the first three real-time signals.)

The default action for an unhandled real-time signal is to terminate the receiving process.

Real-time signals are distinguished by the following:

1.
Multiple instances of real-time signals can be queued. By contrast, if multiple instances of a standard signal are delivered while that signal is currently blocked, then only one instance is queued.
2.
If the signal is sent using sigqueue(2), an accompanying value (either an integer or a pointer) can be sent with the signal. If the receiving process establishes a handler for this signal using the SA_SIGINFO flag to sigaction(2) then it can obtain this data via the si_value field of the siginfo_t structure passed as the second argument to the handler. Furthermore, the si_pid and si_uid fields of this structure can be used to obtain the PID and real user ID of the process sending the signal.
3.
Real-time signals are delivered in a guaranteed order. Multiple real-time signals of the same type are delivered in the order they were sent. If different real-time signals are sent to a process, they are delivered starting with the lowest-numbered signal. (I.e., low-numbered signals have highest priority.)

If both standard and real-time signals are pending for a process, POSIX leaves it unspecified which is delivered first. Linux, like many other implementations, gives priority to standard signals in this case.

According to POSIX, an implementation should permit at least _POSIX_SIGQUEUE_MAX (32) real-time signals to be queued to a process. However, Linux does things differently. In kernels up to and including 2.6.7, Linux imposes a system-wide limit on the number of queued real-time signals for all processes. This limit can be viewed and (with privilege) changed via the /proc/sys/kernel/rtsig-max file. A related file, /proc/sys/kernel/rtsig-nr, can be used to find out how many real-time signals are currently queued. In Linux 2.6.8, these /proc interfaces were replaced by the RLIMIT_SIGPENDING resource limit, which specifies a per-user limit for queued signals; see setrlimit(2) for further details.

Async-signal-safe functions

A signal handling routine established by sigaction(2) or signal(2) must be very careful, since processing elsewhere may be interrupted at some arbitrary point in the execution of the program1. POSIX has the concept of "safe function". If a signal interrupts the execution of an unsafe function, and handler calls an unsafe function, then the behavior of the program is undefined. POSIX.1-2003 requires an implementation to guarantee that the following functions can be safely called inside a signal handler:

_Exit(),
_exit(),
abort(),
accept(),
access(),
aio_error(),
aio_return(),
aio_suspend(),
alarm(),
bind(),
cfgetispeed(),
cfgetospeed(),
cfsetispeed(),
cfsetospeed(),
chdir(),
chmod(),
chown(),
clock_gettime(),
close(),
connect(),
creat(),
dup(),
dup2(),
execle(),
execve(),
fchmod(),
fchown(),
fcntl(),
fdatasync(),
fork(),
fpathconf(),
fstat(),
fsync(),
ftruncate(),
getegid(),
geteuid(),
getgid(),
getgroups(),
getpeername(),
getpgrp(),
getpid(),
getppid(),
getsockname(),
getsockopt(),
getuid(),
kill(),
link(),
listen(),
lseek(),
lstat(),
mkdir(),
mkfifo(),
open(),
pathconf(),
pause(),
pipe(),
poll(),
posix_trace_event(),
pselect(),
raise(),
read(),
readlink(),
recv(),
recvfrom(),
recvmsg(),
rename(),
rmdir(),
select(),
sem_post(),
send(),
sendmsg(),
sendto(),
setgid(),
setpgid(),
setsid(),
setsockopt(),
setuid(),
shutdown(),
sigaction(),
sigaddset(),
sigdelset(),
sigemptyset(),
sigfillset(),
sigismember(),
signal(),
sigpause(),
sigpending(),
sigprocmask(),
sigqueue(),
sigset(),
sigsuspend(),
sleep(),
socket(),
socketpair(),
stat(),
symlink(),
sysconf(),
tcdrain(),
tcflow(),
tcflush(),
tcgetattr(),
tcgetpgrp(),
tcsendbreak(),
tcsetattr(),
tcsetpgrp(),
time(),
timer_getoverrun(),
timer_gettime(),
timer_settime(),
times(),
umask(),
uname(),
unlink(),
utime(),
wait(),
waitpid(),
write().

CONFORMING TO

POSIX.1

BUGS

SIGIO and SIGLOST have the same value. The latter is commented out in the kernel source, but the build process of some software still thinks that signal 29 is SIGLOST.

SEE ALSO

kill(1), kill(2), killpg(2), setitimer(2), setrlimit(2), sigaction(2), signal(2), sigpending(2), sigprocmask(2), sigqueue(2), sigsuspend(2), sigwaitinfo(2), bsd_signal(3), raise(3), sigvec(3), sigset(3), strsignal(3), sysv_signal(3), core(5), proc(5), pthreads(7)


rtnetlink(7)

RTNETLINK

Section: Linux Programmer's Manual (7)
Updated: 1999-04-30 Return to Main Contents

NAME

rtnetlink, NETLINK_ROUTE - Linux IPv4 routing socket

SYNOPSIS

#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/socket.h>

rtnetlink_socket = socket(PF_NETLINK, int socket_type, NETLINK_ROUTE);

DESCRIPTION

Rtnetlink allows the kernel's routing tables to be read and altered. It is used within the kernel to communicate between various subsystems, though this usage is not documented here, and for communication with user-space programs. Network routes, ip addresses, link parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers may all be controlled through NETLINK_ROUTE sockets. It is based on netlink messages, see netlink(7) for more information.

Routing Attributes

Some rtnetlink messages have optional attributes after the initial header:

struct rtattr {
    unsigned short rta_len;    /* Length of option */
    unsigned short rta_type;   /* Type of option */
    /* Data follows */
};

These attributes should be only manipulated using the RTA_* macros or libnetlink, see rtnetlink(3).

Messages

Rtnetlink consists of these message types (in addition to standard netlink messages):
RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK
Create, remove or get information about a specific network interface. These messages contain an ifinfomsg structure followed by a series of rtattr structures.

struct ifinfomsg {
    unsigned char  ifi_family; /* AF_UNSPEC */
    unsigned short ifi_type;   /* Device type */
    int            ifi_index;  /* Interface index */
    unsigned int   ifi_flags;  /* Device flags  */
    unsigned int   ifi_change; /* change mask */
};

ifi_flags contains the device flags, see netdevice(7); ifi_index is the unique interface index, ifi_change is reserved for future use and should be always set to 0xFFFFFFFF.
Routing attributes
rta_type
value type
description
IFLA_UNSPEC
-
unspecified.
IFLA_ADDRESS
hardware address
interface L2 address
IFLA_BROADCAST
hardware address
L2 broadcast address.
IFLA_IFNAME
asciiz string
Device name.
IFLA_MTU
unsigned int
MTU of the device.
IFLA_LINK
int
Link type.
IFLA_QDISC
asciiz string
Queueing discipline.
IFLA_STATS
 see below
Interface Statistics.

The value type for IFLA_STATS is struct net_device_stats.

RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR
Add, remove or receive information about an IP address associated with an interface. In Linux 2.2 an interface can carry multiple IP addresses, this replaces the alias device concept in 2.0. In Linux 2.2 these messages support IPv4 and IPv6 addresses. They contain an ifaddrmsg structure, optionally followed by rtaddr routing attributes.

struct ifaddrmsg {
    unsigned char ifa_family;    /* Address type */
    unsigned char ifa_prefixlen; /* Prefixlength of address */
    unsigned char ifa_flags;     /* Address flags */
    unsigned char ifa_scope;     /* Address scope */
    int           ifa_index;     /* Interface index */
};

ifa_family is the address family type (currently AF_INET or AF_INET6), ifa_prefixlen is the length of the address mask of the address if defined for the family (like for IPv4), ifa_scope is the address scope, ifa_index is the interface index of the interface the address is associated with. ifa_flags is a flag word of IFA_F_SECONDARY for secondary address (old alias interface), IFA_F_PERMANENT for a permanent address set by the user and other undocumented flags.

Attributes
rta_type
value type
description
IFA_UNSPEC
-
unspecified.
IFA_ADDRESS
raw protocol address
interface address
IFA_LOCAL
raw protocol address
local address
IFA_LABEL
asciiz string
name of the interface
IFA_BROADCAST
raw protocol address
broadcast address.
IFA_ANYCAST
raw protocol address
anycast address
IFA_CACHEINFO
struct ifa_cacheinfo
Address information.

RTM_NEWROUTE, RTM_DELROUTE, RTM_GETROUTE
Create, remove or receive information about a network route. These messages contain an rtmsg structure with an optional sequence of rtattr structures following. For RTM_GETROUTE setting rtm_dst_len and rtm_src_len to 0 means you get all entries for the specified routing table. For the other fields except rtm_table and rtm_protocol 0 is the wildcard.

struct rtmsg {
    unsigned char rtm_family;   /* Address family of route */
    unsigned char rtm_dst_len;  /* Length of source */
    unsigned char rtm_src_len;  /* Length of destination */
    unsigned char rtm_tos;      /* TOS filter */

    unsigned char rtm_table;    /* Routing table ID */
    unsigned char rtm_protocol; /* Routing protocol; see below */
    unsigned char rtm_scope;    /* See below */
    unsigned char rtm_type;     /* See below */

    unsigned int  rtm_flags;
};

rtm_type Route type
RTN_UNSPEC unknown route
RTN_UNICAST a gateway or direct route
RTN_LOCAL a local interface route
RTN_BROADCAST a local broadcast route (sent as a broadcast)
RTN_ANYCAST a local broadcast route (sent as a unicast)
RTN_MULTICAST a multicast route
RTN_BLACKHOLE a packet dropping route
RTN_UNREACHABLE an unreachable destination
RTN_PROHIBIT a packet rejection route
RTN_THROW continue routing lookup in another table
RTN_NAT a network address translation rule
RTN_XRESOLVE refer to an external resolver (not implemented)

rtm_protocol Route origin.
RTPROT_UNSPEC unknown
RTPROT_REDIRECT by an ICMP redirect (currently unused)
RTPROT_KERNEL by the kernel
RTPROT_BOOT during boot
RTPROT_STATIC by the administrator

Values larger than RTPROT_STATIC are not interpreted by the kernel, they are just for user information. They may be used to tag the source of a routing information or to distinguish between multiple routing daemons. See <linux/rtnetlink.h> for the routing daemon identifiers which are already assigned.

rtm_scope is the distance to the destination:

RT_SCOPE_UNIVERSE global route
RT_SCOPE_SITE interior route in the local autonomous system
RT_SCOPE_LINK route on this link
RT_SCOPE_HOST route on the local host
RT_SCOPE_NOWHERE destination doesn't exist

The values between RT_SCOPE_UNIVERSE and RT_SCOPE_SITE are available to the user.

The rtm_flags have the following meanings:

RTM_F_NOTIFY if the route changes, notify the user via rtnetlink
RTM_F_CLONED route is cloned from another route
RTM_F_EQUALIZE a multicast equalizer (not yet implemented)

rtm_table specifies the routing table

RT_TABLE_UNSPEC an unspecified routing table
RT_TABLE_DEFAULT the default table
RT_TABLE_MAIN the main table
RT_TABLE_LOCAL the local table

The user may assign arbitrary values between RT_TABLE_UNSPEC and RT_TABLE_DEFAULT.

Attributes
rta_type
value type
description
RTA_UNSPEC
-
ignored.
RTA_DST
protocol address
Route destination address.
RTA_SRC
protocol address
Route source address.
RTA_IIF
int
Input interface index.
RTA_OIF
int
Output interface index.
RTA_GATEWAY
protocol address
The gateway of the route
RTA_PRIORITY
int
Priority of route.
RTA_PREFSRC

RTA_METRICS
int
Route metric
RTA_MULTIPATH

RTA_PROTOINFO

RTA_FLOW

RTA_CACHEINFO

Fill these values in!

RTM_NEWNEIGH, RTM_DELNEIGH, RTM_GETNEIGH
Add, remove or receive information about a neighbor table entry (e.g., an ARP entry). The message contains an ndmsg structure.

struct ndmsg {
    unsigned char ndm_family;
    int           ndm_ifindex;  /* Interface index */
    __u16         ndm_state;    /* State */
    __u8          ndm_flags;    /* Flags */
    __u8          ndm_type;
};

struct nda_cacheinfo {
    __u32         ndm_confirmed;
    __u32         ndm_used;
    __u32         ndm_updated;
    __u32         ndm_refcnt;
};

ndm_state is a bitmask of the following states:

NUD_INCOMPLETE a currently resolving cache entry
NUD_REACHABLE a confirmed working cache entry
NUD_STALE an expired cache entry
NUD_DELAY an entry waiting for a timer
NUD_PROBE a cache entry that is currently reprobed
NUD_FAILED an invalid cache entry
NUD_NOARP a device with no destination cache
NUD_PERMANENT a static entry

Valid ndm_flags are:

NTF_PROXY a proxy arp entry
NTF_ROUTER an IPv6 router

document the members of the struct better

The rtaddr struct has the following meanings for the rta_type field:

NDA_UNSPEC unknown type
NDA_DST a neighbor cache n/w layer destination address
NDA_LLADDR a neighbor cache link layer address
NDA_CACHEINFO cache statistics.

If the rta_type field is NDA_CACHEINFO then a struct nda_cacheinfo header follows

RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE
Add, delete or retrieve a routing rule. Carries a struct rtmsg
RTM_NEWQDISC, RTM_DELQDISC, RTM_GETQDISC
Add, remove or get a queueing discipline. The message contains a struct tcmsg and may be followed by a series of attributes.

struct tcmsg {
    unsigned char    tcm_family;
    int              tcm_ifindex;   /* interface index */
    __u32            tcm_handle;    /* Qdisc handle */
    __u32            tcm_parent;    /* Parent qdisc */
    __u32            tcm_info;
};

Attributes
rta_type
value type
Description
TCA_UNSPEC
-
unspecified
TCA_KIND
asciiz string
Name of queueing discipline
TCA_OPTIONS
byte sequence
Qdisc specific options follow
TCA_STATS
struct tc_stats
Qdisc statistics.
TCA_XSTATS
qdisc specific
Module specific statistics.
TCA_RATE
struct tc_estimator
Rate limit.

In addition various other qdisc module specific attributes are allowed. For more information see the appropriate include files.

RTM_NEWTCLASS, RTM_DELTCLASS, RTM_GETTCLASS
Add, remove or get a traffic class. These messages contain a struct tcmsg as described above.
RTM_NEWTFILTER, RTM_DELTFILTER, RTM_GETTFILTER
Add, remove or receive information about a traffic filter. These messages contain a struct tcmsg as described above.

VERSIONS

rtnetlink is a new feature of Linux 2.2.

BUGS

This manual page is incomplete.

SEE ALSO

cmsg(3), rtnetlink(3), ip(7), netlink(7)


ip(7)

IP

Section: Linux Programmer's Manual (7)
Updated: 2001-06-19 Return to Main Contents

NAME

ip - Linux IPv4 protocol implementation

SYNOPSIS

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */

tcp_socket = socket(PF_INET, SOCK_STREAM, 0);
udp_socket = socket(PF_INET, SOCK_DGRAM, 0);
raw_socket = socket(PF_INET, SOCK_RAW, protocol);

DESCRIPTION

Linux implements the Internet Protocol, version 4, described in RFC 791 and RFC 1122. ip contains a level 2 multicasting implementation conforming to RFC 1112. It also contains an IP router including a packet filter.

The programming interface is BSD sockets compatible. For more information on sockets, see socket(7).

An IP socket is created by calling the socket(2) function as socket(PF_INET, socket_type, protocol). Valid socket types are SOCK_STREAM to open a tcp(7) socket, SOCK_DGRAM to open a udp(7) socket, or SOCK_RAW to open a raw(7) socket to access the IP protocol directly. protocol is the IP protocol in the IP header to be received or sent. The only valid values for protocol are 0 and IPPROTO_TCP for TCP sockets and 0 and IPPROTO_UDP for UDP sockets. For SOCK_RAW you may specify a valid IANA IP protocol defined in RFC 1700 assigned numbers.

When a process wants to receive new incoming packets or connections, it should bind a socket to a local interface address using bind(2). Only one IP socket may be bound to any given local (address, port) pair. When INADDR_ANY is specified in the bind call the socket will be bound to all local interfaces. When listen(2) or connect(2) are called on an unbound socket, it is automatically bound to a random free port with the local address set to INADDR_ANY.

A TCP local socket address that has been bound is unavailable for some time after closing, unless the SO_REUSEADDR flag has been set. Care should be taken when using this flag as it makes TCP less reliable.

Address Format

An IP socket address is defined as a combination of an IP interface address and a 16-bit port number. The basic IP protocol does not supply port numbers, they are implemented by higher level protocols like udp(7) and tcp(7). On raw sockets sin_port is set to the IP protocol.

struct sockaddr_in {
    sa_family_t    sin_family; /* address family: AF_INET */
    u_int16_t      sin_port;   /* port in network byte order */
    struct in_addr sin_addr;   /* internet address */
};

/* Internet address. */
struct in_addr {
    u_int32_t      s_addr;     /* address in network byte order */
};

sin_family is always set to AF_INET. This is required; in Linux 2.2 most networking functions return EINVAL when this setting is missing. sin_port contains the port in network byte order. The port numbers below 1024 are called reserved ports. Only privileged processes (i.e., those having the CAP_NET_BIND_SERVICE capability) may bind(2) to these sockets. Note that the raw IPv4 protocol as such has no concept of a port, they are only implemented by higher protocols like tcp(7) and udp(7).

sin_addr is the IP host address. The s_addr member of struct in_addr contains the host interface address in network byte order. in_addr should be assigned one of the INADDR_* values (e.g., INADDR_ANY) or set using the inet_aton(3), inet_addr(3), inet_makeaddr(3) library functions or directly with the name resolver (see gethostbyname(3)). IPv4 addresses are divided into unicast, broadcast and multicast addresses. Unicast addresses specify a single interface of a host, broadcast addresses specify all hosts on a network and multicast addresses address all hosts in a multicast group. Datagrams to broadcast addresses can be only sent or received when the SO_BROADCAST socket flag is set. In the current implementation connection oriented sockets are only allowed to use unicast addresses.

Note that the address and the port are always stored in network byte order. In particular, this means that you need to call htons(3) on the number that is assigned to a port. All address/port manipulation functions in the standard library work in network byte order.

There are several special addresses: INADDR_LOOPBACK (127.0.0.1) always refers to the local host via the loopback device; INADDR_ANY (0.0.0.0) means any address for binding; INADDR_BROADCAST (255.255.255.255) means any host and has the same effect on bind as INADDR_ANY for historical reasons.

Socket Options

IP supports some protocol specific socket options that can be set with setsockopt(2) and read with getsockopt(2). The socket option level for IP is IPPROTO_IP. A boolean integer flag is zero when it is false, otherwise true.
IP_OPTIONS
Sets or get the IP options to be sent with every packet from this socket. The arguments are a pointer to a memory buffer containing the options and the option length. The setsockopt(2) call sets the IP options associated with a socket. The maximum option size for IPv4 is 40 bytes. See RFC 791 for the allowed options. When the initial connection request packet for a SOCK_STREAM socket contains IP options, the IP options will be set automatically to the options from the initial packet with routing headers reversed. Incoming packets are not allowed to change options after the connection is established. The processing of all incoming source routing options is disabled by default and can be enabled by using the accept_source_route sysctl. Other options like timestamps are still handled. For datagram sockets, IP options can be only set by the local user. Calling getsockopt(2) with IP_OPTIONS puts the current IP options used for sending into the supplied buffer.
IP_PKTINFO
Pass an IP_PKTINFO ancillary message that contains a pktinfo structure that supplies some information about the incoming packet. This only works for datagram oriented sockets. The argument is a flag that tells the socket whether the IP_PKTINFO message should be passed or not. The message itself can only be sent/retrieved as control message with a packet using recvmsg(2) or sendmsg(2).
struct in_pktinfo {
    unsigned int   ipi_ifindex;  /* Interface index */
    struct in_addr ipi_spec_dst; /* Local address */
    struct in_addr ipi_addr;     /* Header Destination
                                    address */
};
ipi_ifindex is the unique index of the interface the packet was received on. ipi_spec_dst is the local address of the packet and ipi_addr is the destination address in the packet header. If IP_PKTINFO is passed to sendmsg(2) and ipi_spec_dst is not zero, then it is used as the local source address for the routing table lookup and for setting up IP source route options. When ipi_ifindex is not zero the primary local address of the interface specified by the index overwrites ipi_spec_dst for the routing table lookup.
IP_RECVTOS
If enabled the IP_TOS ancillary message is passed with incoming packets. It contains a byte which specifies the Type of Service/Precedence field of the packet header. Expects a boolean integer flag.
IP_RECVTTL
When this flag is set pass a IP_TTL control message with the time to live field of the received packet as a byte. Not supported for SOCK_STREAM sockets.
IP_RECVOPTS
Pass all incoming IP options to the user in a IP_OPTIONS control message. The routing header and other options are already filled in for the local host. Not supported for SOCK_STREAM sockets.
IP_RETOPTS
Identical to IP_RECVOPTS but returns raw unprocessed options with timestamp and route record options not filled in for this hop.
IP_TOS
Set or receive the Type-Of-Service (TOS) field that is sent with every IP packet originating from this socket. It is used to prioritize packets on the network. TOS is a byte. There are some standard TOS flags defined: IPTOS_LOWDELAY to minimize delays for interactive traffic, IPTOS_THROUGHPUT to optimize throughput, IPTOS_RELIABILITY to optimize for reliability, IPTOS_MINCOST should be used for "filler data" where slow transmission doesn't matter. At most one of these TOS values can be specified. Other bits are invalid and shall be cleared. Linux sends IPTOS_LOWDELAY datagrams first by default, but the exact behavior depends on the configured queueing discipline. Some high priority levels may require superuser privileges (the CAP_NET_ADMIN capability). The priority can also be set in a protocol independent way by the (SOL_SOCKET, SO_PRIORITY) socket option (see socket(7)).
IP_TTL
Set or retrieve the current time to live field that is used in every packet sent from this socket.
IP_HDRINCL
If enabled the user supplies an IP header in front of the user data. Only valid for SOCK_RAW sockets. See raw(7) for more information. When this flag is enabled the values set by IP_OPTIONS, IP_TTL and IP_TOS are ignored.
IP_RECVERR (defined in <linux/errqueue.h>)
Enable extended reliable error message passing. When enabled on a datagram socket all generated errors will be queued in a per-socket error queue. When the user receives an error from a socket operation the errors can be received by calling recvmsg(2) with the MSG_ERRQUEUE flag set. The sock_extended_err structure describing the error will be passed in a ancillary message with the type IP_RECVERR and the level IPPROTO_IP. This is useful for reliable error handling on unconnected sockets. The received data portion of the error queue contains the error packet.
The IP_RECVERR control message contains a sock_extended_err structure:
#define SO_EE_ORIGIN_NONE    0
#define SO_EE_ORIGIN_LOCAL   1
#define SO_EE_ORIGIN_ICMP    2
#define SO_EE_ORIGIN_ICMP6   3

struct sock_extended_err {
    u_int32_t ee_errno;   /* error number */
    u_int8_t  ee_origin;  /* where the error originated */
    u_int8_t  ee_type;    /* type */
    u_int8_t  ee_code;    /* code */
    u_int8_t  ee_pad;
    u_int32_t ee_info;    /* additional information */
    u_int32_t ee_data;    /* other data */
    /* More data may follow */
};

struct sockaddr *SO_EE_OFFENDER(struct sock_extended_err *);
ee_errno contains the errno number of the queued error. ee_origin is the origin code of where the error originated. The other fields are protocol specific. The macro SO_EE_OFFENDER returns a pointer to the address of the network object where the error originated from given a pointer to the ancillary message. If this address is not known, the sa_family member of the sockaddr contains AF_UNSPEC and the other fields of the sockaddr are undefined.
IP uses the sock_extended_err structure as follows: ee_origin is set to SO_EE_ORIGIN_ICMP for errors received as an ICMP packet, or SO_EE_ORIGIN_LOCAL for locally generated errors. Unknown values should be ignored. ee_type and ee_code are set from the type and code fields of the ICMP header. ee_info contains the discovered MTU for EMSGSIZE errors. The message also contains the sockaddr_in of the node caused the error, which can be accessed with the SO_EE_OFFENDER macro. The sin_family field of the SO_EE_OFFENDER address is AF_UNSPEC when the source was unknown. When the error originated from the network, all IP options (IP_OPTIONS, IP_TTL, etc.) enabled on the socket and contained in the error packet are passed as control messages. The payload of the packet causing the error is returned as normal payload. Note that TCP has no error queue; MSG_ERRQUEUE is illegal on SOCK_STREAM sockets. IP_RECVERR is valid for TCP, but all errors are returned by socket function return or SO_ERROR only.
For raw sockets, IP_RECVERR enables passing of all received ICMP errors to the application, otherwise errors are only reported on connected sockets
It sets or retrieves an integer boolean flag. IP_RECVERR defaults to off.
IP_MTU_DISCOVER
Sets or receives the Path MTU Discovery setting for a socket. When enabled, Linux will perform Path MTU Discovery as defined in RFC 1191 on this socket. The don't fragment flag is set on all outgoing datagrams. The system-wide default is controlled by the ip_no_pmtu_disc sysctl for SOCK_STREAM sockets, and disabled on all others. For non SOCK_STREAM sockets it is the user's responsibility to packetize the data in MTU sized chunks and to do the retransmits if necessary. The kernel will reject packets that are bigger than the known path MTU if this flag is set (with EMSGSIZE ).
Path MTU discovery flags Meaning
IP_PMTUDISC_WANT Use per-route settings.
IP_PMTUDISC_DONT Never do Path MTU Discovery.
IP_PMTUDISC_DO Always do Path MTU Discovery.
IP_PMTUDISC_PROBE Set DF but ignore Path MTU.

When PMTU discovery is enabled the kernel automatically keeps track of the path MTU per destination host. When it is connected to a specific peer with connect(2) the currently known path MTU can be retrieved conveniently using the IP_MTU socket option (e.g., after a EMSGSIZE error occurred). It may change over time. For connectionless sockets with many destinations the new also MTU for a given destination can also be accessed using the error queue (see IP_RECVERR). A new error will be queued for every incoming MTU update.

While MTU discovery is in progress initial packets from datagram sockets may be dropped. Applications using UDP should be aware of this and not take it into account for their packet retransmit strategy.

To bootstrap the path MTU discovery process on unconnected sockets it is possible to start with a big datagram size (up to 64K-headers bytes long) and let it shrink by updates of the path MTU.

To get an initial estimate of the path MTU connect a datagram socket to the destination address using connect(2) and retrieve the MTU by calling getsockopt(2) with the IP_MTU option.

It is possible to implement RFC 4821 MTU probing with SOCK_DGRAM of SOCK_RAW sockets by setting a value of IP_PMTUDISC_PROBE. This is also particularly useful for diagnostic tools such as tracepath(8) that wish to deliberately send probe packets larger than the observed Path MTU.

IP_MTU
Retrieve the current known path MTU of the current socket. Only valid when the socket has been connected. Returns an integer. Only valid as a getsockopt(2).
IP_ROUTER_ALERT
Pass all to-be forwarded packets with the IP Router Alert option set to this socket. Only valid for raw sockets. This is useful, for instance, for user space RSVP daemons. The tapped packets are not forwarded by the kernel, it is the users responsibility to send them out again. Socket binding is ignored, such packets are only filtered by protocol. Expects an integer flag.
IP_MULTICAST_TTL
Set or reads the time-to-live value of outgoing multicast packets for this socket. It is very important for multicast packets to set the smallest TTL possible. The default is 1 which means that multicast packets don't leave the local network unless the user program explicitly requests it. Argument is an integer.
IP_MULTICAST_LOOP
Sets or reads a boolean integer argument whether sent multicast packets should be looped back to the local sockets.
IP_ADD_MEMBERSHIP
Join a multicast group. Argument is an ip_mreqn structure.

struct ip_mreqn {
    struct in_addr imr_multiaddr; /* IP multicast group
                                     address */
    struct in_addr imr_address;   /* IP address of local
                                     interface */
    int            imr_ifindex;   /* interface index */
};

imr_multiaddr contains the address of the multicast group the application wants to join or leave. It must be a valid multicast address. imr_address is the address of the local interface with which the system should join the multicast group; if it is equal to INADDR_ANY an appropriate interface is chosen by the system. imr_ifindex is the interface index of the interface that should join/leave the imr_multiaddr group, or 0 to indicate any interface.

For compatibility, the old ip_mreq structure is still supported. It differs from ip_mreqn only by not including the imr_ifindex field. Only valid as a setsockopt(2).
IP_DROP_MEMBERSHIP
Leave a multicast group. Argument is an ip_mreqn or ip_mreq structure similar to IP_ADD_MEMBERSHIP.
IP_MULTICAST_IF
Set the local device for a multicast socket. Argument is an ip_mreqn or ip_mreq structure similar to IP_ADD_MEMBERSHIP.
When an invalid socket option is passed, ENOPROTOOPT is returned.

Sysctls

The IP protocol supports the sysctl interface to configure some global options. The sysctls can be accessed by reading or writing the /proc/sys/net/ipv4/* files or using the sysctl(2) interface. Variables described as Boolean take an integer value, with a non-zero value ("true") meaning that the corresponding option is enabled, and a zero value ("false") meaning that the option is disabled.
ip_always_defrag (Boolean)
[New with kernel 2.2.13; in earlier kernel version the feature was controlled at compile time by the CONFIG_IP_ALWAYS_DEFRAG option; this file is not present in 2.4.x and later]

When this boolean frag is enabled (not equal 0) incoming fragments (parts of IP packets that arose when some host between origin and destination decided that the packets were too large and cut them into pieces) will be reassembled (defragmented) before being processed, even if they are about to be forwarded.

Only enable if running either a firewall that is the sole link to your network or a transparent proxy; never ever turn on here for a normal router or host. Otherwise fragmented communication may me disturbed when the fragments would travel over different links. Defragmentation also has a large memory and CPU time cost.

This is automagically turned on when masquerading or transparent proxying are configured.

ip_autoconfig
Not documented.
ip_default_ttl (integer; default: 64)
Set the default time-to-live value of outgoing packets. This can be changed per socket with the IP_TTL option.
ip_dynaddr (Boolean; default: disabled)
Enable dynamic socket address and masquerading entry rewriting on interface address change. This is useful for dialup interface with changing IP addresses. 0 means no rewriting, 1 turns it on and 2 enables verbose mode.
ip_forward (Boolean; default: disabled)
Enable IP forwarding with a boolean flag. IP forwarding can be also set on a per interface basis.
ip_local_port_range
Contains two integers that define the default local port range allocated to sockets. Allocation starts with the first number and ends with the second number. Note that these should not conflict with the ports used by masquerading (although the case is handled). Also arbitrary choices may cause problems with some firewall packet filters that make assumptions about the local ports in use. First number should be at least >1024, better >4096 to avoid clashes with well known ports and to minimize firewall problems.
ip_no_pmtu_disc (Boolean; default: disabled)
If enabled, don't do Path MTU Discovery for TCP sockets by default. Path MTU discovery may fail if misconfigured firewalls (that drop all ICMP packets) or misconfigured interfaces (e.g., a point-to-point link where the both ends don't agree on the MTU) are on the path. It is better to fix the broken routers on the path than to turn off Path MTU Discovery globally, because not doing it incurs a high cost to the network.
ip_nonlocal_bind (Boolean; default: disabled)
If set, allows processes to bind(2) to non-local IP addresses, which can be quite useful, but may break some applications.
ip6frag_time (integer; default 30)
Time in seconds to keep an IPv6 fragment in memory.
ip6frag_secret_interval (integer; default 600)
Regeneration interval (in seconds) of the hash secret (or lifetime for the hash secret) for IPv6 fragments.
ipfrag_high_thresh (integer), ipfrag_low_thresh (integer)
If the amount of queued IP fragments reaches ipfrag_high_thresh, the queue is pruned down to ipfrag_low_thresh. Contains an integer with the number of bytes.
neigh/*
See arp(7).

Ioctls

All ioctls described in socket(7) apply to ip.

Ioctls to configure generic device parameters are described in netdevice(7).

ERRORS

ENOTCONN
The operation is only defined on a connected socket, but the socket wasn't connected.
EINVAL
Invalid argument passed. For send operations this can be caused by sending to a blackhole route.
EMSGSIZE
Datagram is bigger than an MTU on the path and it cannot be fragmented.
EACCES
The user tried to execute an operation without the necessary permissions. These include: sending a packet to a broadcast address without having the SO_BROADCAST flag set; sending a packet via a prohibit route; modifying firewall settings without superuser privileges (the CAP_NET_ADMIN capability); binding to a reserved port without superuser privileges (the CAP_NET_BIND_SERVICE capability).
EADDRINUSE
Tried to bind to an address already in use.
ENOPROTOOPT and EOPNOTSUPP
Invalid socket option passed.
EPERM
User doesn't have permission to set high priority, change configuration, or send signals to the requested process or group.
EADDRNOTAVAIL
A non-existent interface was requested or the requested source address was not local.
EAGAIN
Operation on a non-blocking socket would block.
ESOCKTNOSUPPORT
The socket is not configured or an unknown socket type was requested.
EISCONN
connect(2) was called on an already connected socket.
EALREADY
An connection operation on a non-blocking socket is already in progress.
ECONNABORTED
A connection was closed during an accept(2).
EPIPE
The connection was unexpectedly closed or shut down by the other end.
ENOENT
SIOCGSTAMP was called on a socket where no packet arrived.
EHOSTUNREACH
No valid routing table entry matches the destination address. This error can be caused by a ICMP message from a remote router or for the local routing table.
ENODEV
Network device not available or not capable of sending IP.
ENOPKG
A kernel subsystem was not configured.
ENOBUFS, ENOMEM
Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory, but this is not 100% consistent.

Other errors may be generated by the overlaying protocols; see
tcp(7),

raw(7),

udp(7)

and
socket(7).

VERSIONS

IP_MTU, IP_MTU_DISCOVER, IP_PKTINFO, IP_RECVERR and IP_ROUTER_ALERT are new options in Linux 2.2. They are also all Linux specific and should not be used in programs intended to be portable.

IP_PMTUDISC_PROBE is new in Linux 2.6.22.

struct ip_mreqn is new in Linux 2.2. Linux 2.0 only supported ip_mreq.

The sysctls were introduced with Linux 2.2.

NOTES

Be very careful with the SO_BROADCAST option - it is not privileged in Linux. It is easy to overload the network with careless broadcasts. For new application protocols it is better to use a multicast group instead of broadcasting. Broadcasting is discouraged.

Some other BSD sockets implementations provide IP_RCVDSTADDR and IP_RECVIF socket options to get the destination address and the interface of received datagrams. Linux has the more general IP_PKTINFO for the same task.

Some BSD sockets implementations also provide an IP_RECVTTL option, but an ancillary message with type IP_RECVTTL is passed with the incoming packet. This is different from the IP_TTL option used in Linux.

Using SOL_IP socket options level isn't portable, BSD-based stacks use IPPROTO_IP level.

Compatibility

For compatibility with Linux 2.0, the obsolete socket(PF_INET, SOCK_PACKET, protocol) syntax is still supported to open a packet(7) socket. This is deprecated and should be replaced by socket(PF_PACKET, SOCK_RAW, protocol) instead. The main difference is the new sockaddr_ll address structure for generic link layer information instead of the old sockaddr_pkt.

BUGS

There are too many inconsistent error values.

The ioctls to configure IP-specific interface options and ARP tables are not described.

Some versions of glibc forget to declare in_pktinfo. Workaround currently is to copy it into your program from this man page.

Receiving the original destination address with MSG_ERRQUEUE in msg_name by recvmsg(2) does not work in some 2.2 kernels.

SEE ALSO

recvmsg(2), sendmsg(2), byteorder(3), ipfw(4), capabilities(7), netlink(7), raw(7), socket(7), tcp(7), udp(7)

RFC 791 for the original IP specification.
RFC 1122 for the IPv4 host requirements.
RFC 1812 for the IPv4 router requirements.


raw(7)

RAW

Section: Linux Programmer's Manual (7)
Updated: 1998-10-02 Return to Main Contents

NAME

raw, SOCK_RAW - Linux IPv4 raw sockets

SYNOPSIS

#include <sys/socket.h>
#include <netinet/in.h>
raw_socket = socket(PF_INET, SOCK_RAW, int protocol);

DESCRIPTION

Raw sockets allow new IPv4 protocols to be implemented in user space. A raw socket receives or sends the raw datagram not including link level headers.

The IPv4 layer generates an IP header when sending a packet unless the IP_HDRINCL socket option is enabled on the socket. When it is enabled, the packet must contain an IP header. For receiving the IP header is always included in the packet.

Only processes with an effective user ID of 0 or the CAP_NET_RAW capability are allowed to open raw sockets.

All packets or errors matching the protocol number specified for the raw socket are passed to this socket. For a list of the allowed protocols see RFC 1700 assigned numbers and getprotobyname(3).

A protocol of IPPROTO_RAW implies enabled IP_HDRINCL and is able to send any IP protocol that is specified in the passed header. Receiving of all IP protocols via IPPROTO_RAW is not possible using raw sockets.

IP Header fields modified on sending by IP_HDRINCL
IP Checksum Always filled in.
Source Address Filled in when zero.
Packet Id Filled in when zero.
Total Length Always filled in.

If IP_HDRINCL is specified and the IP header has a non-zero destination address then the destination address of the socket is used to route the packet. When MSG_DONTROUTE is specified the destination address should refer to a local interface, otherwise a routing table lookup is done anyway but gatewayed routes are ignored.

If IP_HDRINCL isn't set then IP header options can be set on raw sockets with setsockopt(2); see ip(7) for more information.

In Linux 2.2 all IP header fields and options can be set using IP socket options. This means raw sockets are usually only needed for new protocols or protocols with no user interface (like ICMP).

When a packet is received, it is passed to any raw sockets which have been bound to its protocol before it is passed to other protocol handlers (e.g., kernel protocol modules).

Address Format

Raw sockets use the standard sockaddr_in address structure defined in ip(7). The sin_port field could be used to specify the IP protocol number, but it is ignored for sending in Linux 2.2 and should be always set to 0 (see BUGS) For incoming packets sin_port is set to the protocol of the packet. See the <netinet/in.h> include file for valid IP protocols.

Socket Options

Raw socket options can be set with setsockopt(2) and read with getsockopt(2) by passing the IPPROTO_RAW family flag.
ICMP_FILTER
Enable a special filter for raw sockets bound to the IPPROTO_ICMP protocol. The value has a bit set for each ICMP message type which should be filtered out. The default is to filter no ICMP messages.

In addition all ip(7) IPPROTO_IP socket options valid for datagram sockets are supported.

Error Handling

Errors originating from the network are only passed to the user when the socket is connected or the IP_RECVERR flag is enabled. For connected sockets only EMSGSIZE and EPROTO are passed for compatibility. With IP_RECVERR all network errors are saved in the error queue.

ERRORS

EMSGSIZE
Packet too big. Either Path MTU Discovery is enabled (the IP_MTU_DISCOVER socket flag) or the packet size exceeds the maximum allowed IPv4 packet size of 64KB.
EACCES
User tried to send to a broadcast address without having the broadcast flag set on the socket.
EPROTO
An ICMP error has arrived reporting a parameter problem.
EFAULT
An invalid memory address was supplied.
EOPNOTSUPP
Invalid flag has been passed to a socket call (like MSG_OOB).
EINVAL
Invalid argument.
EPERM
The user doesn't have permission to open raw sockets. Only processes with a effective user ID of 0 or the CAP_NET_RAW attribute may do that.

VERSIONS

IP_RECVERR and ICMP_FILTER are new in Linux 2.2. They are Linux extensions and should not be used in portable programs.

Linux 2.0 enabled some bug-to-bug compatibility with BSD in the raw socket code when the SO_BSDCOMPAT socket option was set --- since Linux 2.2, this option no longer has that effect.

NOTES

By default raw sockets do path MTU (Maximum Transmission Unit) discovery. This means the kernel will keep track of the MTU to a specific target IP address and return EMSGSIZE when a raw packet write exceeds it. When this happens the application should decrease the packet size. Path MTU discovery can be also turned off using the IP_MTU_DISCOVER socket option or the ip_no_pmtu_disc sysctl, see ip(7) for details. When turned off raw sockets will fragment outgoing packets that exceed the interface MTU. However disabling it is not recommended for performance and reliability reasons.

A raw socket can be bound to a specific local address using the bind(2) call. If it isn't bound all packets with the specified IP protocol are received. In addition a RAW socket can be bound to a specific network device using SO_BINDTODEVICE; see socket(7).

An IPPROTO_RAW socket is send only. If you really want to receive all IP packets use a packet(7) socket with the ETH_P_IP protocol. Note that packet sockets don't reassemble IP fragments, unlike raw sockets.

If you want to receive all ICMP packets for a datagram socket it is often better to use IP_RECVERR on that particular socket; see ip(7).

Raw sockets may tap all IP protocols in Linux, even protocols like ICMP or TCP which have a protocol module in the kernel. In this case the packets are passed to both the kernel module and the raw socket(s). This should not be relied upon in portable programs, many other BSD socket implementation have limitations here.

Linux never changes headers passed from the user (except for filling in some zeroed fields as described for IP_HDRINCL). This differs from many other implementations of raw sockets.

RAW sockets are generally rather unportable and should be avoided in programs intended to be portable.

Sending on raw sockets should take the IP protocol from sin_port; this ability was lost in Linux 2.2. The workaround is to use IP_HDRINCL.

BUGS

Transparent proxy extensions are not described.

When the IP_HDRINCL option is set datagrams will not be fragmented and are limited to the interface MTU.

Setting the IP protocol for sending in sin_port got lost in Linux 2.2. The protocol that the socket was bound to or that was specified in the initial socket(2) call is always used.

SEE ALSO

recvmsg(2), sendmsg(2), capabilities(7), ip(7), socket(7)

RFC 1191 for path MTU discovery.

RFC 791 and the <linux/ip.h> include file for the IP protocol.


x25(7)

X25

Section: Linux Programmer's Manual (7)
Updated: 1998-12-01 Return to Main Contents

NAME

x25, PF_X25 - ITU-T X.25 / ISO-8208 protocol interface.

SYNOPSIS

#include <sys/socket.h>
#include <linux/x25.h>

x25_socket = socket(PF_X25, SOCK_SEQPACKET, 0);

DESCRIPTION

X25 sockets provide an interface to the X.25 packet layer protocol. This allows applications to communicate over a public X.25 data network as standardized by International Telecommunication Union's recommendation X.25 (X.25 DTE-DCE mode). X25 sockets can also be used for communication without an intermediate X.25 network (X.25 DTE-DTE mode) as described in ISO-8208.

Message boundaries are preserved --- a read(2) from a socket will retrieve the same chunk of data as output with the corresponding write(2) to the peer socket. When necessary, the kernel takes care of segmenting and re-assembling long messages by means of the X.25 M-bit. There is no hard-coded upper limit for the message size. However, re-assembling of a long message might fail if there is a temporary lack of system resources or when other constraints (such as socket memory or buffer size limits) become effective. If that occurs, the X.25 connection will be reset.

Socket Addresses

The AF_X25 socket address family uses the struct sockaddr_x25 for representing network addresses as defined in ITU-T recommendation X.121.

struct sockaddr_x25 {
    sa_family_t sx25_family;    /* must be AF_X25 */
    x25_address sx25_addr;      /* X.121 Address */
};

sx25_addr contains a char array x25_addr[] to be interpreted as a null-terminated string. sx25_addr.x25_addr[] consists of up to 15 (not counting the terminating 0) ASCII characters forming the X.121 address. Only the decimal digit characters from `0' to `9' are allowed.

Socket Options

The following X.25 specific socket options can be set by using setsockopt(2) and read with getsockopt(2) with the level parameter set to SOL_X25.
X25_QBITINCL
Controls whether the X.25 Q-bit (Qualified Data Bit) is accessible by the user. It expects an integer argument. If set to 0 (default), the Q-bit is never set for outgoing packets and the Q-bit of incoming packets is ignored. If set to 1, an additional first byte is prepended to each message read from or written to the socket. For data read from the socket, a 0 first byte indicates that the Q-bits of the corresponding incoming data packets were not set. A first byte with value 1 indicates that the Q-bit of the corresponding incoming data packets was set. If the first byte of the data written to the socket is 1 the Q-bit of the corresponding outgoing data packets will be set. If the first byte is 0 the Q-bit will not be set.

VERSIONS

The PF_X25 protocol family is a new feature of Linux 2.2.

BUGS

Plenty, as the X.25 PLP implementation is CONFIG_EXPERIMENTAL.

This man page is incomplete.

There is no dedicated application programmer's header file yet; you need to include the kernel header file <linux/x25.h>. CONFIG_EXPERIMENTAL might also imply that future versions of the interface are not binary compatible.

X.25 N-Reset events are not propagated to the user process yet. Thus, if a reset occurred, data might be lost without notice.

SEE ALSO

socket(2), socket(7)

Jonathan Simon Naylor: "The Re-Analysis and Re-Implementation of X.25." The URL is

ftp://ftp.pspt.fi/pub/ham/linux/ax25/x25doc.tgz


socket(7)

SOCKET

Section: Linux Programmer's Manual (7)
Updated: 2004-05-27 Return to Main Contents

NAME

socket - Linux socket interface

SYNOPSIS

#include <sys/socket.h>
mysocket = socket(int socket_family, int socket_type, int protocol);

DESCRIPTION

This manual page describes the Linux networking socket layer user interface. The BSD compatible sockets are the uniform interface between the user process and the network protocol stacks in the kernel. The protocol modules are grouped into protocol families like PF_INET, PF_IPX, PF_PACKET and socket types like SOCK_STREAM or SOCK_DGRAM. See socket(2) for more information on families and types.

Socket Layer Functions

These functions are used by the user process to send or receive packets and to do other socket operations. For more information see their respective manual pages.

socket(2) creates a socket, connect(2) connects a socket to a remote socket address, the bind(2) function binds a socket to a local socket address, listen(2) tells the socket that new connections shall be accepted, and accept(2) is used to get a new socket with a new incoming connection. socketpair(2) returns two connected anonymous sockets (only implemented for a few local families like PF_UNIX)

send(2),

sendto(2),

and
sendmsg(2)

send data over a socket, and
recv(2),

recvfrom(2),

recvmsg(2)

receive data from a socket.
poll(2)

and
select(2)

wait for arriving data or a readiness to send data.
In addition, the standard I/O operations like
write(2),

writev(2),

sendfile(2),

read(2),

and
readv(2)

can be used to read and write data.

getsockname(2) returns the local socket address and getpeername(2) returns the remote socket address. getsockopt(2) and setsockopt(2) are used to set or get socket layer or protocol options. ioctl(2) can be used to set or read some other options.

close(2) is used to close a socket. shutdown(2) closes parts of a full duplex socket connection.

Seeking, or calling pread(2) or pwrite(2) with a non-zero position is not supported on sockets.

It is possible to do non-blocking I/O on sockets by setting the O_NONBLOCK flag on a socket file descriptor using fcntl(2). Then all operations that would block will (usually) return with EAGAIN (operation should be retried later); connect(2) will return EINPROGRESS error. The user can then wait for various events via poll(2) or select(2).
I/O events
Event | Poll flag | Occurrence
Read | POLLIN | New data arrived.
Read | POLLIN | A connection setup has been completed (for connection-oriented sockets)
Read | POLLHUP | A disconnection request has been initiated by the other end.
Read | POLLHUP | A connection is broken (only for connection-oriented protocols). When the socket is written SIGPIPE is also sent.
Write | POLLOUT | Socket has enough send buffer space for writing new data.
Read/Write | POLLIN| POLLOUT | An outgoing connect(2) finished.
Read/Write | POLLERR | An asynchronous error occurred.
Read/Write | POLLHUP | The other end has shut down one direction.
Exception | POLLPRI | Urgent data arrived. SIGURG is sent then.

An alternative to poll(2) and select(2) is to let the kernel inform the application about events via a SIGIO signal. For that the FASYNC flag must be set on a socket file descriptor via fcntl(2) and a valid signal handler for SIGIO must be installed via sigaction(2). See the SIGNALS discussion below.

Socket Options

These socket options can be set by using setsockopt(2) and read with getsockopt(2) with the socket level set to SOL_SOCKET for all sockets:
SO_ACCEPTCONN
Returns a value indicating whether or not this socket has been marked to accept connections with listen(2). The value 0 indicates that this is not a listening socket, the value 1 indicates that this is a listening socket. Can only be read with getsockopt(2).
SO_BINDTODEVICE
Bind this socket to a particular device like "eth0", as specified in the passed interface name. If the name is an empty string or the option length is zero, the socket device binding is removed. The passed option is a variable-length null terminated interface name string with the maximum size of IFNAMSIZ. If a socket is bound to an interface, only packets received from that particular interface are processed by the socket. Note that this only works for some socket types, particularly AF_INET sockets. It is not supported for packet sockets (use normal bind(8) there).
SO_BROADCAST
Set or get the broadcast flag. When enabled, datagram sockets receive packets sent to a broadcast address and they are allowed to send packets to a broadcast address. This option has no effect on stream-oriented sockets.
SO_BSDCOMPAT
Enable BSD bug-to-bug compatibility. This is used by the UDP protocol module in Linux 2.0 and 2.2. If enabled ICMP errors received for a UDP socket will not be passed to the user program. In later kernel versions, support for this option has been phased out: Linux 2.4 silently ignores it, and Linux 2.6 generates a kernel warning (printk()) if a program uses this option. Linux 2.0 also enabled BSD bug-to-bug compatibility options (random header changing, skipping of the broadcast flag) for raw sockets with this option, but that was removed in Linux 2.2.
SO_DEBUG
Enable socket debugging. Only allowed for processes with the CAP_NET_ADMIN capability or an effective user ID of 0.
SO_ERROR
Get and clear the pending socket error. Only valid as a getsockopt(2). Expects an integer.
SO_DONTROUTE
Don't send via a gateway, only send to directly connected hosts. The same effect can be achieved by setting the MSG_DONTROUTE flag on a socket send(2) operation. Expects an integer boolean flag.
SO_KEEPALIVE
Enable sending of keep-alive messages on connection-oriented sockets. Expects an integer boolean flag.
SO_LINGER
Sets or gets the SO_LINGER option. The argument is a linger structure.

struct linger {
    int l_onoff;    /* linger active */
    int l_linger;   /* how many seconds to linger for */
};
When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. When the socket is closed as part of exit(2), it always lingers in the background.
SO_OOBINLINE
If this option is enabled, out-of-band data is directly placed into the receive data stream. Otherwise out-of-band data is only passed when the MSG_OOB flag is set during receiving.
SO_PASSCRED
Enable or disable the receiving of the SCM_CREDENTIALS control message. For more information see unix(7).
SO_PEERCRED
Return the credentials of the foreign process connected to this socket. This is only possible for connected PF_UNIX stream sockets and PF_UNIX stream and datagram socket pairs created using socketpair(2); see unix(7). The returned credentials are those that were in effect at the time of the call to connect(2) or socketpair(2). Argument is a ucred structure. Only valid as a getsockopt(2).
SO_PRIORITY
Set the protocol-defined priority for all packets to be sent on this socket. Linux uses this value to order the networking queues: packets with a higher priority may be processed first depending on the selected device queueing discipline. For ip(7), this also sets the IP type-of-service (TOS) field for outgoing packets. Setting a priority outside the range 0 to 6 requires the CAP_NET_ADMIN capability.
SO_RCVBUF
Sets or gets the maximum socket receive buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead) when it is set using setsockopt(2), and this doubled value is returned by getsockopt(2). The default value is set by the rmem_default sysctl and the maximum allowed value is set by the rmem_max sysctl. The minimum (doubled) value for this option is 256.
SO_RCVBUFFORCE (since Linux 2.6.14)
Using this socket option, a privileged (CAP_NET_ADMIN) process can perform the same task as SO_RCVBUF, but the rmem_max limit can be overridden.
SO_RCVLOWAT and SO_SNDLOWAT
Specify the minimum number of bytes in the buffer until the socket layer will pass the data to the protocol (SO_SNDLOWAT) or the user on receiving (SO_RCVLOWAT). These two values are initialized to 1. SO_SNDLOWAT is not changeable on Linux (setsockopt fails with the error ENOPROTOOPT). SO_RCVLOWAT is changeable only since Linux 2.4. The select(2) and poll(2) system calls currently do not respect the SO_RCVLOWAT setting on Linux, and mark a socket readable when even a single byte of data is available. A subsequent read from the socket will block until SO_RCVLOWAT bytes are available.
SO_RCVTIMEO and SO_SNDTIMEO
Specify the receiving or sending timeouts until reporting an error. The parameter is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK just as if the socket was specified to be nonblocking. If the timeout is set to zero (the default) then the operation will never timeout.
SO_REUSEADDR
Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. For PF_INET sockets this means that a socket may bind, except when there is an active listening socket bound to the address. When the listening socket is bound to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address.
SO_SNDBUF
Sets or gets the maximum socket send buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead) when it is set using setsockopt(2), and this doubled value is returned by getsockopt(2). The default value is set by the wmem_default sysctl and the maximum allowed value is set by the wmem_max sysctl. The minimum (doubled) value for this option is 2048.
SO_SNDBUFFORCE (since Linux 2.6.14)
Using this socket option, a privileged (CAP_NET_ADMIN) process can perform the same task as SO_SNDBUF, but the wmem_max limit can be overridden.
SO_TIMESTAMP
Enable or disable the receiving of the SO_TIMESTAMP control message. The timestamp control message is sent with level SOL_SOCKET and the cmsg_data field is a struct timeval indicating the reception time of the last packet passed to the user in this call. See cmsg(3) for details on control messages.
SO_TYPE
Gets the socket type as an integer (like SOCK_STREAM). Can only be read with getsockopt(2).

Signals

When writing onto a connection-oriented socket that has been shut down (by the local or the remote end) SIGPIPE is sent to the writing process and EPIPE is returned. The signal is not sent when the write call specified the MSG_NOSIGNAL flag.

When requested with the FIOSETOWN fcntl(2) or SIOCSPGRP ioctl(2), SIGIO is sent when an I/O event occurs. It is possible to use poll(2) or select(2) in the signal handler to find out which socket the event occurred on. An alternative (in Linux 2.2) is to set a realtime signal using the F_SETSIG fcntl(2); the handler of the real time signal will be called with the file descriptor in the si_fd field of its siginfo_t. See fcntl(2) for more information.

Under some circumstances (e.g., multiple processes accessing a single socket), the condition that caused the SIGIO may have already disappeared when the process reacts to the signal. If this happens, the process should wait again because Linux will resend the signal later.

Sysctls

The core socket networking sysctls can be accessed using the /proc/sys/net/core/* files or with the sysctl(2) interface.
rmem_default
contains the default setting in bytes of the socket receive buffer.
rmem_max
contains the maximum socket receive buffer size in bytes which a user may set by using the SO_RCVBUF socket option.
wmem_default
contains the default setting in bytes of the socket send buffer.
wmem_max
contains the maximum socket send buffer size in bytes which a user may set by using the SO_SNDBUF socket option.
message_cost and message_burst
configure the token bucket filter used to load limit warning messages caused by external network events.
netdev_max_backlog
Maximum number of packets in the global input queue.
optmem_max
Maximum length of ancillary data and user control data like the iovecs per socket.

Ioctls

These operations can be accessed using ioctl(2):

error = ioctl(ip_socket, ioctl_type, &value_result);
SIOCGSTAMP
Return a struct timeval with the receive timestamp of the last packet passed to the user. This is useful for accurate round trip time measurements. See setitimer(2) for a description of struct timeval. This ioctl should only be used if the socket option SO_TIMESTAMP is not set on the socket. Otherwise, it returns the timestamp of the last packet that was received while SO_TIMESTAMP was not set, or it fails if no such packet has been received, (i.e., ioctl(2) returns -1 with errno set to ENOENT).
SIOCSPGRP
Set the process or process group to send SIGIO or SIGURG signals to when an asynchronous I/O operation has finished or urgent data is available. The argument is a pointer to a pid_t. If the argument is positive, send the signals to that process. If the argument is negative, send the signals to the process group with the ID of the absolute value of the argument. The process may only choose itself or its own process group to receive signals unless it has the CAP_KILL capability or an effective UID of 0.
FIOASYNC
Change the O_ASYNC flag to enable or disable asynchronous I/O mode of the socket. Asynchronous I/O mode means that the SIGIO signal or the signal set with F_SETSIG is raised when a new I/O event occurs.
Argument is an integer boolean flag.
SIOCGPGRP
Get the current process or process group that receives SIGIO or SIGURG signals, or 0 when none is set.

Valid fcntl(2) operations:

FIOGETOWN
The same as the SIOCGPGRP ioctl(2).
FIOSETOWN
The same as the SIOCSPGRP ioctl(2).

VERSIONS

SO_BINDTODEVICE was introduced in Linux 2.0.30. SO_PASSCRED is new in Linux 2.2. The sysctls are new in Linux 2.2. SO_RCVTIMEO and SO_SNDTIMEO are supported since Linux 2.3.41. Earlier, timeouts were fixed to a protocol specific setting, and could not be read or written.

NOTES

Linux assumes that half of the send/receive buffer is used for internal kernel structures; thus the sysctls are twice what can be observed on the wire.

Linux will only allow port re-use with the SO_REUSEADDR option when this option was set both in the previous program that performed a bind(2) to the port and in the program that wants to re-use the port. This differs from some implementations (e.g., FreeBSD) where only the later program needs to set the SO_REUSEADDR option. Typically this difference is invisible, since, for example, a server program is designed to always set this option.

BUGS

The CONFIG_FILTER socket options SO_ATTACH_FILTER and SO_DETACH_FILTER are not documented. The suggested interface to use them is via the libpcap library.

SEE ALSO

getsockopt(2), setsockopt(2), socket(2), capabilities(7), ddp(7), ip(7), packet(7)


arp(7)

ARP

Section: Linux Programmer's Manual (7)
Updated: 1999-06-03 Return to Main Contents

NAME

arp - Linux ARP kernel module.

DESCRIPTION

This kernel protocol module implements the Address Resolution Protocol defined in RFC 826. It is used to convert between Layer2 hardware addresses and IPv4 protocol addresses on directly connected networks. The user normally doesn't interact directly with this module except to configure it; instead it provides a service for other protocols in the kernel.

A user process can receive ARP packets by using packet(7) sockets. There is also a mechanism for managing the ARP cache in user-space by using netlink(7) sockets. The ARP table can also be controlled via ioctl(2) on any PF_INET socket.

The ARP module maintains a cache of mappings between hardware addresses and protocol addresses. The cache has a limited size so old and less frequently used entries are garbage-collected. Entries which are marked as permanent are never deleted by the garbage-collector. The cache can be directly manipulated by the use of ioctls and its behavior can be tuned by the sysctls defined below.

When there is no positive feedback for an existing mapping after some time (see the sysctls below) a neighbor cache entry is considered stale. Positive feedback can be gotten from a higher layer; for example from a successful TCP ACK. Other protocols can signal forward progress using the MSG_CONFIRM flag to sendmsg(2). When there is no forward progress ARP tries to reprobe. It first tries to ask a local arp daemon app_solicit times for an updated MAC address. If that fails and an old MAC address is known an unicast probe is send ucast_solicit times. If that fails too it will broadcast a new ARP request to the network. Requests are only send when there is data queued for sending.

Linux will automatically add a non-permanent proxy arp entry when it receives a request for an address it forwards to and proxy arp is enabled on the receiving interface. When there is a reject route for the target no proxy arp entry is added.

Ioctls

Three ioctls are available on all PF_INET sockets. They take a pointer to a struct arpreq as their parameter.

struct arpreq {
    struct sockaddr arp_pa;       /* protocol address */
    struct sockaddr arp_ha;       /* hardware address */
    int             arp_flags;    /* flags */
    struct sockaddr arp_netmask;  /* netmask of protocol address */
    char            arp_dev[16];
};

SIOCSARP, SIOCDARP and SIOCGARP respectively set, delete and get an ARP mapping. Setting & deleting ARP maps are privileged operations and may only be performed by a process with the CAP_NET_ADMIN capability or an effective UID of 0.

arp_pa must be an AF_INET socket and arp_ha must have the same type as the device which is specified in arp_dev. arp_dev is a zero-terminated string which names a device.

arp_flags
flag meaning
ATF_COM Lookup complete
ATF_PERM Permanent entry
ATF_PUBL Publish entry
ATF_USETRAILERS Trailers requested
ATF_NETMASK Use a netmask
ATF_DONTPUB Don't answer

If the ATF_NETMASK flag is set, then arp_netmask should be valid. Linux 2.2 does not support proxy network ARP entries, so this should be set to 0xffffffff, or 0 to remove an existing proxy arp entry. ATF_USETRAILERS is obsolete and should not be used.

Sysctls

ARP supports a sysctl interface to configure parameters on a global or per-interface basis. The sysctls can be accessed by reading or writing the /proc/sys/net/ipv4/neigh/*/* files or with the sysctl(2) interface. Each interface in the system has its own directory in /proc/sys/net/ipv4/neigh/. The setting in the `default' directory is used for all newly created devices. Unless otherwise specified time-related sysctls are specified in seconds.
anycast_delay
The maximum number of jiffies to delay before replying to a IPv6 neighbor solicitation message. Anycast support is not yet implemented. Defaults to 1 second.
app_solicit
The maximum number of probes to send to the user space ARP daemon via netlink before dropping back to multicast probes (see mcast_solicit). Defaults to 0.
base_reachable_time
Once a neighbor has been found, the entry is considered to be valid for at least a random value between base_reachable_time/2 and 3*base_reachable_time/2. An entry's validity will be extended if it receives positive feedback from higher level protocols. Defaults to 30 seconds.
delay_first_probe_time
Delay before first probe after it has been decided that a neighbor is stale. Defaults to 5 seconds.
gc_interval
How frequently the garbage collector for neighbor entries should attempt to run. Defaults to 30 seconds.
gc_stale_time
Determines how often to check for stale neighbor entries. When a neighbor entry is considered stale it is resolved again before sending data to it. Defaults to 60 seconds.
gc_thresh1
The minimum number of entries to keep in the ARP cache. The garbage collector will not run if there are fewer than this number of entries in the cache. Defaults to 128.
gc_thresh2
The soft maximum number of entries to keep in the ARP cache. The garbage collector will allow the number of entries to exceed this for 5 seconds before collection will be performed. Defaults to 512.
gc_thresh3
The hard maximum number of entries to keep in the ARP cache. The garbage collector will always run if there are more than this number of entries in the cache. Defaults to 1024.
locktime
The minimum number of jiffies to keep an ARP entry in the cache. This prevents ARP cache thrashing if there is more than one potential mapping (generally due to network misconfiguration). Defaults to 1 second.
mcast_solicit
The maximum number of attempts to resolve an address by multicast/broadcast before marking the entry as unreachable. Defaults to 3.
proxy_delay
When an ARP request for a known proxy-ARP address is received, delay up to proxy_delay jiffies before replying. This is used to prevent network flooding in some cases. Defaults to 0.8 seconds.
proxy_qlen
The maximum number of packets which may be queued to proxy-ARP addresses. Defaults to 64.
retrans_time
The number of jiffies to delay before retransmitting a request. Defaults to 1 second.
ucast_solicit
The maximum number of attempts to send unicast probes before asking the ARP daemon (see app_solicit). Defaults to 3.
unres_qlen
The maximum number of packets which may be queued for each unresolved address by other network layers. Defaults to 3.

VERSIONS

The struct arpreq changed in Linux 2.0 to include the arp_dev member and the ioctl numbers changed at the same time. Support for the old ioctls was dropped in Linux 2.2.

Support for proxy arp entries for networks (netmask not equal 0xffffffff) was dropped in Linux 2.2. It is replaced by automatic proxy arp setup by the kernel for all reachable hosts on other interfaces (when forwarding and proxy arp is enabled for the interface).

The neigh/* sysctls did not exist before Linux 2.2.

BUGS

Some timer settings are specified in jiffies, which is architecture related. On the Alpha a jiffy is 1/1024 of a second, on most other architectures it is 1/100s.

There is no way to signal positive feedback from user space. This means connection oriented protocols implemented in user space will generate excessive ARP traffic, because ndisc will regularly reprobe the MAC address. The same problem applies for some kernel protocols (e.g., NFS over UDP).

This man page mashes IPv4 specific and shared between IPv4 and IPv6 functionality together.

SEE ALSO

capabilities(7), ip(7)

RFC 826 for a description of ARP.
RFC 2461 for a description of IPv6 neighbor discovery and the base algorithms used.

Linux 2.2+ IPv4 ARP uses the IPv6 algorithms when applicable.


hier(7)

HIER

Section: Linux Programmer's Manual (7)
Updated: 2001-09-07 Return to Main Contents

NAME

hier - Description of the file system hierarchy

DESCRIPTION

A typical Linux system has, among others, the following directories:
/
This is the root directory. This is where the whole tree starts.
/bin
This directory contains executable programs which are needed in single user mode and to bring the system up or repair it.
/boot
Contains static files for the boot loader. This directory only holds the files which are needed during the boot process. The map installer and configuration files should go to /sbin and /etc.
/dev
Special or device files, which refer to physical devices. See mknod(1).
/etc
Contains configuration files which are local to the machine. Some larger software packages, like X11, can have their own subdirectories below /etc. Site-wide configuration files may be placed here or in /usr/etc. Nevertheless, programs should always look for these files in /etc and you may have links for these files to /usr/etc.
/etc/opt
Host-specific configuration files for add-on applications installed in /opt.
/etc/sgml
This directory contains the configuration files for SGML and XML (optional).
/etc/skel
When a new user account is created, files from this directory are usually copied into the user's home directory.
/etc/X11
Configuration files for the X11 window system (optional).
/home
On machines with home directories for users, these are usually beneath this directory, directly or not. The structure of this directory depends on local administration decisions.
/lib
This directory should hold those shared libraries that are necessary to boot the system and to run the commands in the root filesystem.
/media
This directory contains mount points for removeable media such as CD and DVD disks or USB sticks
/mnt
This directory contains mount points for temporarily mounted filesystems
/opt
This directory should contain add-on packages that contain static files.
/proc
This is a mount point for the proc filesystem, which provides information about running processes and the kernel. This pseudo-file system is described in more detail in proc(5).
/root
This directory is usually the home directory for the root user (optional).
/sbin
Like /bin, this directory holds commands needed to boot the system, but which are usually not executed by normal users.
/tmp
This directory contains temporary files which may be deleted with no notice, such as by a regular job or at system boot up.
/usr
This directory is usually mounted from a separate partition. It should hold only sharable, read-only data, so that it can be mounted by various machines running Linux.
/usr/X11R6
The X-Window system, version 11 release 6 (optional).
/usr/X11R6/bin
Binaries which belong to the X-Windows system; often, there is a symbolic link from the more traditional /usr/bin/X11 to here.
/usr/X11R6/lib
Data files associated with the X-Windows system.
/usr/X11R6/lib/X11
These contain miscellaneous files needed to run X; Often, there is a symbolic link from /usr/lib/X11 to this directory.
/usr/X11R6/include/X11
Contains include files needed for compiling programs using the X11 window system. Often, there is a symbolic link from /usr/include/X11 to this directory.
/usr/bin
This is the primary directory for executable programs. Most programs executed by normal users which are not needed for booting or for repairing the system and which are not installed locally should be placed in this directory.
/usr/bin/X11
is the traditional place to look for X11 executables; on Linux, it usually is a symbolic link to /usr/X11R6/bin.
/usr/dict
Replaced by /usr/share/dict.
/usr/doc
Replaced by /usr/share/doc.
/usr/etc
Site-wide configuration files to be shared between several machines may be stored in this directory. However, commands should always reference those files using the /etc directory. Links from files in /etc should point to the appropriate files in /usr/etc.
/usr/games
Binaries for games and educational programs (optional).
/usr/include
Include files for the C compiler.
/usr/include/X11
Include files for the C compiler and the X-Windows system. This is usually a symbolic link to /usr/X11R6/include/X11.
/usr/include/asm
Include files which declare some assembler functions. This used to be a symbolic link to /usr/src/linux/include/asm.
/usr/include/linux
This contains information which may change from system release to system release and used to be a symbolic link to /usr/src/linux/include/linux to get at operating system specific information.

(Note that one should have include files there that work correctly with the current libc and in user space. However, Linux kernel source is not designed to be used with user programs and does not know anything about the libc you are using. It is very likely that things will break if you let /usr/include/asm and /usr/include/linux point at a random kernel tree. Debian systems don't do this and use headers from a known good kernel version, provided in the libc*-dev package.)

/usr/include/g++
Include files to use with the GNU C++ compiler.
/usr/lib
Object libraries, including dynamic libraries, plus some executables which usually are not invoked directly. More complicated programs may have whole subdirectories there.
/usr/lib/X11
The usual place for data files associated with X programs, and configuration files for the X system itself. On Linux, it usually is a symbolic link to /usr/X11R6/lib/X11.
/usr/lib/gcc-lib
contains executables and include files for the GNU C compiler, gcc(1).
/usr/lib/groff
Files for the GNU groff document formatting system.
/usr/lib/uucp
Files for uucp(1).
/usr/local
This is where programs which are local to the site typically go.
/usr/local/bin
Binaries for programs local to the site.
/usr/local/doc
Local documentation.
/usr/local/etc
Configuration files associated with locally installed programs.
/usr/local/games
Binaries for locally installed games.
/usr/local/lib
Files associated with locally installed programs.
/usr/local/include
Header files for the local C compiler.
/usr/local/info
Info pages associated with locally installed programs.
/usr/local/man
Man pages associated with locally installed programs.
/usr/local/sbin
Locally installed programs for system administration.
/usr/local/share
Local application data that can be shared among different architectures of the same OS.
/usr/local/src
Source code for locally installed software.
/usr/man
Replaced by /usr/share/man.
/usr/sbin
This directory contains program binaries for system administration which are not essential for the boot process, for mounting /usr, or for system repair.
/usr/share
This directory contains subdirectories with specific application data, that can be shared among different architectures of the same OS. Often one finds stuff here that used to live in /usr/doc or /usr/lib or /usr/man.
/usr/share/dict
Contains the word lists used by spell checkers.
/usr/share/doc
Documentation about installed programs.
/usr/share/games
Static data files for games in /usr/games.
/usr/share/info
Info pages go here.
/usr/share/locale
Locale information goes here.
/usr/share/man
Manual pages go here in subdirectories according to the man page sections.
/usr/share/man/<locale>/man[1-9]
These directories contain manual pages for the specific locale in source code form. Systems which use a unique language and code set for all manual pages may omit the <locale> substring.
/usr/share/misc
Miscellaneous data that can be shared among different architectures of the same OS.
/usr/share/nls
The message catalogs for native language support go here.
/usr/share/sgml
Files for SGML and XML.
/usr/share/terminfo
The database for terminfo.
/usr/share/tmac
Troff macros that are not distributed with groff.
/usr/share/zoneinfo
Files for timezone information.
/usr/src
Source files for different parts of the system, included with some packages for reference purposes. Don't work here with your own projects, as files below /usr should be read-only except when installing software.
/usr/src/linux
This was the traditional place for the kernel source. Some distributions put here the source for the default kernel they ship. You should probably use another directory when building your own kernel.
/usr/tmp
Obsolete. This should be a link to /var/tmp. This link is present only for compatibility reasons and shouldn't be used.
/var
This directory contains files which may change in size, such as spool and log files.
/var/adm
This directory is superseded by /var/log and should be a symbolic link to /var/log.
/var/backups
Reserved for historical reasons.
/var/cache
Data cached for programs.
/var/catman/cat[1-9] or /var/cache/man/cat[1-9]
These directories contain preformatted manual pages according to their man page section. (The use of preformatted manual pages is deprecated.)
/var/cron
Reserved for historical reasons.
/var/lib
Variable state information for programs.
/var/local
Variable data for /usr/local.
/var/lock
Lock files are placed in this directory. The naming convention for device lock files is LCK..<device> where <device> is the device's name in the filesystem. The format used is that of HDU UUCP lock files, that is, lock files contain a PID as a 10-byte ASCII decimal number, followed by a newline character.
/var/log
Miscellaneous log files.
/var/opt
Variable data for /opt.
/var/mail
Users' mailboxes. Replaces /var/spool/mail.
/var/msgs
Reserved for historical reasons.
/var/preserve
Reserved for historical reasons.
/var/run
Run-time variable files, like files holding process identifiers (PIDs) and logged user information (utmp). Files in this directory are usually cleared when the system boots.
/var/spool
Spooled (or queued) files for various programs.
/var/spool/at
Spooled jobs for at(1).
/var/spool/cron
Spooled jobs for cron(1).
/var/spool/lpd
Spooled files for printing.
/var/spool/mail
Replaced by /var/mail.
/var/spool/mqueue
Queued outgoing mail.
/var/spool/news
Spool directory for news.
/var/spool/rwho
Spooled files for rwhod(8).
/var/spool/smail
Spooled files for the smail(1) mail delivery program.
/var/spool/uucp
Spooled files for uucp(1).
/var/tmp
Like /tmp, this directory holds temporary files stored for an unspecified duration.
/var/yp
Database files for NIS.

CONFORMING TO

The Filesystem Hierarchy Standard, Version 2.2 <http://www.pathname.com/fhs/>

BUGS

This list is not exhaustive; different systems may be configured differently.

SEE ALSO

find(1), ln(1), mount(1), proc(5)

The Filesystem Hierarchy Standard


iso_8859-7(7)

ISO_8859-7

Section: Linux Programmer's Manual (7)
Updated: 1999-05-31 Return to Main Contents

NAME

iso_8859-7 - the ISO 8859-7 character set encoded in octal, decimal, and hexadecimal

DESCRIPTION

The ISO 8859 standard includes several 8-bit extensions to the ASCII character set (also known as ISO 646-IRV). ISO 8859-7 encodes the characters used in modern monotonic Greek.

ISO 8859 Alphabets

The full set of ISO 8859 alphabets includes:
ISO 8859-1 | West European languages (Latin-1)
ISO 8859-2 | Central and East European languages (Latin-2)
ISO 8859-3 | Southeast European and miscellaneous languages (Latin-3)
ISO 8859-4 | Scandinavian/Baltic languages (Latin-4)
ISO 8859-5 | Latin/Cyrillic
ISO 8859-6 | Latin/Arabic
ISO 8859-7 | Latin/Greek
ISO 8859-8 | Latin/Hebrew
ISO 8859-9 | Latin-1 modification for Turkish (Latin-5)
ISO 8859-10 | Lappish/Nordic/Eskimo languages (Latin-6)
ISO 8859-11 | Latin/Thai
ISO 8859-13 | Baltic Rim languages (Latin-7)
ISO 8859-14 | Celtic (Latin-8)
ISO 8859-15 | West European languages (Latin-9)
ISO 8859-16 | Romanian (Latin-10)

ISO 8859-7 Characters

The following table displays the characters in ISO 8859-7, which are printable and unlisted in the ascii(7) manual page. The fourth column will only show the proper glyphs in an environment configured for ISO 8859-7.
Oct | Dec | Hex | Char | Description
240 | 160 | A0 |  | NO-BREAK SPACE
241 | 161 | A1 | ¡ | MODIFIER LETTER REVERSED COMMA
242 | 162 | A2 | ¢ | MODIFIER LETTER APOSTROPHE
243 | 163 | A3 | £ | POUND SIGN
246 | 166 | A6 | ¦ | BROKEN BAR
247 | 167 | A7 | § | SECTION SIGN
250 | 168 | A8 | ¨ | DIAERESIS
251 | 169 | A9 | © | COPYRIGHT SIGN
253 | 171 | AB | « | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
254 | 172 | AC | ¬ | NOT SIGN
255 | 173 | AD |  | SOFT HYPHEN
257 | 175 | AF | ¯ | HORIZONTAL BAR
260 | 176 | B0 | ° | DEGREE SIGN
261 | 177 | B1 | ± | PLUS-MINUS SIGN
262 | 178 | B2 | ² | SUPERSCRIPT TWO
263 | 179 | B3 | ³ | SUPERSCRIPT THREE
264 | 180 | B4 | ´ | GREEK TONOS
265 | 181 | B5 | µ | GREEK DIALYTIKA TONOS
266 | 182 | B6 | ¶ | GREEK CAPITAL LETTER ALPHA WITH TONOS
267 | 183 | B7 | · | MIDDLE DOT
270 | 184 | B8 | ¸ | GREEK CAPITAL LETTER EPSILON WITH TONOS
271 | 185 | B9 | ¹ | GREEK CAPITAL LETTER ETA WITH TONOS
272 | 186 | BA | º | GREEK CAPITAL LETTER IOTA WITH TONOS
273 | 187 | BB | » | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
274 | 188 | BC | ¼ | GREEK CAPITAL LETTER OMICRON WITH TONOS
275 | 189 | BD | ½ | VULGAR FRACTION ONE HALF
276 | 190 | BE | ¾ | GREEK CAPITAL LETTER UPSILON WITH TONOS
277 | 191 | BF | ¿ | GREEK CAPITAL LETTER OMEGA WITH TONOS
300 | 192 | C0 | À | GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
301 | 193 | C1 | Á | GREEK CAPITAL LETTER ALPHA
302 | 194 | C2 | Â | GREEK CAPITAL LETTER BETA
303 | 195 | C3 | Ã | GREEK CAPITAL LETTER GAMMA
304 | 196 | C4 | Ä | GREEK CAPITAL LETTER DELTA
305 | 197 | C5 | Å | GREEK CAPITAL LETTER EPSILON
306 | 198 | C6 | Æ | GREEK CAPITAL LETTER ZETA
307 | 199 | C7 | Ç | GREEK CAPITAL LETTER ETA
310 | 200 | C8 | È | GREEK CAPITAL LETTER THETA
311 | 201 | C9 | É | GREEK CAPITAL LETTER IOTA
312 | 202 | CA | Ê | GREEK CAPITAL LETTER KAPPA
313 | 203 | CB | Ë | GREEK CAPITAL LETTER LAMDA
314 | 204 | CC | Ì | GREEK CAPITAL LETTER MU
315 | 205 | CD | Í | GREEK CAPITAL LETTER NU
316 | 206 | CE | Î | GREEK CAPITAL LETTER XI
317 | 207 | CF | Ï | GREEK CAPITAL LETTER OMICRON
320 | 208 | D0 | Ð | GREEK CAPITAL LETTER PI
321 | 209 | D1 | Ñ | GREEK CAPITAL LETTER RHO
323 | 211 | D3 | Ó | GREEK CAPITAL LETTER SIGMA
324 | 212 | D4 | Ô | GREEK CAPITAL LETTER TAU
325 | 213 | D5 | Õ | GREEK CAPITAL LETTER UPSILON
326 | 214 | D6 | Ö | GREEK CAPITAL LETTER PHI
327 | 215 | D7 | × | GREEK CAPITAL LETTER CHI
330 | 216 | D8 | Ø | GREEK CAPITAL LETTER PSI
331 | 217 | D9 | Ù | GREEK CAPITAL LETTER OMEGA
332 | 218 | DA | Ú | GREEK CAPITAL LETTER IOTA WITH DIALYTIKA
333 | 219 | DB | Û | GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA
334 | 220 | DC | Ü | GREEK SMALL LETTER ALPHA WITH TONOS
335 | 221 | DD | Ý | GREEK SMALL LETTER EPSILON WITH TONOS
336 | 222 | DE | Þ | GREEK SMALL LETTER ETA WITH TONOS
337 | 223 | DF | ß | GREEK SMALL LETTER IOTA WITH TONOS
340 | 224 | E0 | à | GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
341 | 225 | E1 | á | GREEK SMALL LETTER ALPHA
342 | 226 | E2 | â | GREEK SMALL LETTER BETA
343 | 227 | E3 | ã | GREEK SMALL LETTER GAMMA
344 | 228 | E4 | ä | GREEK SMALL LETTER DELTA
345 | 229 | E5 | å | GREEK SMALL LETTER EPSILON
346 | 230 | E6 | æ | GREEK SMALL LETTER ZETA
347 | 231 | E7 | ç | GREEK SMALL LETTER ETA
350 | 232 | E8 | è | GREEK SMALL LETTER THETA
351 | 233 | E9 | é | GREEK SMALL LETTER IOTA
352 | 234 | EA | ê | GREEK SMALL LETTER KAPPA
353 | 235 | EB | ë | GREEK SMALL LETTER LAMDA
354 | 236 | EC | ì | GREEK SMALL LETTER MU
355 | 237 | ED | í | GREEK SMALL LETTER NU
356 | 238 | EE | î | GREEK SMALL LETTER XI
357 | 239 | EF | ï | GREEK SMALL LETTER OMICRON
360 | 240 | F0 | ð | GREEK SMALL LETTER PI
361 | 241 | F1 | ñ | GREEK SMALL LETTER RHO
362 | 242 | F2 | ò | GREEK SMALL LETTER FINAL SIGMA
363 | 243 | F3 | ó | GREEK SMALL LETTER SIGMA
364 | 244 | F4 | ô | GREEK SMALL LETTER TAU
365 | 245 | F5 | õ | GREEK SMALL LETTER UPSILON
366 | 246 | F6 | ö | GREEK SMALL LETTER PHI
367 | 247 | F7 | ÷ | GREEK SMALL LETTER CHI
370 | 248 | F8 | ø | GREEK SMALL LETTER PSI
371 | 249 | F9 | ù | GREEK SMALL LETTER OMEGA
372 | 250 | FA | ú | GREEK SMALL LETTER IOTA WITH DIALYTIKA
373 | 251 | FB | û | GREEK SMALL LETTER UPSILON WITH DIALYTIKA
374 | 252 | FC | ü | GREEK SMALL LETTER OMICRON WITH TONOS
375 | 253 | FD | ý | GREEK SMALL LETTER UPSILON WITH TONOS
376 | 254 | FE | þ | GREEK SMALL LETTER OMEGA WITH TONOS

NOTES

ISO 8859-7 was formerly known as ELOT-928 or ECMA-118:1986.

SEE ALSO

ascii(7)


man(7)

MAN

Section: Linux Programmer's Manual (7)
Updated: 2007-05-30 Return to Main Contents

NAME

man - macros to format man pages

SYNOPSIS

groff -Tascii -man file ...

groff -Tps -man file ...

man [section] title

DESCRIPTION

This manual page explains the groff tmac.an macro package (often called the man macro package). This macro package should be used by developers when writing or porting man pages for Linux. It is fairly compatible with other versions of this macro package, so porting man pages should not be a major problem (exceptions include the NET-2 BSD release, which uses a totally different macro package called mdoc; see mdoc(7)).

Note that NET-2 BSD mdoc man pages can be used with groff simply by specifying the -mdoc option instead of the -man option. Using the -mandoc option is, however, recommended, since this will automatically detect which macro package is in use.

For conventions that should be employed when writing man pages for the Linux man-pages package, see man-pages(7).

Title line

The first command in a man page (after comment lines, that is, lines that start with .\") should be

.TH title section date source manual

For details of the arguments that should be supplied to the TH command, see man-pages(7).

Note that BSD mdoc-formatted pages begin with the Dd command, not the TH command.

Sections

Sections are started with .SH followed by the heading name.

The only mandatory heading is NAME, which should be the first section and be followed on the next line by a one line description of the program:

.SH NAME

It is extremely important that this format is followed, and that there is a backslash before the single dash which follows the command name. This syntax is used by the makewhatis(8) program to create a database of short command descriptions for the whatis(1) and apropos(1) commands.

For a list of other sections that might appear in a manual page, see man-pages(7).

Fonts

The commands to select the type face are:
.B
Bold
.BI
Bold alternating with italics (especially useful for function specifications)
.BR
Bold alternating with Roman (especially useful for referring to other manual pages)
.I
Italics
.IB
Italics alternating with bold
.IR
Italics alternating with Roman
.RB
Roman alternating with bold
.RI
Roman alternating with italics
.SB
Small alternating with bold
.SM
Small (useful for acronyms)

Traditionally, each command can have up to six arguments, but the GNU implementation removes this limitation (you might still want to limit yourself to 6 arguments for portability's sake). Arguments are delimited by spaces. Double quotes can be used to specify an argument which contains spaces. All of the arguments will be printed next to each other without intervening spaces, so that the .BR command can be used to specify a word in bold followed by a mark of punctuation in Roman. If no arguments are given, the command is applied to the following line of text.

Other Macros and Strings

Below are other relevant macros and predefined strings. Unless noted otherwise, all macros cause a break (end the current line of text). Many of these macros set or use the "prevailing indent." The "prevailing indent" value is set by any macro with the parameter i below; macros may omit i in which case the current prevailing indent will be used. As a result, successive indented paragraphs can use the same indent without re-specifying the indent value. A normal (non-indented) paragraph resets the prevailing indent value to its default value (0.5 inches). By default a given indent is measured in ens; try to use ens or ems as units for indents, since these will automatically adjust to font size changes. The other key macro definitions are:

Normal Paragraphs

.LP
Same as .PP (begin a new paragraph).
.P
Same as .PP (begin a new paragraph).
.PP
Begin a new paragraph and reset prevailing indent.

Relative Margin Indent

.RS i
Start relative margin indent: moves the left margin i to the right (if i is omitted, the prevailing indent value is used). A new prevailing indent is set to 0.5 inches. As a result, all following paragraph(s) will be indented until the corresponding .RE.
.RE
End relative margin indent and restores the previous value of the prevailing indent.

Indented Paragraph Macros

.HP i
Begin paragraph with a hanging indent (the first line of the paragraph is at the left margin of normal paragraphs, and the rest of the paragraph's lines are indented).
.IP x i
Indented paragraph with optional hanging tag. If the tag x is omitted, the entire following paragraph is indented by i. If the tag x is provided, it is hung at the left margin before the following indented paragraph (this is just like .TP except the tag is included with the command instead of being on the following line). If the tag is too long, the text after the tag will be moved down to the next line (text will not be lost or garbled). For bulleted lists, use this macro with \(bu (bullet) or \(em (em dash) as the tag, and for numbered lists, use the number or letter followed by a period as the tag; this simplifies translation to other formats.
.TP i
Begin paragraph with hanging tag. The tag is given on the next line, but its results are like those of the .IP command.

Hypertext Link Macros

(Feature supported with groff only.) In order to use hypertext link macros, it is necessary to load the www.tmac macro package. Use the request .mso www.tmac to do this.
.URL url link trailer
Inserts a hypertext link to the URI (URL) url, with link as the text of the link. The trailer will be printed immediately afterwards. When generating HTML this should translate into the HTML command <A HREF="url">link</A>trailer.
This and other related macros are new, and many tools won't do anything with them, but since many tools (including troff) will simply ignore undefined macros (or at worst insert their text) these are safe to insert.
It can be useful to define your own URL macro in manual pages for the benefit of those viewing it with a roff viewer other than groff. That way, the URL, link text, and trailer text (if any) are still visible.
Here's an example:
.de URL
\\$2 \(laURL: \\$1 \(ra\\$3
..
.if \n[.g] .mso www.tmac
.TH ...
(later in the page)
This software comes from the
.URL "http://www.gnu.org/" "GNU Project" " of the"
.URL "http://www.fsf.org/" "Free Software Foundation" .
In the above, if groff is being used, the www.tmac macro package's definition of the URL macro will supersede the locally defined one.

A number of other link macros are available. See groff_www(7) for more details.

Miscellaneous Macros

.DT
Reset tabs to default tab values (every 0.5 inches); does not cause a break.
.PD d
Set inter-paragraph vertical distance to d (if omitted, d=0.4v); does not cause a break.
.SS t
Subheading t (like .SH, but used for a subsection inside a section).

Predefined Strings

The man package has the following predefined strings:
\*R
Registration Symbol: ®
\*S
Change to default font size
\*(Tm
Trademark Symbol:
\*(lq
Left angled double quote: ``
\*(rq
Right angled double quote: ''

Safe Subset

Although technically man is a troff macro package, in reality a large number of other tools process man page files that don't implement all of troff's abilities. Thus, it's best to avoid some of troff's more exotic abilities where possible to permit these other tools to work correctly. Avoid using the various troff preprocessors (if you must, go ahead and use tbl(1), but try to use the IP and TP commands instead for two-column tables). Avoid using computations; most other tools can't process them. Use simple commands that are easy to translate to other formats. The following troff macros are believed to be safe (though in many cases they will be ignored by translators): \ , ., ad, bp, br, ce, de, ds, el, ie, if, fi, ft, hy, ig, in, na, ne, nf, nh, ps, so, sp, ti, tr.

You may also use many troff escape sequences (those sequences beginning with \). When you need to include the backslash character as normal text, use \e. Other sequences you may use, where x or xx are any characters and N is any digit, include: \', \`, \-, \., \ , \%, \*x, \*(xx, \(xx, \$N, \nx, \n(xx, \fx, and \f(xx. Avoid using the escape sequences for drawing graphics.

Do not use the optional parameter for bp (break page). Use only positive values for sp (vertical space). Don't define a macro (de) with the same name as a macro in this or the mdoc macro package with a different meaning; it's likely that such redefinitions will be ignored. Every positive indent (in) should be paired with a matching negative indent (although you should be using the RS and RE macros instead). The condition test (if,ie) should only have 't' or 'n' as the condition. Only translations (tr) that can be ignored should be used. Font changes (ft and the \f escape sequence) should only have the values 1, 2, 3, 4, R, I, B, P, or CW (the ft command may also have no parameters).

If you use capabilities beyond these, check the results carefully on several tools. Once you've confirmed that the additional capability is safe, let the maintainer of this document know about the safe command or sequence that should be added to this list.

FILES

/usr/share/groff/[*/]tmac/tmac.an
/usr/man/whatis

NOTES

By all means include full URLs (or URIs) in the text itself; some tools such as man2html(1) can automatically turn them into hypertext links. You can also use the new URL macro to identify links to related information. If you include URLs, use the full URL (e.g., <http://www.kernelnotes.org>) to ensure that tools can automatically find the URLs.

Tools processing these files should open the file and examine the first non-whitespace character. A period (.) or single quote (') at the beginning of a line indicates a troff-based file (such as man or mdoc). A left angle bracket (<) indicates an SGML/XML-based file (such as HTML or Docbook). Anything else suggests simple ASCII text (e.g., a "catman" result).

Many man pages begin with '\" followed by a space and a list of characters, indicating how the page is to be preprocessed. For portability's sake to non-troff translators we recommend that you avoid using anything other than tbl(1), and Linux can detect that automatically. However, you might want to include this information so your man page can be handled by other (less capable) systems. Here are the definitions of the preprocessors invoked by these characters:

e
eqn(1)
g
grap(1)
p
pic(1)
r
refer(1)
t
tbl(1)
v
vgrind(1)

BUGS

Most of the macros describe formatting (e.g., font type and spacing) instead of marking semantic content (e.g., this text is a reference to another page), compared to formats like mdoc and DocBook (even HTML has more semantic markings). This situation makes it harder to vary the man format for different media, to make the formatting consistent for a given media, and to automatically insert cross-references. By sticking to the safe subset described above, it should be easier to automate transitioning to a different reference page format in the future.

The Sun macro TX is not implemented.

SEE ALSO

apropos(1), groff(1), man(1), man2html(1), whatis(1), groff_man(7), groff_www(7), man-pages(7), mdoc(7), mdoc.samples(7)


ascii(7)

ASCII

Section: Linux Programmer's Manual (7)
Updated: 2004-04-01 Return to Main Contents

NAME

ascii - the ASCII character set encoded in octal, decimal, and hexadecimal

DESCRIPTION

ASCII is the American Standard Code for Information Interchange. It is a 7-bit code. Many 8-bit codes (such as ISO 8859-1, the Linux default character set) contain ASCII as their lower half. The international counterpart of ASCII is known as ISO 646.

The following table contains the 128 ASCII characters.

C program '\X' escapes are noted.
Oct | Dec | Hex | Char | Oct | Dec | Hex | Char
000 | 0 | 00 | NUL '\0' | 100 | 64 | 40 | @
001 | 1 | 01 | SOH (start of heading) | 101 | 65 | 41 | A
002 | 2 | 02 | STX (start of text) | 102 | 66 | 42 | B
003 | 3 | 03 | ETX (end of text) | 103 | 67 | 43 | C
004 | 4 | 04 | EOT (end of transmission) | 104 | 68 | 44 | D
005 | 5 | 05 | ENQ (enquiry) | 105 | 69 | 45 | E
006 | 6 | 06 | ACK (acknowledge) | 106 | 70 | 46 | F
007 | 7 | 07 | BEL '\a' (bell) | 107 | 71 | 47 | G
010 | 8 | 08 | BS '\b' (backspace) | 110 | 72 | 48 | H
011 | 9 | 09 | HT '\t' (horizontal tab) | 111 | 73 | 49 | I
012 | 10 | 0A | LF '\n' (new line) | 112 | 74 | 4A | J
013 | 11 | 0B | VT '\v' (vertical tab) | 113 | 75 | 4B | K
014 | 12 | 0C | FF '\f' (form feed) | 114 | 76 | 4C | L
015 | 13 | 0D | CR '\r' (carriage ret) | 115 | 77 | 4D | M
016 | 14 | 0E | SO (shift out) | 116 | 78 | 4E | N
017 | 15 | 0F | SI (shift in) | 117 | 79 | 4F | O
020 | 16 | 10 | DLE (data link escape) | 120 | 80 | 50 | P
021 | 17 | 11 | DC1 (device control 1) | 121 | 81 | 51 | Q
022 | 18 | 12 | DC2 (device control 2) | 122 | 82 | 52 | R
023 | 19 | 13 | DC3 (device control 3) | 123 | 83 | 53 | S
024 | 20 | 14 | DC4 (device control 4) | 124 | 84 | 54 | T
025 | 21 | 15 | NAK (negative ack.) | 125 | 85 | 55 | U
026 | 22 | 16 | SYN (synchronous idle) | 126 | 86 | 56 | V
027 | 23 | 17 | ETB (end of trans. blk) | 127 | 87 | 57 | W
030 | 24 | 18 | CAN (cancel) | 130 | 88 | 58 | X
031 | 25 | 19 | EM (end of medium) | 131 | 89 | 59 | Y
032 | 26 | 1A | SUB (substitute) | 132 | 90 | 5A | Z
033 | 27 | 1B | ESC (escape) | 133 | 91 | 5B | [
034 | 28 | 1C | FS (file separator) | 134 | 92 | 5C | \ '\\'
035 | 29 | 1D | GS (group separator) | 135 | 93 | 5D | ]
036 | 30 | 1E | RS (record separator) | 136 | 94 | 5E | ^
037 | 31 | 1F | US (unit separator) | 137 | 95 | 5F | _
040 | 32 | 20 | SPACE | 140 | 96 | 60 | `
041 | 33 | 21 | ! | 141 | 97 | 61 | a
042 | 34 | 22 | " | 142 | 98 | 62 | b
043 | 35 | 23 | # | 143 | 99 | 63 | c
044 | 36 | 24 | $ | 144 | 100 | 64 | d
045 | 37 | 25 | % | 145 | 101 | 65 | e
046 | 38 | 26 | & | 146 | 102 | 66 | f
047 | 39 | 27 | ' | 147 | 103 | 67 | g
050 | 40 | 28 | ( | 150 | 104 | 68 | h
051 | 41 | 29 | ) | 151 | 105 | 69 | i
052 | 42 | 2A | * | 152 | 106 | 6A | j
053 | 43 | 2B | + | 153 | 107 | 6B | k
054 | 44 | 2C | , | 154 | 108 | 6C | l
055 | 45 | 2D | - | 155 | 109 | 6D | m
056 | 46 | 2E | . | 156 | 110 | 6E | n
057 | 47 | 2F | / | 157 | 111 | 6F | o
060 | 48 | 30 | 0 | 160 | 112 | 70 | p
061 | 49 | 31 | 1 | 161 | 113 | 71 | q
062 | 50 | 32 | 2 | 162 | 114 | 72 | r
063 | 51 | 33 | 3 | 163 | 115 | 73 | s
064 | 52 | 34 | 4 | 164 | 116 | 74 | t
065 | 53 | 35 | 5 | 165 | 117 | 75 | u
066 | 54 | 36 | 6 | 166 | 118 | 76 | v
067 | 55 | 37 | 7 | 167 | 119 | 77 | w
070 | 56 | 38 | 8 | 170 | 120 | 78 | x
071 | 57 | 39 | 9 | 171 | 121 | 79 | y
072 | 58 | 3A | : | 172 | 122 | 7A | z
073 | 59 | 3B | ; | 173 | 123 | 7B | {
074 | 60 | 3C | < | 174 | 124 | 7C | |
075 | 61 | 3D | = | 175 | 125 | 7D | }
076 | 62 | 3E | > | 176 | 126 | 7E | ~
077 | 63 | 3F | ? | 177 | 127 | 7F | DEL

Tables

For convenience, let us give more compact tables in hex and decimal.

   2 3 4 5 6 7       30 40 50 60 70 80 90 100 110 120
 -------------      ---------------------------------
0:   0 @ P ` p     0:    (  2  <  F  P  Z  d   n   x
1: ! 1 A Q a q     1:    )  3  =  G  Q  [  e   o   y
2: " 2 B R b r     2:    *  4  >  H  R  \  f   p   z
3: # 3 C S c s     3: !  +  5  ?  I  S  ]  g   q   {
4: $ 4 D T d t     4: "  ,  6  @  J  T  ^  h   r   |
5: % 5 E U e u     5: #  -  7  A  K  U  _  i   s   }
6: & 6 F V f v     6: $  .  8  B  L  V  `  j   t   ~
7: ' 7 G W g w     7: %  /  9  C  M  W  a  k   u  DEL
8: ( 8 H X h x     8: &  0  :  D  N  X  b  l   v
9: ) 9 I Y i y     9: '  1  ;  E  O  Y  c  m   w
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL

NOTES

History

An ascii manual page appeared in Version 7 of AT&T UNIX.

On older terminals, the underscore code is displayed as a left arrow, called backarrow, the caret is displayed as an up-arrow and the vertical bar has a hole in the middle.

Uppercase and lowercase characters differ by just one bit and the ASCII character 2 differs from the double quote by just one bit, too. That made it much easier to encode characters mechanically or with a non-microcontroller-based electronic keyboard and that pairing was found on old teletypes.

The ASCII standard was published by the United States of America Standards Institute (USASI) in 1968.

SEE ALSO

iso_8859-1(7), iso_8859-15(7), iso_8859-16(7), iso_8859-2(7), iso_8859-7(7), iso_8859-9(7)


tcp(7)

TCP

Section: Linux Programmer's Manual (7)
Updated: 2005-06-15 Return to Main Contents

NAME

tcp - TCP protocol

SYNOPSIS

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
tcp_socket = socket(PF_INET, SOCK_STREAM, 0);

DESCRIPTION

This is an implementation of the TCP protocol defined in RFC 793, RFC 1122 and RFC 2001 with the NewReno and SACK extensions. It provides a reliable, stream-oriented, full-duplex connection between two sockets on top of ip(7), for both v4 and v6 versions. TCP guarantees that the data arrives in order and retransmits lost packets. It generates and checks a per-packet checksum to catch transmission errors. TCP does not preserve record boundaries.

A newly created TCP socket has no remote or local address and is not fully specified. To create an outgoing TCP connection use connect(2) to establish a connection to another TCP socket. To receive new incoming connections, first bind(2) the socket to a local address and port and then call listen(2) to put the socket into the listening state. After that a new socket for each incoming connection can be accepted using accept(2). A socket which has had accept(2) or connect(2) successfully called on it is fully specified and may transmit data. Data cannot be transmitted on listening or not yet connected sockets.

Linux supports RFC 1323 TCP high performance extensions. These include Protection Against Wrapped Sequence Numbers (PAWS), Window Scaling and Timestamps. Window scaling allows the use of large (> 64K) TCP windows in order to support links with high latency or bandwidth. To make use of them, the send and receive buffer sizes must be increased. They can be set globally with the net.ipv4.tcp_wmem and net.ipv4.tcp_rmem sysctl variables, or on individual sockets by using the SO_SNDBUF and SO_RCVBUF socket options with the setsockopt(2) call.

The maximum sizes for socket buffers declared via the SO_SNDBUF and SO_RCVBUF mechanisms are limited by the global net.core.rmem_max and net.core.wmem_max sysctls. Note that TCP actually allocates twice the size of the buffer requested in the setsockopt(2) call, and so a succeeding getsockopt(2) call will not return the same size of buffer as requested in the setsockopt(2) call. TCP uses the extra space for administrative purposes and internal kernel structures, and the sysctl variables reflect the larger sizes compared to the actual TCP windows. On individual connections, the socket buffer size must be set prior to the listen(2) or connect(2) calls in order to have it take effect. See socket(7) for more information.

TCP supports urgent data. Urgent data is used to signal the receiver that some important message is part of the data stream and that it should be processed as soon as possible. To send urgent data specify the MSG_OOB option to send(2). When urgent data is received, the kernel sends a SIGURG signal to the process or process group that has been set as the socket "owner" using the SIOCSPGRP or FIOSETOWN ioctls (or the POSIX.1-2001-specified fcntl(2) F_SETOWN operation). When the SO_OOBINLINE socket option is enabled, urgent data is put into the normal data stream (a program can test for its location using the SIOCATMARK ioctl described below), otherwise it can be only received when the MSG_OOB flag is set for recv(2) or recvmsg(2).

Linux 2.4 introduced a number of changes for improved throughput and scaling, as well as enhanced functionality. Some of these features include support for zero-copy sendfile(2), Explicit Congestion Notification, new management of TIME_WAIT sockets, keep-alive socket options and support for Duplicate SACK extensions.

Address Formats

TCP is built on top of IP (see ip(7)). The address formats defined by ip(7) apply to TCP. TCP only supports point-to-point communication; broadcasting and multicasting are not supported.

Sysctls

These variables can be accessed by the /proc/sys/net/ipv4/* files or with the sysctl(2) interface. In addition, most IP sysctls also apply to TCP; see ip(7). Variables described as Boolean take an integer value, with a non-zero value ("true") meaning that the corresponding option is enabled, and a zero value ("false") meaning that the option is disabled.
tcp_abort_on_overflow (Boolean; default: disabled)
Enable resetting connections if the listening service is too slow and unable to keep up and accept them. It means that if overflow occurred due to a burst, the connection will recover. Enable this option only if you are really sure that the listening daemon cannot be tuned to accept connections faster. Enabling this option can harm the clients of your server.
tcp_adv_win_scale (integer; default: 2)
Count buffering overhead as bytes/2^tcp_adv_win_scale (if tcp_adv_win_scale > 0) or bytes-bytes/2^(-tcp_adv_win_scale), if it is <= 0.

The socket receive buffer space is shared between the application and kernel. TCP maintains part of the buffer as the TCP window, this is the size of the receive window advertised to the other end. The rest of the space is used as the "application" buffer, used to isolate the network from scheduling and application latencies. The tcp_adv_win_scale default value of 2 implies that the space used for the application buffer is one fourth that of the total.

tcp_app_win (integer; default: 31)
This variable defines how many bytes of the TCP window are reserved for buffering overhead.

A maximum of (window/2^tcp_app_win, mss) bytes in the window are reserved for the application buffer. A value of 0 implies that no amount is reserved.

tcp_bic (Boolean; default: disabled)
Enable BIC TCP congestion control algorithm. BIC-TCP is a sender-side only change that ensures a linear RTT fairness under large windows while offering both scalability and bounded TCP-friendliness. The protocol combines two schemes called additive increase and binary search increase. When the congestion window is large, additive increase with a large increment ensures linear RTT fairness as well as good scalability. Under small congestion windows, binary search increase provides TCP friendliness.
tcp_bic_low_window (integer; default: 14)
Sets the threshold window (in packets) where BIC TCP starts to adjust the congestion window. Below this threshold BIC TCP behaves the same as the default TCP Reno.
tcp_bic_fast_convergence (Boolean; default: enabled)
Forces BIC TCP to more quickly respond to changes in congestion window. Allows two flows sharing the same connection to converge more rapidly.
tcp_dsack (Boolean; default: enabled)
Enable RFC 2883 TCP Duplicate SACK support.
tcp_ecn (Boolean; default: disabled)
Enable RFC 2884 Explicit Congestion Notification. When enabled, connectivity to some destinations could be affected due to older, misbehaving routers along the path causing connections to be dropped.
tcp_fack (Boolean; default: enabled)
Enable TCP Forward Acknowledgement support.
tcp_fin_timeout (integer; default: 60)
This specifies how many seconds to wait for a final FIN packet before the socket is forcibly closed. This is strictly a violation of the TCP specification, but required to prevent denial-of-service attacks. In Linux 2.2, the default value was 180.
tcp_frto (Boolean; default: disabled)
Enables F-RTO, an enhanced recovery algorithm for TCP retransmission timeouts. It is particularly beneficial in wireless environments where packet loss is typically due to random radio interference rather than intermediate router congestion.
tcp_keepalive_intvl (integer; default: 75)
The number of seconds between TCP keep-alive probes.
tcp_keepalive_probes (integer; default: 9)
The maximum number of TCP keep-alive probes to send before giving up and killing the connection if no response is obtained from the other end.
tcp_keepalive_time (integer; default: 7200)
The number of seconds a connection needs to be idle before TCP begins sending out keep-alive probes. Keep-alives are only sent when the SO_KEEPALIVE socket option is enabled. The default value is 7200 seconds (2 hours). An idle connection is terminated after approximately an additional 11 minutes (9 probes an interval of 75 seconds apart) when keep-alive is enabled.

Note that underlying connection tracking mechanisms and application timeouts may be much shorter.

tcp_low_latency (Boolean; default: disabled)
If enabled, the TCP stack makes decisions that prefer lower latency as opposed to higher throughput. It this option is disabled, then higher throughput is preferred. An example of an application where this default should be changed would be a Beowulf compute cluster.
tcp_max_orphans (integer; default: see below)
The maximum number of orphaned (not attached to any user file handle) TCP sockets allowed in the system. When this number is exceeded, the orphaned connection is reset and a warning is printed. This limit exists only to prevent simple denial-of-service attacks. Lowering this limit is not recommended. Network conditions might require you to increase the number of orphans allowed, but note that each orphan can eat up to ~64K of unswappable memory. The default initial value is set equal to the kernel parameter NR_FILE. This initial default is adjusted depending on the memory in the system.
tcp_max_syn_backlog (integer; default: see below)
The maximum number of queued connection requests which have still not received an acknowledgement from the connecting client. If this number is exceeded, the kernel will begin dropping requests. The default value of 256 is increased to 1024 when the memory present in the system is adequate or greater (>= 128Mb), and reduced to 128 for those systems with very low memory (<= 32Mb). It is recommended that if this needs to be increased above 1024, TCP_SYNQ_HSIZE in include/net/tcp.h be modified to keep TCP_SYNQ_HSIZE*16<=tcp_max_syn_backlog, and the kernel be recompiled.
tcp_max_tw_buckets (integer; default: see below)
The maximum number of sockets in TIME_WAIT state allowed in the system. This limit exists only to prevent simple denial-of-service attacks. The default value of NR_FILE*2 is adjusted depending on the memory in the system. If this number is exceeded, the socket is closed and a warning is printed.
tcp_mem
This is a vector of 3 integers: [low, pressure, high]. These bounds are used by TCP to track its memory usage. The defaults are calculated at boot time from the amount of available memory. (TCP can only use low memory for this, which is limited to around 900 megabytes on 32-bit systems. 64-bit systems do not suffer this limitation.)

low - TCP doesn't regulate its memory allocation when the number of pages it has allocated globally is below this number.

pressure - when the amount of memory allocated by TCP exceeds this number of pages, TCP moderates its memory consumption. This memory pressure state is exited once the number of pages allocated falls below the low mark.

high - the maximum number of pages, globally, that TCP will allocate. This value overrides any other limits imposed by the kernel.

tcp_orphan_retries (integer; default: 8)
The maximum number of attempts made to probe the other end of a connection which has been closed by our end.
tcp_reordering (integer; default: 3)
The maximum a packet can be reordered in a TCP packet stream without TCP assuming packet loss and going into slow start. It is not advisable to change this number. This is a packet reordering detection metric designed to minimize unnecessary back off and retransmits provoked by reordering of packets on a connection.
tcp_retrans_collapse (Boolean; default: enabled)
Try to send full-sized packets during retransmit.
tcp_retries1 (integer; default: 3)
The number of times TCP will attempt to retransmit a packet on an established connection normally, without the extra effort of getting the network layers involved. Once we exceed this number of retransmits, we first have the network layer update the route if possible before each new retransmit. The default is the RFC specified minimum of 3.
tcp_retries2 (integer; default: 15)
The maximum number of times a TCP packet is retransmitted in established state before giving up. The default value is 15, which corresponds to a duration of approximately between 13 to 30 minutes, depending on the retransmission timeout. The RFC 1122 specified minimum limit of 100 seconds is typically deemed too short.
tcp_rfc1337 (Boolean; default: disabled)
Enable TCP behavior conformant with RFC 1337. When disabled, if a RST is received in TIME_WAIT state, we close the socket immediately without waiting for the end of the TIME_WAIT period.
tcp_rmem
This is a vector of 3 integers: [min, default, max]. These parameters are used by TCP to regulate receive buffer sizes. TCP dynamically adjusts the size of the receive buffer from the defaults listed below, in the range of these sysctl variables, depending on memory available in the system.

min - minimum size of the receive buffer used by each TCP socket. The default value is 4K, and is lowered to PAGE_SIZE bytes in low-memory systems. This value is used to ensure that in memory pressure mode, allocations below this size will still succeed. This is not used to bound the size of the receive buffer declared using SO_RCVBUF on a socket.

default - the default size of the receive buffer for a TCP socket. This value overwrites the initial default buffer size from the generic global net.core.rmem_default defined for all protocols. The default value is 87380 bytes, and is lowered to 43689 in low-memory systems. If larger receive buffer sizes are desired, this value should be increased (to affect all sockets). To employ large TCP windows, the net.ipv4.tcp_window_scaling must be enabled (default).

max - the maximum size of the receive buffer used by each TCP socket. This value does not override the global net.core.rmem_max. This is not used to limit the size of the receive buffer declared using SO_RCVBUF on a socket. The default value of 87380*2 bytes is lowered to 87380 in low-memory systems.

tcp_sack (Boolean; default: enabled)
Enable RFC 2018 TCP Selective Acknowledgements.
tcp_stdurg (Boolean; default: disabled)
If this option is enabled, then use the RFC 1122 interpretation of the TCP urgent-pointer field. According to this interpretation, the urgent pointer points to the last byte of urgent data. If this option is disabled, then use the BSD-compatible interpretation of the urgent pointer: the urgent pointer points to the first byte after the urgent data. Enabling this option may lead to interoperability problems.
tcp_synack_retries (integer; default: 5)
The maximum number of times a SYN/ACK segment for a passive TCP connection will be retransmitted. This number should not be higher than 255.
tcp_syncookies (Boolean)
Enable TCP syncookies. The kernel must be compiled with CONFIG_SYN_COOKIES. Send out syncookies when the syn backlog queue of a socket overflows. The syncookies feature attempts to protect a socket from a SYN flood attack. This should be used as a last resort, if at all. This is a violation of the TCP protocol, and conflicts with other areas of TCP such as TCP extensions. It can cause problems for clients and relays. It is not recommended as a tuning mechanism for heavily loaded servers to help with overloaded or misconfigured conditions. For recommended alternatives see tcp_max_syn_backlog, tcp_synack_retries, and tcp_abort_on_overflow.
tcp_syn_retries (integer; default: 5)
The maximum number of times initial SYNs for an active TCP connection attempt will be retransmitted. This value should not be higher than 255. The default value is 5, which corresponds to approximately 180 seconds.
tcp_timestamps (Boolean; default: enabled)
Enable RFC 1323 TCP timestamps.
tcp_tw_recycle (Boolean; default: disabled)
Enable fast recycling of TIME-WAIT sockets. Enabling this option is not recommended since this causes problems when working with NAT (Network Address Translation).
tcp_tw_reuse (Boolean; default: disabled)
Allow to reuse TIME-WAIT sockets for new connections when it is safe from protocol viewpoint. It should not be changed without advice/request of technical experts.
tcp_window_scaling (Boolean; default: enabled)
Enable RFC 1323 TCP window scaling. This feature allows the use of a large window (> 64K) on a TCP connection, should the other end support it. Normally, the 16 bit window length field in the TCP header limits the window size to less than 64K bytes. If larger windows are desired, applications can increase the size of their socket buffers and the window scaling option will be employed. If tcp_window_scaling is disabled, TCP will not negotiate the use of window scaling with the other end during connection setup.
tcp_vegas_cong_avoid (Boolean; default: disabled)
Enable TCP Vegas congestion avoidance algorithm. TCP Vegas is a sender-side only change to TCP that anticipates the onset of congestion by estimating the bandwidth. TCP Vegas adjusts the sending rate by modifying the congestion window. TCP Vegas should provide less packet loss, but it is not as aggressive as TCP Reno.
tcp_westwood (Boolean; default: disabled)
Enable TCP Westwood+ congestion control algorithm. TCP Westwood+ is a sender-side only modification of the TCP Reno protocol stack that optimizes the performance of TCP congestion control. It is based on end-to-end bandwidth estimation to set congestion window and slow start threshold after a congestion episode. Using this estimation, TCP Westwood+ adaptively sets a slow start threshold and a congestion window which takes into account the bandwidth used at the time congestion is experienced. TCP Westwood+ significantly increases fairness with respect to TCP Reno in wired networks and throughput over wireless links.
tcp_wmem
This is a vector of 3 integers: [min, default, max]. These parameters are used by TCP to regulate send buffer sizes. TCP dynamically adjusts the size of the send buffer from the default values listed below, in the range of these sysctl variables, depending on memory available.

min - minimum size of the send buffer used by each TCP socket. The default value is 4K bytes. This value is used to ensure that in memory pressure mode, allocations below this size will still succeed. This is not used to bound the size of the send buffer declared using SO_SNDBUF on a socket.

default - the default size of the send buffer for a TCP socket. This value overwrites the initial default buffer size from the generic global net.core.wmem_default defined for all protocols. The default value is 16K bytes. If larger send buffer sizes are desired, this value should be increased (to affect all sockets). To employ large TCP windows, the sysctl variable net.ipv4.tcp_window_scaling must be enabled (default).

max - the maximum size of the send buffer used by each TCP socket. This value does not override the global net.core.wmem_max. This is not used to limit the size of the send buffer declared using SO_SNDBUF on a socket. The default value is 128K bytes. It is lowered to 64K depending on the memory available in the system.

Socket Options

To set or get a TCP socket option, call getsockopt(2) to read or setsockopt(2) to write the option with the option level argument set to IPPROTO_TCP. In addition, most IPPROTO_IP socket options are valid on TCP sockets. For more information see ip(7).
TCP_CORK
If set, don't send out partial frames. All queued partial frames are sent when the option is cleared again. This is useful for prepending headers before calling sendfile(2), or for throughput optimization. As currently implemented, there is a 200 millisecond ceiling on the time for which output is corked by TCP_CORK. If this ceiling is reached, then queued data is automatically transmitted. This option can be combined with TCP_NODELAY only since Linux 2.5.71. This option should not be used in code intended to be portable.
TCP_DEFER_ACCEPT
Allows a listener to be awakened only when data arrives on the socket. Takes an integer value (seconds), this can bound the maximum number of attempts TCP will make to complete the connection. This option should not be used in code intended to be portable.
TCP_INFO
Used to collect information about this socket. The kernel returns a struct tcp_info as defined in the file /usr/include/linux/tcp.h. This option should not be used in code intended to be portable.
TCP_KEEPCNT
The maximum number of keepalive probes TCP should send before dropping the connection. This option should not be used in code intended to be portable.
TCP_KEEPIDLE
The time (in seconds) the connection needs to remain idle before TCP starts sending keepalive probes, if the socket option SO_KEEPALIVE has been set on this socket. This option should not be used in code intended to be portable.
TCP_KEEPINTVL
The time (in seconds) between individual keepalive probes. This option should not be used in code intended to be portable.
TCP_LINGER2
The lifetime of orphaned FIN_WAIT2 state sockets. This option can be used to override the system wide sysctl tcp_fin_timeout on this socket. This is not to be confused with the socket(7) level option SO_LINGER. This option should not be used in code intended to be portable.
TCP_MAXSEG
The maximum segment size for outgoing TCP packets. If this option is set before connection establishment, it also changes the MSS value announced to the other end in the initial packet. Values greater than the (eventual) interface MTU have no effect. TCP will also impose its minimum and maximum bounds over the value provided.
TCP_NODELAY
If set, disable the Nagle algorithm. This means that segments are always sent as soon as possible, even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, thereby avoiding the frequent sending of small packets, which results in poor utilization of the network. This option is overridden by TCP_CORK; however, setting this option forces an explicit flush of pending output, even if TCP_CORK is currently set.
TCP_QUICKACK
Enable quickack mode if set or disable quickack mode if cleared. In quickack mode, acks are sent immediately, rather than delayed if needed in accordance to normal TCP operation. This flag is not permanent, it only enables a switch to or from quickack mode. Subsequent operation of the TCP protocol will once again enter/leave quickack mode depending on internal protocol processing and factors such as delayed ack timeouts occurring and data transfer. This option should not be used in code intended to be portable.
TCP_SYNCNT
Set the number of SYN retransmits that TCP should send before aborting the attempt to connect. It cannot exceed 255. This option should not be used in code intended to be portable.
TCP_WINDOW_CLAMP
Bound the size of the advertised window to this value. The kernel imposes a minimum size of SOCK_MIN_RCVBUF/2. This option should not be used in code intended to be portable.

Ioctls

These following ioctl(2) calls return information in value. The correct syntax is:

int value;
error = ioctl(tcp_socket, ioctl_type, &value);

ioctl_type is one of the following:

SIOCINQ
Returns the amount of queued unread data in the receive buffer. The socket must not be in LISTEN state, otherwise an error (EINVAL) is returned.
SIOCATMARK
Returns true (i.e., value is non-zero) if the inbound data stream is at the urgent mark.

If the SO_OOBINLINE socket option is set, and SIOCATMARK returns true, then the next read from the socket will return the urgent data. If the SO_OOBINLINE socket option is not set, and SIOCATMARK returns true, then the next read from the socket will return the bytes following the urgent data (to actually read the urgent data requires the recv(MSG_OOB) flag).

Note that a read never reads across the urgent mark. If an application is informed of the presence of urgent data via select(2) (using the exceptfds argument) or through delivery of a SIGURG signal, then it can advance up to the mark using a loop which repeatedly tests SIOCATMARK and performs a read (requesting any number of bytes) as long as SIOCATMARK returns false.

SIOCOUTQ
Returns the amount of unsent data in the socket send queue. The socket must not be in LISTEN state, otherwise an error (EINVAL) is returned.

Error Handling

When a network error occurs, TCP tries to resend the packet. If it doesn't succeed after some time, either ETIMEDOUT or the last received error on this connection is reported.

Some applications require a quicker error notification. This can be enabled with the IPPROTO_IP level IP_RECVERR socket option. When this option is enabled, all incoming errors are immediately passed to the user program. Use this option with care --- it makes TCP less tolerant to routing changes and other normal network conditions.

ERRORS

EPIPE
The other end closed the socket unexpectedly or a read is executed on a shut down socket.
ETIMEDOUT
The other end didn't acknowledge retransmitted data after some time.
EAFNOTSUPPORT
Passed socket address type in sin_family was not AF_INET.

Any errors defined for ip(7) or the generic socket layer may also be returned for TCP.

VERSIONS

Support for Explicit Congestion Notification, zero-copy sendfile(2), reordering support and some SACK extensions (DSACK) were introduced in 2.4. Support for forward acknowledgement (FACK), TIME_WAIT recycling, per connection keepalive socket options and sysctls were introduced in 2.3.

The default values and descriptions for the sysctl variables given above are applicable for the 2.4 kernel.

NOTES

TCP has no real out-of-band data; it has urgent data. In Linux this means if the other end sends newer out-of-band data the older urgent data is inserted as normal data into the stream (even when SO_OOBINLINE is not set). This differs from BSD-based stacks.

Linux uses the BSD compatible interpretation of the urgent pointer field by default. This violates RFC 1122, but is required for interoperability with other stacks. It can be changed by the tcp_stdurg sysctl.

BUGS

Not all errors are documented.
IPv6 is not described.

SEE ALSO

accept(2), bind(2), connect(2), getsockopt(2), listen(2), recvmsg(2), sendfile(2), sendmsg(2), socket(2), sysctl(2), ip(7), socket(7)

RFC 793 for the TCP specification.
RFC 1122 for the TCP requirements and a description of the Nagle algorithm.
RFC 1323 for TCP timestamp and window scaling options.
RFC 1644 for a description of TIME_WAIT assassination hazards.
RFC 3168 for a description of Explicit Congestion Notification.
RFC 2581 for TCP congestion control algorithms.
RFC 2018 and RFC 2883 for SACK and extensions to SACK.


unicode(7)

UNICODE

Section: Linux Programmer's Manual (7)
Updated: 2001-05-11 Return to Main Contents

NAME

Unicode - the Universal Character Set

DESCRIPTION

The international standard ISO 10646 defines the Universal Character Set (UCS). UCS contains all characters of all other character set standards. It also guarantees round-trip compatibility, i.e., conversion tables can be built such that no information is lost when a string is converted from any other encoding to UCS and back.

UCS contains the characters required to represent practically all known languages. This includes not only the Latin, Greek, Cyrillic, Hebrew, Arabic, Armenian, and Georgian scripts, but also Chinese, Japanese and Korean Han ideographs as well as scripts such as Hiragana, Katakana, Hangul, Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam, Thai, Lao, Khmer, Bopomofo, Tibetan, Runic, Ethiopic, Canadian Syllabics, Cherokee, Mongolian, Ogham, Myanmar, Sinhala, Thaana, Yi, and others. For scripts not yet covered, research on how to best encode them for computer usage is still going on and they will be added eventually. This might eventually include not only Hieroglyphs and various historic Indo-European languages, but even some selected artistic scripts such as Tengwar, Cirth, and Klingon. UCS also covers a large number of graphical, typographical, mathematical and scientific symbols, including those provided by TeX, Postscript, APL, MS-DOS, MS-Windows, Macintosh, OCR fonts, as well as many word processing and publishing systems, and more are being added.

The UCS standard (ISO 10646) describes a 31-bit character set architecture consisting of 128 24-bit groups, each divided into 256 16-bit planes made up of 256 8-bit rows with 256 column positions, one for each character. Part 1 of the standard (ISO 10646-1) defines the first 65534 code positions (0x0000 to 0xfffd), which form the Basic Multilingual Plane (BMP), that is plane 0 in group 0. Part 2 of the standard (ISO 10646-2) adds characters to group 0 outside the BMP in several supplementary planes in the range 0x10000 to 0x10ffff. There are no plans to add characters beyond 0x10ffff to the standard, therefore of the entire code space, only a small fraction of group 0 will ever be actually used in the foreseeable future. The BMP contains all characters found in the commonly used other character sets. The supplemental planes added by ISO 10646-2 cover only more exotic characters for special scientific, dictionary printing, publishing industry, higher-level protocol and enthusiast needs.

The representation of each UCS character as a 2-byte word is referred to as the UCS-2 form (only for BMP characters), whereas UCS-4 is the representation of each character by a 4-byte word. In addition, there exist two encoding forms UTF-8 for backwards compatibility with ASCII processing software and UTF-16 for the backwards compatible handling of non-BMP characters up to 0x10ffff by UCS-2 software.

The UCS characters 0x0000 to 0x007f are identical to those of the classic US-ASCII character set and the characters in the range 0x0000 to 0x00ff are identical to those in ISO 8859-1 Latin-1.

COMBINING CHARACTERS

Some code points in UCS have been assigned to combining characters. These are similar to the non-spacing accent keys on a typewriter. A combining character just adds an accent to the previous character. The most important accented characters have codes of their own in UCS, however, the combining character mechanism allows us to add accents and other diacritical marks to any character. The combining characters always follow the character which they modify. For example, the German character Umlaut-A ("Latin capital letter A with diaeresis") can either be represented by the precomposed UCS code 0x00c4, or alternatively as the combination of a normal "Latin capital letter A" followed by a "combining diaeresis": 0x0041 0x0308.

Combining characters are essential for instance for encoding the Thai script or for mathematical typesetting and users of the International Phonetic Alphabet.

IMPLEMENTATION LEVELS

As not all systems are expected to support advanced mechanisms like combining characters, ISO 10646-1 specifies the following three implementation levels of UCS:
Level 1
Combining characters and Hangul Jamo (a variant encoding of the Korean script, where a Hangul syllable glyph is coded as a triplet or pair of vovel/consonant codes) are not supported.
Level 2
In addition to level 1, combining characters are now allowed for some languages where they are essential (e.g., Thai, Lao, Hebrew, Arabic, Devanagari, Malayalam, etc.).
Level 3
All UCS characters are supported.

The Unicode 3.0 Standard published by the Unicode Consortium contains exactly the UCS Basic Multilingual Plane at implementation level 3, as described in ISO 10646-1:2000. Unicode 3.1 added the supplemental planes of ISO 10646-2. The Unicode standard and technical reports published by the Unicode Consortium provide much additional information on the semantics and recommended usages of various characters. They provide guidelines and algorithms for editing, sorting, comparing, normalizing, converting and displaying Unicode strings.

UNICODE UNDER LINUX

Under GNU/Linux, the C type wchar_t is a signed 32-bit integer type. Its values are always interpreted by the C library as UCS code values (in all locales), a convention that is signaled by the GNU C library to applications by defining the constant __STDC_ISO_10646__ as specified in the ISO C 99 standard.

UCS/Unicode can be used just like ASCII in input/output streams, terminal communication, plaintext files, filenames, and environment variables in the ASCII compatible UTF-8 multi-byte encoding. To signal the use of UTF-8 as the character encoding to all applications, a suitable locale has to be selected via environment variables (e.g., "LANG=en_GB.UTF-8").

The nl_langinfo(CODESET) function returns the name of the selected encoding. Library functions such as wctomb(3) and mbsrtowcs(3) can be used to transform the internal wchar_t characters and strings into the system character encoding and back and wcwidth(3) tells, how many positions (0-2) the cursor is advanced by the output of a character.

Under Linux, in general only the BMP at implementation level 1 should be used at the moment. Up to two combining characters per base character for certain scripts (in particular Thai) are also supported by some UTF-8 terminal emulators and ISO 10646 fonts (level 2), but in general precomposed characters should be preferred where available (Unicode calls this Normalization Form C).

PRIVATE AREA

In the BMP, the range 0xe000 to 0xf8ff will never be assigned to any characters by the standard and is reserved for private usage. For the Linux community, this private area has been subdivided further into the range 0xe000 to 0xefff which can be used individually by any end-user and the Linux zone in the range 0xf000 to 0xf8ff where extensions are coordinated among all Linux users. The registry of the characters assigned to the Linux zone is currently maintained by H. Peter Anvin <Peter.Anvin@linux.org>.

LITERATURE

*
Information technology --- Universal Multiple-Octet Coded Character Set (UCS) --- Part 1: Architecture and Basic Multilingual Plane. International Standard ISO/IEC 10646-1, International Organization for Standardization, Geneva, 2000.

This is the official specification of UCS. Available as a PDF file on CD-ROM from http://www.iso.ch/.

*
The Unicode Standard, Version 3.0. The Unicode Consortium, Addison-Wesley, Reading, MA, 2000, ISBN 0-201-61633-5.
*
S. Harbison, G. Steele. C: A Reference Manual. Fourth edition, Prentice Hall, Englewood Cliffs, 1995, ISBN 0-13-326224-3.

A good reference book about the C programming language. The fourth edition covers the 1994 Amendment 1 to the ISO C 90 standard, which adds a large number of new C library functions for handling wide and multi-byte character encodings, but it does not yet cover ISO C 99, which improved wide and multi-byte character support even further.

*
Unicode Technical Reports.
http://www.unicode.org/unicode/reports/
*
Markus Kuhn: UTF-8 and Unicode FAQ for Unix/Linux.
http://www.cl.cam.ac.uk/~mgk25/unicode.html

Provides subscription information for the linux-utf8 mailing list, which is the best place to look for advice on using Unicode under Linux.

*
Bruno Haible: Unicode HOWTO.
ftp://ftp.ilog.fr/pub/Users/haible/utf8/Unicode-HOWTO.html

BUGS

When this man page was last revised, the GNU C Library support for UTF-8 locales was mature and XFree86 support was in an advanced state, but work on making applications (most notably editors) suitable for use in UTF-8 locales was still fully in progress. Current general UCS support under Linux usually provides for CJK double-width characters and sometimes even simple overstriking combining characters, but usually does not include support for scripts with right-to-left writing direction or ligature substitution requirements such as Hebrew, Arabic, or the Indic scripts. These scripts are currently only supported in certain GUI applications (HTML viewers, word processors) with sophisticated text rendering engines.

SEE ALSO

setlocale(3), charsets(7), utf-8(7)


bootparam(7)

BOOTPARAM

Section: Linux Programmer's Manual (7)
Updated: 1995-01-14 Return to Main Contents

NAME

bootparam - Introduction to boot time parameters of the Linux kernel

DESCRIPTION

The Linux kernel accepts certain `command line options' or `boot time parameters' at the moment it is started. In general this is used to supply the kernel with information about hardware parameters that the kernel would not be able to determine on its own, or to avoid/override the values that the kernel would otherwise detect.

When the kernel is booted directly by the BIOS (say from a floppy to which you copied a kernel using `cp zImage /dev/fd0'), you have no opportunity to specify any parameters. So, in order to take advantage of this possibility you have to use software that is able to pass parameters, like LILO or loadlin. For a few parameters one can also modify the kernel image itself, using rdev, see rdev(8) for further details.

The LILO program (LInux LOader) written by Werner Almesberger is the most commonly used. It has the ability to boot various kernels, and stores the configuration information in a plain text file. (See lilo(8) and lilo.conf(5).) LILO can boot DOS, OS/2, Linux, FreeBSD, UnixWare, etc., and is quite flexible.

The other commonly used Linux loader is `LoadLin' which is a DOS program that has the capability to launch a Linux kernel from the DOS prompt (with boot-args) assuming that certain resources are available. This is good for people that want to launch Linux from DOS.

It is also very useful if you have certain hardware which relies on the supplied DOS driver to put the hardware into a known state. A common example is `SoundBlaster Compatible' sound cards that require the DOS driver to twiddle a few mystical registers to put the card into a SB compatible mode. Booting DOS with the supplied driver, and then loading Linux from the DOS prompt with loadlin avoids the reset of the card that happens if one rebooted instead.

THE ARGUMENT LIST

The kernel command line is parsed into a list of strings (boot arguments) separated by spaces. Most of the boot args take the form of:
name[=value_1][,value_2]...[,value_10]

where `name' is a unique keyword that is used to identify what part of the kernel the associated values (if any) are to be given to. Note the limit of 10 is real, as the present code only handles 10 comma separated parameters per keyword. (However, you can re-use the same keyword with up to an additional 10 parameters in unusually complicated situations, assuming the setup function supports it.)

Most of the sorting goes on in linux/init/main.c. First, the kernel checks to see if the argument is any of the special arguments `root=', `nfsroot=', `nfsaddrs=', `ro', `rw', `debug' or `init'. The meaning of these special arguments is described below.

Then it walks a list of setup functions (contained in the bootsetups array) to see if the specified argument string (such as `foo') has been associated with a setup function (`foo_setup()') for a particular device or part of the kernel. If you passed the kernel the line foo=3,4,5,6 then the kernel would search the bootsetups array to see if `foo' was registered. If it was, then it would call the setup function associated with `foo' (foo_setup()) and hand it the arguments 3, 4, 5 and 6 as given on the kernel command line.

Anything of the form `foo=bar' that is not accepted as a setup function as described above is then interpreted as an environment variable to be set. A (useless?) example would be to use `TERM=vt100' as a boot argument.

Any remaining arguments that were not picked up by the kernel and were not interpreted as environment variables are then passed onto process one, which is usually the init program. The most common argument that is passed to the init process is the word `single' which instructs init to boot the computer in single user mode, and not launch all the usual daemons. Check the manual page for the version of init installed on your system to see what arguments it accepts.

GENERAL NON-DEVICE SPECIFIC BOOT ARGS

`init=...'

This sets the initial command to be executed by the kernel. If this is not set, or cannot be found, the kernel will try /sbin/init, then /etc/init, then /bin/init, then /bin/sh and panic if all of this fails.

`nfsaddrs=...'

This sets the nfs boot address to the given string. This boot address is used in case of a net boot.

`nfsroot=...'

This sets the nfs root name to the given string. If this string does not begin with '/' or ',' or a digit, then it is prefixed by `/tftpboot/'. This root name is used in case of a net boot.

`no387'

(Only when CONFIG_BUGi386 is defined.) Some i387 coprocessor chips have bugs that show up when used in 32 bit protected mode. For example, some of the early ULSI-387 chips would cause solid lockups while performing floating point calculations. Using the `no387' boot arg causes Linux to ignore the maths coprocessor even if you have one. Of course you must then have your kernel compiled with math emulation support!

`no-hlt'

(Only when CONFIG_BUGi386 is defined.) Some of the early i486DX-100 chips have a problem with the `hlt' instruction, in that they can't reliably return to operating mode after this instruction is used. Using the `no-hlt' instruction tells Linux to just run an infinite loop when there is nothing else to do, and to not halt the CPU. This allows people with these broken chips to use Linux.

`root=...'

This argument tells the kernel what device is to be used as the root filesystem while booting. The default of this setting is determined at compile time, and usually is the value of the root device of the system that the kernel was built on. To override this value, and select the second floppy drive as the root device, one would use `root=/dev/fd1'. (The root device can also be set using rdev(8).)

The root device can be specified symbolically or numerically. A symbolic specification has the form /dev/XXYN, where XX designates the device type (`hd' for ST-506 compatible hard disk, with Y in `a'-`d'; `sd' for SCSI compatible disk, with Y in `a'-`e'; `ad' for Atari ACSI disk, with Y in `a'-`e', `ez' for a Syquest EZ135 parallel port removable drive, with Y=`a', `xd' for XT compatible disk, with Y either `a' or `b'; `fd' for floppy disk, with Y the floppy drive number --- fd0 would be the DOS `A:' drive, and fd1 would be `B:'), Y the driver letter or number, and N the number (in decimal) of the partition on this device (absent in the case of floppies). Recent kernels allow many other types, mostly for CD-ROMs: nfs, ram, scd, mcd, cdu535, aztcd, cm206cd, gscd, sbpcd, sonycd, bpcd. (The type nfs specifies a net boot; ram refers to a ram disk.)

Note that this has nothing to do with the designation of these devices on your file system. The `/dev/' part is purely conventional.

The more awkward and less portable numeric specification of the above possible root devices in major/minor format is also accepted. (E.g., /dev/sda3 is major 8, minor 3, so you could use `root=0x803' as an alternative.)

`ro' and `rw'

The `ro' option tells the kernel to mount the root filesystem as `readonly' so that filesystem consistency check programs (fsck) can do their work on a quiescent file system. No processes can write to files on the filesystem in question until it is `remounted' as read/write capable, for example, by `mount -w -n -o remount /'. (See also mount(8).)

The `rw' option tells the kernel to mount the root filesystem read/write. This is the default.

The choice between read-only and read/write can also be set using rdev(8).

`reserve=...'

This is used to protect I/O port regions from probes. The form of the command is:
reserve=iobase,extent[,iobase,extent]...

In some machines it may be necessary to prevent device drivers from checking for devices (auto-probing) in a specific region. This may be because of hardware that reacts badly to the probing, or hardware that would be mistakenly identified, or merely hardware you don't want the kernel to initialize.

The reserve boot-time argument specifies an I/O port region that shouldn't be probed. A device driver will not probe a reserved region, unless another boot argument explicitly specifies that it do so.

For example, the boot line

reserve=0x300,32 blah=0x300

keeps all device drivers except the driver for `blah' from probing 0x300-0x31f.

`mem=...'

The BIOS call defined in the PC specification that returns the amount of installed memory was only designed to be able to report up to 64MB. Linux uses this BIOS call at boot to determine how much memory is installed. If you have more than 64MB of RAM installed, you can use this boot arg to tell Linux how much memory you have. The value is in decimal or hexadecimal (prefix 0x), and the suffixes `k' (times 1024) or `M' (times 1048576) can be used. Here is a quote from Linus on usage of the `mem=' parameter.

``The kernel will accept any `mem=xx' parameter you give it, and if it turns out that you lied to it, it will crash horribly sooner or later. The parameter indicates the highest addressable RAM address, so `mem=0x1000000' means you have 16MB of memory, for example. For a 96MB machine this would be `mem=0x6000000'.

NOTE NOTE NOTE: some machines might use the top of memory for BIOS caching or whatever, so you might not actually have up to the full 96MB addressable. The reverse is also true: some chipsets will map the physical memory that is covered by the BIOS area into the area just past the top of memory, so the top-of-mem might actually be 96MB + 384kB for example. If you tell linux that it has more memory than it actually does have, bad things will happen: maybe not at once, but surely eventually.''

You can also use the boot argument `mem=nopentium' to turn off 4 MB page tables on kernels configured for IA32 systems with a pentium or newer CPU.

`panic=N'

By default the kernel will not reboot after a panic, but this option will cause a kernel reboot after N seconds (if N > 0). This panic timeout can also be set by "echo N > /proc/sys/kernel/panic".

`reboot=[warm|cold][,[bios|hard]]'

(Only when CONFIG_BUGi386 is defined.) Since 2.0.22 a reboot is by default a cold reboot. One asks for the old default with `reboot=warm'. (A cold reboot may be required to reset certain hardware, but might destroy not yet written data in a disk cache. A warm reboot may be faster.) By default a reboot is hard, by asking the keyboard controller to pulse the reset line low, but there is at least one type of motherboard where that doesn't work. The option `reboot=bios' will instead jump through the BIOS.

`nosmp' and `maxcpus=N'

(Only when __SMP__ is defined.) A command-line option of `nosmp' or `maxcpus=0' will disable SMP activation entirely; an option `maxcpus=N' limits the maximum number of CPUs activated in SMP mode to N.

BOOT ARGUMENTS FOR USE BY KERNEL DEVELOPERS

`debug'

Kernel messages are handed off to the kernel log daemon klogd so that they may be logged to disk. Messages with a priority above console_loglevel are also printed on the console. (For these levels, see <linux/kernel.h>.) By default this variable is set to log anything more important than debug messages. This boot argument will cause the kernel to also print the messages of DEBUG priority. The console loglevel can also be set at run time via an option to klogd. See klogd(8).

`profile=N'

It is possible to enable a kernel profiling function, if one wishes to find out where the kernel is spending its CPU cycles. Profiling is enabled by setting the variable prof_shift to a non-zero value. This is done either by specifying CONFIG_PROFILE at compile time, or by giving the `profile=' option. Now the value that prof_shift gets will be N, when given, or CONFIG_PROFILE_SHIFT, when that is given, or 2, the default. The significance of this variable is that it gives the granularity of the profiling: each clock tick, if the system was executing kernel code, a counter is incremented:
profile[address >> prof_shift]++;

The raw profiling information can be read from /proc/profile. Probably you'll want to use a tool such as readprofile.c to digest it. Writing to /proc/profile will clear the counters.

`swap=N1,N2,N3,N4,N5,N6,N7,N8'

Set the eight parameters max_page_age, page_advance, page_decline, page_initial_age, age_cluster_fract, age_cluster_min, pageout_weight, bufferout_weight that control the kernel swap algorithm. For kernel tuners only.

`buff=N1,N2,N3,N4,N5,N6'

Set the six parameters max_buff_age, buff_advance, buff_decline, buff_initial_age, bufferout_weight, buffermem_grace that control kernel buffer memory management. For kernel tuners only.

BOOT ARGUMENTS FOR RAMDISK USE

(Only if the kernel was compiled with CONFIG_BLK_DEV_RAM.) In general it is a bad idea to use a ramdisk under Linux --- the system will use available memory more efficiently itself. But while booting (or while constructing boot floppies) it is often useful to load the floppy contents into a ramdisk. One might also have a system in which first some modules (for filesystem or hardware) must be loaded before the main disk can be accessed.

In Linux 1.3.48, ramdisk handling was changed drastically. Earlier, the memory was allocated statically, and there was a `ramdisk=N' parameter to tell its size. (This could also be set in the kernel image at compile time, or by use of rdev(8).) These days ram disks use the buffer cache, and grow dynamically. For a lot of information (e.g., how to use rdev(8) in conjunction with the new ramdisk setup), see /usr/src/linux/Documentation/ramdisk.txt.

There are four parameters, two boolean and two integral.

`load_ramdisk=N'

If N=1, do load a ramdisk. If N=0, do not load a ramdisk. (This is the default.)

`prompt_ramdisk=N'

If N=1, do prompt for insertion of the floppy. (This is the default.) If N=0, do not prompt. (Thus, this parameter is never needed.)

`ramdisk_size=N' or (obsolete) `ramdisk=N'

Set the maximal size of the ramdisk(s) to N kB. The default is 4096 (4 MB).

`ramdisk_start=N'

Sets the starting block number (the offset on the floppy where the ramdisk starts) to N. This is needed in case the ramdisk follows a kernel image.

`noinitrd'

(Only if the kernel was compiled with CONFIG_BLK_DEV_RAM and CONFIG_BLK_DEV_INITRD.) These days it is possible to compile the kernel to use initrd. When this feature is enabled, the boot process will load the kernel and an initial ramdisk; then the kernel converts initrd into a "normal" ramdisk, which is mounted read-write as root device; then /linuxrc is executed; afterwards the "real" root file system is mounted, and the initrd filesystem is moved over to /initrd; finally the usual boot sequence (e.g., invocation of /sbin/init) is performed.

For a detailed description of the initrd feature, see /usr/src/linux/Documentation/initrd.txt.

The `noinitrd' option tells the kernel that although it was compiled for operation with initrd, it should not go through the above steps, but leave the initrd data under /dev/initrd. (This device can be used only once: the data is freed as soon as the last process that used it has closed /dev/initrd.)

BOOT ARGUMENTS FOR SCSI DEVICES

General notation for this section:

iobase -- the first I/O port that the SCSI host occupies. These are specified in hexadecimal notation, and usually lie in the range from 0x200 to 0x3ff.

irq -- the hardware interrupt that the card is configured to use. Valid values will be dependent on the card in question, but will usually be 5, 7, 9, 10, 11, 12, and 15. The other values are usually used for common peripherals like IDE hard disks, floppies, serial ports, etc.

scsi-id -- the ID that the host adapter uses to identify itself on the SCSI bus. Only some host adapters allow you to change this value, as most have it permanently specified internally. The usual default value is 7, but the Seagate and Future Domain TMC-950 boards use 6.

parity -- whether the SCSI host adapter expects the attached devices to supply a parity value with all information exchanges. Specifying a one indicates parity checking is enabled, and a zero disables parity checking. Again, not all adapters will support selection of parity behavior as a boot argument.

`max_scsi_luns=...'

A SCSI device can have a number of `sub-devices' contained within itself. The most common example is one of the new SCSI CD-ROMs that handle more than one disk at a time. Each CD is addressed as a `Logical Unit Number' (LUN) of that particular device. But most devices, such as hard disks, tape drives and such are only one device, and will be assigned to LUN zero.

Some poorly designed SCSI devices cannot handle being probed for LUNs not equal to zero. Therefore, if the compile time flag CONFIG_SCSI_MULTI_LUN is not set, newer kernels will by default only probe LUN zero.

To specify the number of probed LUNs at boot, one enters `max_scsi_luns=n' as a boot arg, where n is a number between one and eight. To avoid problems as described above, one would use n=1 to avoid upsetting such broken devices.

SCSI tape configuration

Some boot time configuration of the SCSI tape driver can be achieved by using the following:
st=buf_size[,write_threshold[,max_bufs]]

The first two numbers are specified in units of kB. The default buf_size is 32kB, and the maximum size that can be specified is a ridiculous 16384kB. The write_threshold is the value at which the buffer is committed to tape, with a default value of 30kB. The maximum number of buffers varies with the number of drives detected, and has a default of two. An example usage would be:

st=32,30,2

Full details can be found in the README.st file that is in the scsi directory of the kernel source tree.

Adaptec aha151x, aha152x, aic6260, aic6360, SB16-SCSI configuration

The aha numbers refer to cards and the aic numbers refer to the actual SCSI chip on these type of cards, including the Soundblaster-16 SCSI.

The probe code for these SCSI hosts looks for an installed BIOS, and if none is present, the probe will not find your card. Then you will have to use a boot arg of the form:

aha152x=iobase[,irq[,scsi-id[,reconnect[,parity]]]]

If the driver was compiled with debugging enabled, a sixth value can be specified to set the debug level.

All the parameters are as described at the top of this section, and the reconnect value will allow device disconnect/reconnect if a non-zero value is used. An example usage is as follows:

aha152x=0x340,11,7,1

Note that the parameters must be specified in order, meaning that if you want to specify a parity setting, then you will have to specify an iobase, irq, scsi-id and reconnect value as well.

Adaptec aha154x configuration

The aha1542 series cards have an i82077 floppy controller onboard, while the aha1540 series cards do not. These are busmastering cards, and have parameters to set the ``fairness'' that is used to share the bus with other devices. The boot arg looks like the following.
aha1542=iobase[,buson,busoff[,dmaspeed]]

Valid iobase values are usually one of: 0x130, 0x134, 0x230, 0x234, 0x330, 0x334. Clone cards may permit other values.

The buson, busoff values refer to the number of microseconds that the card dominates the ISA bus. The defaults are 11us on, and 4us off, so that other cards (such as an ISA LANCE Ethernet card) have a chance to get access to the ISA bus.

The dmaspeed value refers to the rate (in MB/s) at which the DMA (Direct Memory Access) transfers proceed. The default is 5MB/s. Newer revision cards allow you to select this value as part of the soft-configuration, older cards use jumpers. You can use values up to 10MB/s assuming that your motherboard is capable of handling it. Experiment with caution if using values over 5MB/s.

Adaptec aha274x, aha284x, aic7xxx configuration

These boards can accept an argument of the form:
aic7xxx=extended,no_reset

The extended value, if non-zero, indicates that extended translation for large disks is enabled. The no_reset value, if non-zero, tells the driver not to reset the SCSI bus when setting up the host adapter at boot.

AdvanSys SCSI Hosts configuration (`advansys=')

The AdvanSys driver can accept up to four i/o addresses that will be probed for an AdvanSys SCSI card. Note that these values (if used) do not effect EISA or PCI probing in any way. They are only used for probing ISA and VLB cards. In addition, if the driver has been compiled with debugging enabled, the level of debugging output can be set by adding an 0xdeb[0-f] parameter. The 0-f allows setting the level of the debugging messages to any of 16 levels of verbosity.

AM53C974

AM53C974=host-scsi-id,target-scsi-id,max-rate,max-offset

BusLogic SCSI Hosts configuration (`BusLogic=')

BusLogic=N1,N2,N3,N4,N5,S1,S2,...

For an extensive discussion of the BusLogic command line parameters, see /usr/src/linux/drivers/scsi/BusLogic.c (lines 3149-3270 in the kernel version I am looking at). The text below is a very much abbreviated extract.

The parameters N1-N5 are integers. The parameters S1,... are strings. N1 is the I/O Address at which the Host Adapter is located. N2 is the Tagged Queue Depth to use for Target Devices that support Tagged Queuing. N3 is the Bus Settle Time in seconds. This is the amount of time to wait between a Host Adapter Hard Reset which initiates a SCSI Bus Reset and issuing any SCSI Commands. N4 is the Local Options (for one Host Adapter). N5 is the Global Options (for all Host Adapters).

The string options are used to provide control over Tagged Queuing (TQ:Default, TQ:Enable, TQ:Disable, TQ:<Per-Target-Spec>), over Error Recovery (ER:Default, ER:HardReset, ER:BusDeviceReset, ER:None, ER:<Per-Target-Spec>), and over Host Adapter Probing (NoProbe, NoProbeISA, NoSortPCI).

EATA/DMA configuration

The default list of i/o ports to be probed can be changed by
eata=iobase,iobase,....

Future Domain TMC-16x0 configuration

fdomain=iobase,irq[,adapter_id]

Great Valley Products (GVP) SCSI controller configuration

gvp11=dma_transfer_bitmask

Future Domain TMC-8xx, TMC-950 configuration

tmc8xx=mem_base,irq

The mem_base value is the value of the memory mapped I/O region that the card uses. This will usually be one of the following values: 0xc8000, 0xca000, 0xcc000, 0xce000, 0xdc000, 0xde000.

IN2000 configuration

in2000=S

where S is a comma-separated string of items keyword[:value]. Recognized keywords (possibly with value) are: ioport:addr, noreset, nosync:x, period:ns, disconnect:x, debug:x, proc:x. For the function of these parameters, see /usr/src/linux/drivers/scsi/in2000.c.

NCR5380 and NCR53C400 configuration

The boot arg is of the form
ncr5380=iobase,irq,dma

or

ncr53c400=iobase,irq

If the card doesn't use interrupts, then an IRQ value of 255 (0xff) will disable interrupts. An IRQ value of 254 means to autoprobe. More details can be found in the file /usr/src/linux/drivers/scsi/README.g_NCR5380.

NCR53C8xx configuration

ncr53c8xx=S

where S is a comma-separated string of items keyword:value. Recognized keywords are: mpar (master_parity), spar (scsi_parity), disc (disconnection), specf (special_features), ultra (ultra_scsi), fsn (force_sync_nego), tags (default_tags), sync (default_sync), verb (verbose), debug (debug), burst (burst_max). For the function of the assigned values, see /usr/src/linux/drivers/scsi/ncr53c8xx.c.

NCR53c406a configuration

ncr53c406a=iobase[,irq[,fastpio]]

Specify irq = 0 for non-interrupt driven mode. Set fastpio = 1 for fast pio mode, 0 for slow mode.

Pro Audio Spectrum configuration

The PAS16 uses a NC5380 SCSI chip, and newer models support jumperless configuration. The boot arg is of the form:
pas16=iobase,irq

The only difference is that you can specify an IRQ value of 255, which will tell the driver to work without using interrupts, albeit at a performance loss. The iobase is usually 0x388.

Seagate ST-0x configuration

If your card is not detected at boot time, you will then have to use a boot arg of the form:
st0x=mem_base,irq

The mem_base value is the value of the memory mapped I/O region that the card uses. This will usually be one of the following values: 0xc8000, 0xca000, 0xcc000, 0xce000, 0xdc000, 0xde000.

Trantor T128 configuration

These cards are also based on the NCR5380 chip, and accept the following options:
t128=mem_base,irq

The valid values for mem_base are as follows: 0xcc000, 0xc8000, 0xdc000, 0xd8000.

UltraStor 14F/34F configuration

The default list of i/o ports to be probed can be changed by
eata=iobase,iobase,....

WD7000 configuration

wd7000=irq,dma,iobase

Commodore Amiga A2091/590 SCSI controller configuration

wd33c93=S

where S is a comma-separated string of options. Recognized options are nosync:bitmask, nodma:x, period:ns, disconnect:x, debug:x, clock:x, next. For details, see /usr/src/linux/drivers/scsi/wd33c93.c.

HARD DISKS

IDE Disk/CD-ROM Driver Parameters

The IDE driver accepts a number of parameters, which range from disk geometry specifications, to support for broken controller chips. Drive specific options are specified by using `hdX=' with X in `a'-`h'.

Non-drive specific options are specified with the prefix `hd='. Note that using a drive specific prefix for a non-drive specific option will still work, and the option will just be applied as expected.

Also note that `hd=' can be used to refer to the next unspecified drive in the (a, ..., h) sequence. For the following discussions, the `hd=' option will be cited for brevity. See the file README.ide in linux/drivers/block for more details.

The `hd=cyls,heads,sects[,wpcom[,irq]]' options

These options are used to specify the physical geometry of the disk. Only the first three values are required. The cylinder/head/sectors values will be those used by fdisk. The write precompensation value is ignored for IDE disks. The IRQ value specified will be the IRQ used for the interface that the drive resides on, and is not really a drive specific parameter.

The `hd=serialize' option

The dual IDE interface CMD-640 chip is broken as designed such that when drives on the secondary interface are used at the same time as drives on the primary interface, it will corrupt your data. Using this option tells the driver to make sure that both interfaces are never used at the same time.

The `hd=dtc2278' option

This option tells the driver that you have a DTC-2278D IDE interface. The driver then tries to do DTC specific operations to enable the second interface and to enable faster transfer modes.

The `hd=noprobe' option

Do not probe for this drive. For example,
hdb=noprobe hdb=1166,7,17

would disable the probe, but still specify the drive geometry so that it would be registered as a valid block device, and hence usable.

The `hd=nowerr' option

Some drives apparently have the WRERR_STAT bit stuck on permanently. This enables a work-around for these broken devices.

The `hd=cdrom' option

This tells the IDE driver that there is an ATAPI compatible CD-ROM attached in place of a normal IDE hard disk. In most cases the CD-ROM is identified automatically, but if it isn't then this may help.

Standard ST-506 Disk Driver Options (`hd=')

The standard disk driver can accept geometry arguments for the disks similar to the IDE driver. Note however that it only expects three values (C/H/S); any more or any less and it will silently ignore you. Also, it only accepts `hd=' as an argument, that is, `hda=' and so on are not valid here. The format is as follows:
hd=cyls,heads,sects

If there are two disks installed, the above is repeated with the geometry parameters of the second disk.

XT Disk Driver Options (`xd=')

If you are unfortunate enough to be using one of these old 8 bit cards that move data at a whopping 125kB/s then here is the scoop. If the card is not recognized, you will have to use a boot arg of the form:
xd=type,irq,iobase,dma_chan

The type value specifies the particular manufacturer of the card, overriding autodetection. For the types to use, consult the drivers/block/xd.c source file of the kernel you are using. The type is an index in the list xd_sigs and in the course of time types have been added to or deleted from the middle of the list, changing all type numbers. Today (Linux 2.5.0) the types are 0=generic; 1=DTC 5150cx; 2,3=DTC 5150x; 4,5=Western Digital; 6,7,8=Seagate; 9=Omti; 10=XEBEC, and where here several types are given with the same designation, they are equivalent.

The xd_setup() function does no checking on the values, and assumes that you entered all four values. Don't disappoint it. Here is an example usage for a WD1002 controller with the BIOS disabled/removed, using the `default' XT controller parameters:

xd=2,5,0x320,3

Syquest's EZ* removable disks

ez=iobase[,irq[,rep[,nybble]]]

IBM MCA BUS DEVICES

See also /usr/src/linux/Documentation/mca.txt.

PS/2 ESDI hard disks

It is possible to specify the desired geometry at boot time:
ed=cyls,heads,sectors.

For a ThinkPad-720, add the option

tp720=1.

IBM Microchannel SCSI Subsystem configuration

ibmmcascsi=N

where N is the pun (SCSI ID) of the subsystem.

The Aztech Interface

The syntax for this type of card is:
aztcd=iobase[,magic_number]

If you set the magic_number to 0x79 then the driver will try and run anyway in the event of an unknown firmware version. All other values are ignored.

Parallel port CD-ROM drives

Syntax:
pcd.driveN=prt,pro,uni,mod,slv,dly
pcd.nice=nice

where `port' is the base address, `pro' is the protocol number, `uni' is the unit selector (for chained devices), `mod' is the mode (or -1 to choose the best automatically), `slv' is 1 if it should be a slave, and `dly' is a small integer for slowing down port accesses. The `nice' parameter controls the driver's use of idle CPU time, at the expense of some speed.

The CDU-31A and CDU-33A Sony Interface

This CD-ROM interface is found on some of the Pro Audio Spectrum sound cards, and other Sony supplied interface cards. The syntax is as follows:
cdu31a=iobase,[irq[,is_pas_card]]

Specifying an IRQ value of zero tells the driver that hardware interrupts aren't supported (as on some PAS cards). If your card supports interrupts, you should use them as it cuts down on the CPU usage of the driver.

The is_pas_card should be entered as `PAS' if using a Pro Audio Spectrum card, and otherwise it should not be specified at all.

The CDU-535 Sony Interface

The syntax for this CD-ROM interface is:
sonycd535=iobase[,irq]

A zero can be used for the I/O base as a `placeholder' if one wishes to specify an IRQ value.

The GoldStar Interface

The syntax for this CD-ROM interface is:
gscd=iobase

The ISP16 CD-ROM Interface

Syntax:
isp16=[iobase[,irq[,dma[,type]]]]

(three integers and a string). If the type is given as `noisp16', the interface will not be configured. Other recognized types are: `Sanyo", `Sony', `Panasonic' and `Mitsumi'.

The Mitsumi Standard Interface

The syntax for this CD-ROM interface is:
mcd=iobase,[irq[,wait_value]]

The wait_value is used as an internal timeout value for people who are having problems with their drive, and may or may not be implemented depending on a compile time #define. The Mitsumi FX400 is an IDE/ATAPI CD-ROM player and does not use the mcd driver.

The Mitsumi XA/MultiSession Interface

This is for the same hardware as above, but the driver has extended features. Syntax:
mcdx=iobase[,irq]

The Optics Storage Interface

The syntax for this type of card is:
optcd=iobase

The Phillips CM206 Interface

The syntax for this type of card is:
cm206=[iobase][,irq]

The driver assumes numbers between 3 and 11 are IRQ values, and numbers between 0x300 and 0x370 are I/O ports, so you can specify one, or both numbers, in any order. It also accepts `cm206=auto' to enable autoprobing.

The Sanyo Interface

The syntax for this type of card is:
sjcd=iobase[,irq[,dma_channel]]

The SoundBlaster Pro Interface

The syntax for this type of card is:
sbpcd=iobase,type

where type is one of the following (case sensitive) strings: `SoundBlaster', `LaserMate', or `SPEA'. The I/O base is that of the CD-ROM interface, and not that of the sound portion of the card.

ETHERNET DEVICES

Different drivers make use of different parameters, but they all at least share having an IRQ, an I/O port base value, and a name. In its most generic form, it looks something like this:
ether=irq,iobase[,param_1[,...param_8]],name

The first non-numeric argument is taken as the name. The param_n values (if applicable) usually have different meanings for each different card/driver. Typical param_n values are used to specify things like shared memory address, interface selection, DMA channel and the like.

The most common use of this parameter is to force probing for a second ethercard, as the default is to only probe for one. This can be accomplished with a simple:

ether=0,0,eth1

Note that the values of zero for the IRQ and I/O base in the above example tell the driver(s) to autoprobe.

The Ethernet-HowTo has extensive documentation on using multiple cards and on the card/driver specific implementation of the param_n values where used. Interested readers should refer to the section in that document on their particular card.

THE FLOPPY DISK DRIVER

There are many floppy driver options, and they are all listed in README.fd in linux/drivers/block. This information is taken directly from that file.

floppy=mask,allowed_drive_mask

Sets the bitmask of allowed drives to mask. By default, only units 0 and 1 of each floppy controller are allowed. This is done because certain non-standard hardware (ASUS PCI motherboards) mess up the keyboard when accessing units 2 or 3. This option is somewhat obsoleted by the cmos option.

floppy=all_drives

Sets the bitmask of allowed drives to all drives. Use this if you have more than two drives connected to a floppy controller.

floppy=asus_pci

Sets the bitmask to allow only units 0 and 1. (The default)

floppy=daring

Tells the floppy driver that you have a well behaved floppy controller. This allows more efficient and smoother operation, but may fail on certain controllers. This may speed up certain operations.

floppy=0,daring

Tells the floppy driver that your floppy controller should be used with caution.

floppy=one_fdc

Tells the floppy driver that you have only floppy controller (default)

floppy=two_fdc or floppy=address,two_fdc

Tells the floppy driver that you have two floppy controllers. The second floppy controller is assumed to be at address. If address is not given, 0x370 is assumed.

floppy=thinkpad

Tells the floppy driver that you have a Thinkpad. Thinkpads use an inverted convention for the disk change line.

floppy=0,thinkpad

Tells the floppy driver that you don't have a Thinkpad.

floppy=drive,type,cmos

Sets the cmos type of drive to type. Additionally, this drive is allowed in the bitmask. This is useful if you have more than two floppy drives (only two can be described in the physical cmos), or if your BIOS uses non-standard CMOS types. Setting the CMOS to 0 for the first two drives (default) makes the floppy driver read the physical cmos for those drives.

floppy=unexpected_interrupts

Print a warning message when an unexpected interrupt is received (default behavior)

floppy=no_unexpected_interrupts or floppy=L40SX

Don't print a message when an unexpected interrupt is received. This is needed on IBM L40SX laptops in certain video modes. (There seems to be an interaction between video and floppy. The unexpected interrupts only affect performance, and can safely be ignored.)

THE SOUND DRIVER

The sound driver can also accept boot args to override the compiled in values. This is not recommended, as it is rather complex. It is described in the Readme.Linux file, in linux/drivers/sound. It accepts a boot arg of the form:
sound=device1[,device2[,device3...[,device10]]]

where each deviceN value is of the following format 0xTaaaId and the bytes are used as follows:

T - device type: 1=FM, 2=SB, 3=PAS, 4=GUS, 5=MPU401, 6=SB16, 7=SB16-MPU401

aaa - I/O address in hex.

I - interrupt line in hex (i.e 10=a, 11=b, ...)

d - DMA channel.

As you can see it gets pretty messy, and you are better off to compile in your own personal values as recommended. Using a boot arg of `sound=0' will disable the sound driver entirely.

ISDN DRIVERS

The ICN ISDN driver

Syntax:
icn=iobase,membase,icn_id1,icn_id2

where icn_id1,icn_id2 are two strings used to identify the card in kernel messages.

The PCBIT ISDN driver

Syntax:
pcbit=membase1,irq1[,membase2,irq2]

where membaseN is the shared memory base of the N'th card, and irqN is the interrupt setting of the N'th card. The default is IRQ 5 and membase 0xD0000.

The Teles ISDN driver

Syntax:
teles=iobase,irq,membase,protocol,teles_id

where iobase is the i/o port address of the card, membase is the shared memory base address of the card, irq is the interrupt channel the card uses, and teles_id is the unique ASCII string identifier.

SERIAL PORT DRIVERS

The RISCom/8 Multiport Serial Driver (`riscom8=')

Syntax:
riscom=iobase1[,iobase2[,iobase3[,iobase4]]]

More details can be found in /usr/src/linux/Documentation/riscom8.txt.

The DigiBoard Driver (`digi=')

If this option is used, it should have precisely six parameters. Syntax:
digi=status,type,altpin,numports,iobase,membase

The parameters maybe given as integers, or as strings. If strings are used, then iobase and membase should be given in hexadecimal. The integer arguments (fewer may be given) are in order: status (Enable(1) or Disable(0) this card), type (PC/Xi(0), PC/Xe(1), PC/Xeve(2), PC/Xem(3)), altpin (Enable(1) or Disable(0) alternate pin arrangement), numports (number of ports on this card), iobase (I/O Port where card is configured (in HEX)), membase (base of memory window (in HEX)). Thus, the following two boot prompt arguments are equivalent:

digi=E,PC/Xi,D,16,200,D0000
digi=1,0,0,16,0x200,851968

More details can be found in /usr/src/linux/Documentation/digiboard.txt.

The Baycom Serial/Parallel Radio Modem

Syntax:
baycom=iobase,irq,modem

There are precisely 3 parameters; for several cards, give several `baycom=' commands. The modem parameter is a string that can take one of the values ser12, ser12*, par96, par96*. Here the * denotes that software DCD is to be used, and ser12/par96 chooses between the supported modem types. For more details, see /usr/src/linux/drivers/net/README.baycom.

Soundcard radio modem driver

Syntax:
soundmodem=iobase,irq,dma[,dma2[,serio[,pario]]],0,mode

All parameters except the last are integers; the dummy 0 is required because of a bug in the setup code. The mode parameter is a string with syntax hw:modem, where hw is one of sbc, wss, wssfdx and modem is one of afsk1200, fsk9600.

THE LINE PRINTER DRIVER

`lp='

Syntax:
lp=0
lp=auto
lp=reset
lp=port[,port...]

You can tell the printer driver what ports to use and what ports not to use. The latter comes in handy if you don't want the printer driver to claim all available parallel ports, so that other drivers (e.g., PLIP, PPA) can use them instead.

The format of the argument is multiple port names. For example, lp=none,parport0 would use the first parallel port for lp1, and disable lp0. To disable the printer driver entirely, one can use lp=0.

WDT500/501 driver

Syntax:
wdt=io,irq

MOUSE DRIVERS

`bmouse=irq'

The busmouse driver only accepts one parameter, that being the hardware IRQ value to be used.

`msmouse=irq'

And precisely the same is true for the msmouse driver.

ATARI mouse setup

atamouse=threshold[,y-threshold]

If only one argument is given, it is used for both x-threshold and y-threshold. Otherwise, the first argument is the x-threshold, and the second the y-threshold. These values must lie between 1 and 20 (inclusive); the default is 2.

VIDEO HARDWARE

`no-scroll'

This option tells the console driver not to use hardware scroll (where a scroll is effected by moving the screen origin in video memory, instead of moving the data). It is required by certain Braille machines.

SEE ALSO

lilo.conf(5), klogd(8), lilo(8), mount(8), rdev(8)

Large parts of this man page have been derived from the Boot Parameter HOWTO (version 1.0.1) written by Paul Gortmaker. More information may be found in this (or a more recent) HOWTO. An up-to-date source of information is /usr/src/linux/Documentation/kernel-parameters.txt.


ddp(7)

DDP

Section: Linux Programmer's Manual (7)
Updated: 1999-05-01 Return to Main Contents

NAME

ddp - Linux AppleTalk protocol implementation

SYNOPSIS

#include <sys/socket.h>
#include <netatalk/at.h>

ddp_socket = socket(PF_APPLETALK, SOCK_DGRAM, 0);
raw_socket = socket(PF_APPLETALK, SOCK_RAW, protocol);

DESCRIPTION

Linux implements the Appletalk protocols described in Inside Appletalk. Only the DDP layer and AARP are present in the kernel. They are designed to be used via the netatalk protocol libraries. This page documents the interface for those who wish or need to use the DDP layer directly.

The communication between Appletalk and the user program works using a BSD-compatible socket interface. For more information on sockets, see socket(7).

An AppleTalk socket is created by calling the socket(2) function with a PF_APPLETALK socket family argument. Valid socket types are SOCK_DGRAM to open a ddp socket or SOCK_RAW to open a raw socket. protocol is the Appletalk protocol to be received or sent. For SOCK_RAW you must specify ATPROTO_DDP.

Raw sockets may be only opened by a process with effective user ID 0 or when the process has the CAP_NET_RAW capability.

Address Format

An Appletalk socket address is defined as a combination of a network number, a node number, and a port number.

struct at_addr {
    u_short        s_net;
    u_char         s_node;
};

struct sockaddr_atalk {
    sa_family_t    sat_family;    /* address family */
    u_char         sat_port;      /* port */
    struct at_addr sat_addr;      /* net/node */
};

sat_family is always set to AF_APPLETALK. sat_port contains the port. The port numbers below 129 are known as reserved ports. Only processes with the effective user ID 0 or the CAP_NET_BIND_SERVICE capability may bind(2) to these sockets. sat_addr is the host address. The net member of struct at_addr contains the host network in network byte order. The value of AT_ANYNET is a wildcard and also implies "this network." The node member of struct at_addr contains the host node number. The value of AT_ANYNODE is a wildcard and also implies "this node." The value of ATADDR_BCAST is a link local broadcast address.

Socket Options

No protocol-specific socket options are supported.

Sysctls

IP supports a sysctl interface to configure some global AppleTalk parameters. The sysctls can be accessed by reading or writing the /proc/sys/net/atalk/* files or with the sysctl(2) interface.
aarp-expiry-time
The time interval (in seconds) before an AARP cache entry expires.
aarp-resolve-time
The time interval (in seconds) before an AARP cache entry is resolved.
aarp-retransmit-limit
The number of retransmissions of an AARP query before the node is declared dead.
aarp-tick-time
The timer rate (in seconds) for the timer driving AARP.

The default values match the specification and should never need to be changed.

Ioctls

All ioctls described in socket(7) apply to ddp.

ERRORS

ENOTCONN
The operation is only defined on a connected socket, but the socket wasn't connected.
EINVAL
Invalid argument passed.
EMSGSIZE
Datagram is bigger than the DDP MTU.
EACCES
The user tried to execute an operation without the necessary permissions. These include sending to a broadcast address without having the broadcast flag set, and trying to bind to a reserved port without effective user ID 0 or CAP_NET_BIND_SERVICE.
EADDRINUSE
Tried to bind to an address already in use.
ENOMEM and ENOBUFS
Not enough memory available.
ENOPROTOOPT and EOPNOTSUPP
Invalid socket option passed.
EPERM
User doesn't have permission to set high priority, make a configuration change, or send signals to the requested process or group,
EADDRNOTAVAIL
A non-existent interface was requested or the requested source address was not local.
EAGAIN
Operation on a nonblocking socket would block.
ESOCKTNOSUPPORT
The socket was unconfigured, or an unknown socket type was requested.
EISCONN
connect(2) was called on an already connected socket.
EALREADY
A connection operation on a non-blocking socket is already in progress.
ECONNABORTED
A connection was closed during an accept(2).
EPIPE
The connection was unexpectedly closed or shut down by the other end.
ENOENT
SIOCGSTAMP was called on a socket where no packet arrived.
EHOSTUNREACH
No routing table entry matches the destination address.
ENODEV
Network device not available or not capable of sending IP.
ENOPKG
A kernel subsystem was not configured.

VERSIONS

Appletalk is supported by Linux 2.0 or higher. The sysctl interface is new in Linux 2.2.

NOTES

Be very careful with the SO_BROADCAST option - it is not privileged in Linux. It is easy to overload the network with careless sending to broadcast addresses.

Compatibility

The basic AppleTalk socket interface is compatible with netatalk on BSD-derived systems. Many BSD systems fail to check SO_BROADCAST when sending broadcast frames; this can lead to compatibility problems.

The raw socket mode is unique to Linux and exists to support the alternative CAP package and AppleTalk monitoring tools more easily.

BUGS

There are too many inconsistent error values.

The ioctls used to configure routing tables, devices, AARP tables and other devices are not yet described.

SEE ALSO

recvmsg(2), sendmsg(2), capabilities(7), socket(7)


icmp(7)

ICMP

Section: Linux Programmer's Manual (7)
Updated: 1999-04-27 Return to Main Contents

NAME

icmp, IPPROTO_ICMP - Linux IPv4 ICMP kernel module.

DESCRIPTION

This kernel protocol module implements the Internet Control Message Protocol defined in RFC 792. It is used to signal error conditions and for diagnosis. The user doesn't interact directly with this module; instead it communicates with the other protocols in the kernel and these pass the ICMP errors to the application layers. The kernel ICMP module also answers ICMP requests.

A user protocol may receive ICMP packets for all local sockets by opening a raw socket with the protocol IPPROTO_ICMP. See raw(7) for more information. The types of ICMP packets passed to the socket can be filtered using the ICMP_FILTER socket option. ICMP packets are always processed by the kernel too, even when passed to a user socket.

Linux limits the rate of ICMP error packets to each destination. ICMP_REDIRECT and ICMP_DEST_UNREACH are also limited by the destination route of the incoming packets.

Sysctls

ICMP supports a sysctl interface to configure some global IP parameters. The sysctls can be accessed by reading or writing the /proc/sys/net/ipv4/* files or with the sysctl(2) interface. Most of these sysctls are rate limitations for specific ICMP types. Linux 2.2 uses a token bucket filter to limit ICMPs. The value is the timeout in jiffies until the token bucket filter is cleared after a burst. A jiffy is a system dependent unit, usually 10ms on x86 and about 1ms on alpha and IA64.
icmp_destunreach_rate
Maximum rate to send ICMP Destination Unreachable packets. This limits the rate at which packets are sent to any individual route or destination. The limit does not affect sending of ICMP_FRAG_NEEDED packets needed for path MTU discovery.
icmp_echo_ignore_all
If this value is non-zero, Linux will ignore all ICMP_ECHO requests.
icmp_echo_ignore_broadcasts
If this value is non-zero, Linux will ignore all ICMP_ECHO packets sent to broadcast addresses.
icmp_echoreply_rate
Maximum rate for sending ICMP_ECHOREPLY packets in response to ICMP_ECHOREQUEST packets.
icmp_paramprob_rate
Maximum rate for sending ICMP_PARAMETERPROB packets. These packets are sent when a packet arrives with an invalid IP header.
icmp_timeexceed_rate
Maximum rate for sending ICMP_TIME_EXCEEDED packets. These packets are sent to prevent loops when a packet has crossed too many hops.

VERSIONS

Support for the ICMP_ADDRESS request was removed in 2.2.

Support for ICMP_SOURCE_QUENCH was removed in Linux 2.2.

NOTES

As many other implementations don't support IPPROTO_ICMP raw sockets, this feature should not be relied on in portable programs.

ICMP_REDIRECT packets are not sent when Linux is not acting as a router. They are also only accepted from the old gateway defined in the routing table and the redirect routes are expired after some time.

The 64-bit timestamp returned by ICMP_TIMESTAMP is in milliseconds since January 1, 1970.

Linux ICMP internally uses a raw socket to send ICMPs. This raw socket may appear in netstat(8) output with a zero inode.

SEE ALSO

ip(7)

RFC 792 for a description of the ICMP protocol.


intro(7)

INTRO

Section: Linux Programmer's Manual (7)
Updated: 1993-04-23 Return to Main Contents

NAME

intro - Introduction to overview, conventions, and miscellany section

DESCRIPTION

This chapter provides overviews on various topics, and describes conventions and protocols, character set standards, the standard file system layout, and miscellaneous other things.

Authors and Copyright Conditions

Look at the header of the manual page for the author(s) and copyright conditions. Note that these can be different from page to page!

SEE ALSO

standards(7)


netdevice(7)

NETDEVICE

Section: Linux Programmer's Manual (7)
Updated: 1999-05-02 Return to Main Contents

NAME

netdevice - Low level access to Linux network devices

SYNOPSIS

#include <sys/ioctl.h>
#include <net/if.h>

DESCRIPTION

This man page describes the sockets interface which is used to configure network devices.

Linux supports some standard ioctls to configure network devices. They can be used on any socket's file descriptor regardless of the family or type. They pass an ifreq structure:

struct ifreq {
    char ifr_name[IFNAMSIZ]; /* Interface name */
    union {
        struct sockaddr ifr_addr;
        struct sockaddr ifr_dstaddr;
        struct sockaddr ifr_broadaddr;
        struct sockaddr ifr_netmask;
        struct sockaddr ifr_hwaddr;
        short           ifr_flags;
        int             ifr_ifindex;
        int             ifr_metric;
        int             ifr_mtu;
        struct ifmap    ifr_map;
        char            ifr_slave[IFNAMSIZ];
        char            ifr_newname[IFNAMSIZ];
        char *          ifr_data;
    };
};

struct ifconf {
    int                ifc_len; /* size of buffer */
    union {
        char *         ifc_buf; /* buffer address */
        struct ifreq * ifc_req; /* array of structures */
    };
};

Normally, the user specifies which device to affect by setting ifr_name to the name of the interface. All other members of the structure may share memory.

Ioctls

If an ioctl is marked as privileged then using it requires an effective user ID of 0 or the CAP_NET_ADMIN capability. If this is not the case EPERM will be returned.
SIOCGIFNAME
Given the ifr_ifindex, return the name of the interface in ifr_name. This is the only ioctl which returns its result in ifr_name.
SIOCGIFINDEX
Retrieve the interface index of the interface into ifr_ifindex.
SIOCGIFFLAGS, SIOCSIFFLAGS
Get or set the active flag word of the device. ifr_flags contains a bitmask of the following values:
Device flags
IFF_UP Interface is running.
IFF_BROADCAST Valid broadcast address set.
IFF_DEBUG Internal debugging flag.
IFF_LOOPBACK Interface is a loopback interface.
IFF_POINTOPOINT Interface is a point-to-point link.
IFF_RUNNING Resources allocated.
IFF_NOARP No arp protocol, L2 destination address not set.
IFF_PROMISC Interface is in promiscuous mode.
IFF_NOTRAILERS Avoid use of trailers.
IFF_ALLMULTI Receive all multicast packets.
IFF_MASTER Master of a load balancing bundle.
IFF_SLAVE Slave of a load balancing bundle.
IFF_MULTICAST Supports multicast
IFF_PORTSEL Is able to select media type via ifmap.
IFF_AUTOMEDIA Auto media selection active.
IFF_DYNAMIC The addresses are lost when the interface goes down.
Setting the active flag word is a privileged operation, but any process may read it.
SIOCGIFMETRIC, SIOCSIFMETRIC
Get or set the metric of the device using ifr_metric. This is currently not implemented; it sets ifr_metric to 0 if you attempt to read it and returns EOPNOTSUPP if you attempt to set it.
SIOCGIFMTU, SIOCSIFMTU
Get or set the MTU (Maximum Transfer Unit) of a device using ifr_mtu. Setting the MTU is a privileged operation. Setting the MTU to too small values may cause kernel crashes.
SIOCGIFHWADDR, SIOCSIFHWADDR
Get or set the hardware address of a device using ifr_hwaddr. The hardware address is specified in a struct sockaddr. sa_family contains the ARPHRD_* device type, sa_data the L2 hardware address starting from byte 0. Setting the hardware address is a privileged operation.
SIOCSIFHWBROADCAST
Set the hardware broadcast address of a device from ifr_hwaddr. This is a privileged operation.
SIOCGIFMAP, SIOCSIFMAP
Get or set the interface's hardware parameters using ifr_map. Setting the parameters is a privileged operation.

struct ifmap {
    unsigned long   mem_start;
    unsigned long   mem_end;
    unsigned short  base_addr;
    unsigned char   irq;
    unsigned char   dma;
    unsigned char   port;
};

The interpretation of the ifmap structure depends on the device driver and the architecture.

SIOCADDMULTI, SIOCDELMULTI
Add an address to or delete an address from the device's link layer multicast filters using ifr_hwaddr. These are privileged operations. See also packet(7) for an alternative.
SIOCGIFTXQLEN, SIOCSIFTXQLEN
Get or set the transmit queue length of a device using ifr_qlen. Setting the transmit queue length is a privileged operation.
SIOCSIFNAME
Changes the name of the interface specified in ifr_name to ifr_newname. This is a privileged operation. It is only allowed when the interface is not up.
SIOCGIFCONF
Return a list of interface (transport layer) addresses. This currently means only addresses of the AF_INET (IPv4) family for compatibility. The user passes a ifconf structure as argument to the ioctl. It contains a pointer to an array of ifreq structures in ifc_req and its length in bytes in ifc_len. The kernel fills the ifreqs with all current L3 interface addresses that are running: ifr_name contains the interface name (eth0:1 etc.), ifr_addr the address. The kernel returns with the actual length in ifc_len. If ifc_len is equal to the original length the buffer probably has overflowed and you should retry with a bigger buffer to get all addresses. When no error occurs the ioctl returns 0; otherwise -1. Overflow is not an error.

Most protocols support their own ioctls to configure protocol specific interface options. See the protocol man pages for a description. For configuring IP addresses see ip(7).

In addition some devices support private ioctls. These are not described here.

NOTES

Strictly speaking, SIOCGIFCONF is IP specific and belongs in ip(7).

The names of interfaces with no addresses or that don't have the IFF_RUNNING flag set can be found via /proc/net/dev.

Local IPv6 IP addresses can be found via /proc/net or via rtnetlink(7).

BUGS

glibc 2.1 is missing the ifr_newname macro in net/if.h. Add the following to your program as a workaround:

#ifndef ifr_newname
#define ifr_newname     ifr_ifru.ifru_slave
#endif

SEE ALSO

proc(5), capabilities(7), ip(7), rtnetlink(7)


mdoc(7)

MDOC

Section: Environments, Tables, and Troff Macros (7) Return to Main Contents

BSD mandoc
Linux

NAME

mdoc - quick reference guide for the -mdoc macro package

SYNOPSIS

groff -m doc files ...

DESCRIPTION

The -mdoc package is a set of content-based and domain-based macros used to format the BSD man pages. The macro names and their meanings are listed below for quick reference; for a detailed explanation on using the package, see the tutorial sampler mdoc.samples7.

Note that this is not the usual macro package for Linux documentation, although it is used for documentation of several widely-used programs; see man(7).

The macros are described in two groups, the first includes the structural and physical page layout macros. The second contains the manual and general text domain macros which differentiate the -mdoc package from other troff formatting packages.

PAGE STRUCTURE DOMAIN

Title Macros

To create a valid manual page, these three macros, in this order, are required:

. Month day, year
Document date.
.
Title, in upper case.
. OPERATING_SYSTEM [version/release]
Operating system (BSD )

Page Layout Macros

Section headers, paragraph breaks, lists and displays.

.

Section Headers.

Valid headers, in the order of presentation:

NAME
Name section, should include the `.groff ' or `.Fn and ' the `. - macros. '
SYNOPSIS
Usage.
DESCRIPTION
General description, should include options and parameters.
RETURN VALUE
Sections two and three function calls.
ENVIRONMENT
Describe environment variables.
FILES
Files associated with the subject.
EXAMPLES
Examples and suggestions.
DIAGNOSTICS
Normally used for section four device interface diagnostics.
ERRORS
Sections two and three error and signal handling.
SEE ALSO
Cross references and citations.
CONFORMING TO
Conformance to standards if applicable.
HISTORY
If a standard is not applicable, the history of the subject should be given.
BUGS
Gotchas and caveats.
other
Customized headers may be added at the authors discretion.

Li .Ss Subsection Headers. Li .Pp Paragraph Break. Vertical space (one line). Li .D1 (D-one) Display-one Indent and display one text line. Li .Dl (D-ell) Display-one literal. Indent and display one line of literal text. Li .Bd Begin-display block. Display options:

-ragged
Unjustified (ragged edges).
-filled
Justified.
-literal
Literal text or code.
-file name
Read in named file and display.
-offset string
Offset display. Acceptable string values:

left
Align block on left (default).
center
Approximate center margin.
indent
Six constant width spaces (a tab).
indent-two
Two tabs.
right
Left aligns block 2 inches from right.
xx n
Where xx is a number from 4 n to 99 n
Aa Where
Aa is a callable macro name.
string
The width of string is used.

Li .Ed End-display (matches .Bd). Li .Bl Begin-list. Create lists or columns. Options:

List-types

-bullet Ta Bullet Item List
-item Ta Unlabeled List
-enum Ta Enumerated List
-tag Ta Tag Labeled List
-diag Ta Diagnostic List
-hang Ta Hanging Labeled List
-ohang Ta Overhanging Labeled List
-inset Ta Inset or Run-on Labeled List

List-parameters

-offset
(All lists.) See `. ' begin-display above.
-width
( -tag and -hang lists only.) See `. '
-compact
(All lists.) Suppresses blank lines.

Li .El End-list. Li .It List item.

MANUAL AND GENERAL TEXT DOMAIN MACROS

The manual and general text domain macros are special in that most of them are parsed for callable macros for example:

.[-s file ]
Produces [-s file ]

In this example, the option enclosure macro `.[is] ' parsed, and calls the callable content macro `- ' which operates on the argument `s' and then calls the callable content macro `file ... ' which operates on the argument `file' Some macros may be callable, but are not parsed and vice versa. These macros are indicated in the parsed and callable columns below.

Unless stated, manual domain macros share a common syntax:

.argument [ . , ; : ( ) [ ] argument ...]

Note Opening and closing punctuation characters are only recognized as such if they are presented one at a time. The string `),' is not recognized as punctuation and will be output with a leading white space and in what ever font the calling macro uses. The argument list `]' ) , is recognized as three sequential closing punctuation characters and a leading white space is not output between the characters and the previous argument (if any). The special meaning of a punctuation character may be escaped with the string `\&' For example the following string,

.file1 , file2 , file3 ) .
Produces file1 , file2 , file3 )

Manual Domain Macros

Name   Parsed  Callable        Description
Ta Yes Ta Yes Ta Address. (This macro may be deprecated.)
An Ta Yes Ta Yes Ta Author name.
Ta Yes Ta Yes Ta Command line argument.
Ta Ta Ta Configuration declaration (section four only).
Ta Yes Ta Yes Ta Command line argument modifier.
Ta Yes Ta Yes Ta Defined variable (source code).
Er Ta Yes Ta Yes Ta Error number (source code).
Ta Yes Ta Yes Ta Environment variable.
Fa Ta Yes Ta Yes Ta Function argument.
Fd Ta Yes Ta Yes Ta Function declaration.
Fn Ta Yes Ta Yes Ta Function call (also .Fo and .Fc).
Ta Yes Ta Yes Ta Interactive command.
Ta Yes Ta Yes Ta Literal text.
Ta Yes Ta Yes Ta Command name.
[Ta Yes Ta Yes Ta Option (also .[and .Oc). ]
Ot Ta Yes Ta Yes Ta Old style function type (Fortran only).
Ta Yes Ta Yes Ta Pathname or filename.
St Ta Yes Ta Yes Ta Standards (-p1003.2, -p1003.1 or -ansiC)
Ta Yes Ta Yes Ta Variable name.
Vt Ta Yes Ta Yes Ta Variable type (Fortran only).
TaYesTaYesTaManualPageCrossReference.

General Text Domain Macros

Name  Parsed  Callable        Description
%A Ta Yes Ta Ta Reference author.
%B Ta Yes Ta Yes Ta Reference book title.
%C Ta Ta Ta Reference place of publishing (city).
%D Ta Ta Ta Reference date.
%J Ta Yes Ta Yes Ta Reference journal title.
%N Ta Ta Ta Reference issue number.
%O Ta Ta Ta Reference optional information.
%P Ta Ta Ta Reference page number(s).
%R Ta Ta Ta Reference report Name.
%T Ta Yes Ta Yes Ta Reference article title.
%V Ta Ta Ta Reference volume.
Ac Ta Yes Ta Yes Ta Angle close quote.
Ao Ta Yes Ta Yes Ta Angle open quote.
Ap Ta Yes Ta Yes Ta Apostrophe.
Aq Ta Yes Ta Yes Ta Angle quote.
AT&T System Ta Ta Ta AT&T UNIX
Bc Ta Yes Ta Yes Ta Bracket close quote.
Bf Ta Ta Ta Begin font mode.
Bo Ta Yes Ta Yes Ta Bracket open quote.
Bq Ta Yes Ta Yes Ta Bracket quote.
BSD Ta Yes Ta Yes Ta BSD
Db Ta Ta Ta Debug (default is \*qoff\*q)
Dc Ta Yes Ta Yes Ta Double close quote.
Do Ta Yes Ta Yes Ta Double open quote.
``Ta Yes Ta Yes Ta Double quote. ''
Ec Ta Yes Ta Yes Ta Enclose string close quote.
Ef Ta Ta Ta End font mode.
Ta Yes Ta Yes Ta Emphasis (traditional English).
Eo Ta Yes Ta Yes Ta Enclose string open quote.
Fx Ta Ta Ta FreeBSD operating system
Ta Yes Ta Yes Ta Normal text (no-op).
Ta Yes Ta Yes Ta space.
Pc Ta Yes Ta Yes Ta Parenthesis close quote.
Ta Yes Ta Ta Prefix string.
Po Ta Yes Ta Yes Ta Parenthesis open quote.
(Ta Yes Ta Yes Ta Parentheses quote. )
Qc Ta Yes Ta Yes Ta Straight Double close quote.
`Ta Yes '
Ta Yes Ta Quoted literal.
Qo Ta Yes Ta Yes Ta Straight Double open quote.
Qq Ta Yes Ta Yes Ta Straight Double quote.
Li Rs Ta No Ta No Ta "Reference start." Li Rv Ta No Ta No Ta "Return values (sections two and three only)." Li Sc Ta Yes Ta Yes Ta "Single close quote." Li So Ta Yes Ta Yes Ta "Single open quote." Li Sq Ta Yes Ta Yes Ta "Single quote." Li Sm Ta No Ta No Ta "Space mode (default is \*qon\*q)" Li Sx Ta Yes Ta Yes Ta "Section Cross Reference." Li Sy Ta Yes Ta Yes Ta "Symbolic (traditional English)." Li Tn Ta Yes Ta Yes Ta "Trade or type name (small Caps)." Li Ux Ta Yes Ta Yes Ta Ux Li Xc Ta Yes Ta Yes Ta "Extend argument list close." Li Xo Ta Yes Ta Yes Ta "Extend argument list open."

Macro names ending in `q' quote remaining items on the argument list. Macro names ending in `o' begin a quote which may span more than one line of input and are close quoted with the matching macro name ending in `c' Enclosure macros may be nested and are limited to eight arguments.

Note: the extended argument list macros ( `. ' `. ' and the function enclosure macros ( `.Fo , ' `.Fc ) ' are irregular. The extended list macros are used when the number of macro arguments would exceed the troff limitation of nine arguments.

The macros UR (starting a URI/URL hypertext reference), UE (ending one), and UN (identifying a target for a reference) are also available. See man(7) for more information on these macros.

FILES

tmac.doc
Manual and general text domain macros.
tmac.doc-common
Common structural macros and definitions.
tmac.doc-nroff
Site dependent nroff style file.
tmac.doc-ditroff
Site dependent troff style file.
tmac.doc-syms
Special defines (such as the standards macro).

SEE ALSO

groff_mdoc7, mdoc.samples7, man(7), man-pages7


mdoc.samples(7)

MDOC.SAMPLES

Section: Environments, Tables, and Troff Macros (7) Return to Main Contents

BSD mandoc

NAME

mdoc.samples - tutorial sampler for writing BSD manuals with -mdoc

SYNOPSIS

man mdoc.samples

DESCRIPTION

A tutorial sampler for writing BSD manual pages with the -mdoc macro package, a content -based and domain -based formatting package for troff(1). Its predecessor, the -man7 package, addressed page layout leaving the manipulation of fonts and other typesetting details to the individual author. In -mdoc page layout macros make up the page structure domain which consists of macros for titles, section headers, displays and lists. Essentially items which affect the physical position of text on a formatted page. In addition to the page structure domain, there are two more domains, the manual domain and the general text domain. The general text domain is defined as macros which perform tasks such as quoting or emphasizing pieces of text. The manual domain is defined as macros that are a subset of the day to day informal language used to describe commands, routines and related BSD files. Macros in the manual domain handle command names, command line arguments and options, function names, function parameters, pathnames, variables, cross references to other manual pages, and so on. These domain items have value for both the author and the future user of the manual page. It is hoped the consistency gained across the manual set will provide easier translation to future documentation tools.

Throughout the UNIX manual pages, a manual entry is simply referred to as a man page, regardless of actual length and without sexist intention.

GETTING STARTED

Since a tutorial document is normally read when a person desires to use the material immediately, the assumption has been made that the user of this document may be impatient. The material presented in the remained of this document is outlined as follows:

  1. TROFF IDIOSYNCRASIES

    "Macro Usage"
    "Passing Space Characters in an Argument"
    "Trailing Blank Space Characters (a warning)"
    "Escaping Special Characters"

  2. THE ANATOMY OF A MAN PAGE

    "A manual page template"

  3. TITLE MACROS
  4. INTRODUCTION OF MANUAL AND GENERAL TEXT DOMAINS

    "What's in a name..."
    "General Syntax"

  5. MANUAL DOMAIN

    "Addresses"
    "Author name"
    "Arguments"
    "Configuration Declarations (section four only)"
    "Command Modifier"
    "Defined Variables"
    "Errno's (Section two only)"
    "Environment Variables"
    "Function Argument"
    "Function Declaration"
    "Flags"
    "Functions (library routines)"
    "Function Types"
    "Interactive Commands"
    "Names"
    "Options"
    "Pathnames"
    "Variables"
    "Cross References"

  6. GENERAL TEXT DOMAIN

    "AT&T Macro"
    "BSD Macro"
    "FreeBSD Macro"
    "UNIX Macro"
    "Enclosure/Quoting Macros"

    "Angle Bracket Quote/Enclosure"
    "Bracket Quotes/Enclosure"
    "Double Quote macro/Enclosure"
    "Parenthesis Quote/Enclosure"
    "Single Quotes/Enclosure"
    "Prefix Macro"

    "No-[or Normal Text Macro]
    "Space Macro
    "Section Cross References"
    "References and Citations"
    "Return Values (sections two and three only)"
    "Trade Names (Acronyms and Type Names)"
    "Extended Arguments"

  7. PAGE STRUCTURE DOMAIN

    "Section Headers"
    "Paragraphs and Line Spacing"
    "Keeps"
    "Displays"
    "Font Modes (Emphasis, Literal, and Symbolic)"
    "Lists and Columns"

  8. PREDEFINED STRINGS
  9. DIAGNOSTICS
  10. FORMATTING WITH GROFF, TROFF AND NROFF
  11. BUGS

TROFF IDIOSYNCRASIES

The -mdoc package attempts to simplify the process of writing a man page. Theoretically, one should not have to learn the dirty details of troff(1) to use -mdoc however, there are a few limitations which are unavoidable and best gotten out of the way. And, too, be forewarned, this package is not fast.

Macro Usage

As in troff(1), a macro is called by placing a `.' (dot character) at the beginning of a line followed by the two character name for the macro. Arguments may follow the macro separated by spaces. It is the dot character at the beginning of the line which causes troff(1) to interpret the next two characters as a macro name. To place a `.' (dot character) at the beginning of a line in some context other than a macro invocation, precede the `.' (dot) with the `\&' escape sequence. The `\&' translates literally to a zero width space, and is never displayed in the output.

In general, troff(1) macros accept up to nine arguments, any extra arguments are ignored. Most macros in -mdoc accept nine arguments and, in limited cases, arguments may be continued or extended on the next line (See Sx Extensions ) . A few macros handle quoted arguments (see Sx Passing Space Characters in an Argument below).

Most of the -mdoc general text domain and manual domain macros are special in that their argument lists are parsed for callable macro names. This means an argument on the argument list which matches a general text or manual domain macro name and is determined to be callable will be executed or called when it is processed. In this case the argument, although the name of a macro, is not preceded by a `.' (dot). It is in this manner that many macros are nested; for example the option macro, `.[,] ' may call the flag and argument macros, `- ' and `file ... ' to specify an optional flag with an argument:

[-s bytes ]
is produced by .[-s bytes ]

To prevent a two character string from being interpreted as a macro name, precede the string with the escape sequence `\&' :

[-s bytes ]
is produced by .[\&-s \&bytes ]

Here the strings `- ' and `file ... ' are not interpreted as macros. Macros whose argument lists are parsed for callable arguments are referred to as parsed and macros which may be called from an argument list are referred to as callable throughout this document and in the companion quick reference manual mdoc(7). This is a technical faux pas as almost all of the macros in -mdoc are parsed, but as it was cumbersome to constantly refer to macros as being callable and being able to call other macros, the term parsed has been used.

Passing Space Characters in an Argument

Sometimes it is desirable to give as one argument a string containing one or more blank space characters. This may be necessary to defeat the nine argument limit or to specify arguments to macros which expect particular arrangement of items in the argument list. For example, the function macro `.Fn expects ' the first argument to be the name of a function and any remaining arguments to be function parameters. As ANSI C stipulates the declaration of function parameters in the parenthesized parameter list, each parameter is guaranteed to be at minimum a two word string. For example, Fa int foo .

There are two possible ways to pass an argument which contains an embedded space. Implementation note Unfortunately, the most convenient way of passing spaces in between quotes by reassigning individual arguments before parsing was fairly expensive speed wise and space wise to implement in all the macros for AT&T troff. It is not expensive for groff but for the sake of portability, has been limited to the following macros which need it the most:

Configuration declaration (section 4
Sx SYNOPSIS )

Begin list (for the width specifier).
Emphasized text.
Fn Functions (sections two and four).
List items.
Literal text.
Symbolic text.
%B
Book titles.
%J
Journal names.
%O
Optional notes for a reference.
%R
Report title (in a reference).
%T
Title of article in a book or journal.

One way of passing a string containing blank spaces is to use the hard or unpaddable space character `\
,' that is, a blank space preceded by the escape character `\' This method may be used with any macro but has the side effect of interfering with the adjustment of text over the length of a line. Troff sees the hard space as if it were any other printable character and cannot split the string into blank or newline separated pieces as one would expect. The method is useful for strings which are not expected to overlap a line boundary. For example:

Fn fetch char *str
is created by `.Fn fetch ' char\ *str
Fn fetch char *str
can also be created by `.Fn fetch ' \*qchar *str\*q

If the `\' or quotes were omitted, `.Fn would ' see three arguments and the result would be:

Fn fetch char *str

For an example of what happens when the parameter list overlaps a newline boundary, see the Sx BUGS section.

Trailing Blank Space Characters

Troff can be confused by blank space characters at the end of a line. It is a wise preventive measure to globally remove all blank spaces from <blank-space><end-of-line> character sequences. Should the need arise to force a blank character at the end of a line, it may be forced with an unpaddable space and the `\&' escape character. For example, `string\\& .'

Escaping Special Characters

Special characters like the newline character `\n' , are handled by replacing the `\' with `\e' (e.g. `\en' ) to preserve the backslash.

THE ANATOMY OF A MAN PAGE

The body of a man page is easily constructed from a basic template found in the file /usr/share/misc/mdoc.template Several example man pages can also be found in /usr/share/examples/mdoc

A manual page template

.\" The following requests are required for all man pages.
.Dd Month day, year
.Os OPERATING_SYSTEM [version/release]
.Dt DOCUMENT_TITLE [section number] [volume]
.Sh NAME
.Nm name
.Nd one line description of name
.Sh SYNOPSIS
.Sh DESCRIPTION
.\" The following requests should be uncommented and
.\" used where appropriate.  This next request is
.\" for sections 2 and 3 function return values only.
.\" .Sh RETURN VALUE
.\" This next request is for sections 1, 6, 7 & 8 only
.\" .Sh ENVIRONMENT
.\" .Sh FILES
.\" .Sh EXAMPLES
.\" This next request is for sections 1, 6, 7 & 8 only
.\"     (command return values (to shell) and
.\"       fprintf/stderr type diagnostics)
.\" .Sh DIAGNOSTICS
.\" The next request is for sections 2 and 3 error
.\" and signal handling only.
.\" .Sh ERRORS
.\" .Sh SEE ALSO
.\" .Sh CONFORMING TO
.\" .Sh HISTORY
.\" .Sh AUTHORS
.\" .Sh BUGS

The first items in the template are the macros (., ., . ) the document date, the operating system the man page or subject source is developed or modified for, and the man page title (in upper case ) along with the section of the manual the page belongs in. These macros identify the page, and are discussed below in Sx TITLE MACROS .

The remaining items in the template are section headers (.

;

) of which Sx NAME , Sx SYNOPSIS and Sx DESCRIPTION are mandatory. The headers are discussed in Sx PAGE STRUCTURE DOMAIN , after presentation of Sx MANUAL DOMAIN . Several content macros are used to demonstrate page layout macros; reading about content macros before page layout macros is recommended.

TITLE MACROS

The title macros are the first portion of the page structure domain, but are presented first and separate for someone who wishes to start writing a man page yesterday. Three header macros designate the document title or manual page title, the operating system, and the date of authorship. These macros are one called once at the very beginning of the document and are used to construct the headers and footers only.

.
The document title is the subject of the man page and must be in CAPITALS due to troff limitations. The section number may be 1, ..., 8, and if it is specified, the volume title may be omitted. A volume title may be arbitrary or one of the following:

AMD    UNIX Ancestral Manual Documents
SMM  UNIX System Manager's Manual
URM     UNIX Reference Manual
PRMUNIX Programmer's Manual

The default volume labeling is
URM for sections 1, 6, and 7; SMM for section 8; PRM for sections 2, 3, 4, and 5.

.operating_system release#
The name of the operating system should be the common acronym, for example, BSD or FreeBSD or ATT The release should be the standard release nomenclature for the system specified, for example, 4.3, 4.3+Tahoe, V.3, V.4. Unrecognized arguments are displayed as given in the page footer. For instance, a typical footer might be:

.4.3BSD

or

.FreeBSD 2.2

or for a locally produced set

.CS Department

The Berkeley default, `.without ' an argument, has been defined as BSD in the site specific file /usr/share/tmac/mdoc/doc-common It really should default to LOCAL Note, if the `.macro ' is not present, the bottom left corner of the page will be ugly.

.month day, year
The date should be written formally:

January 25, 1989

INTRODUCTION OF MANUAL AND GENERAL TEXT DOMAINS

What's in a name...

The manual domain macro names are derived from the day to day informal language used to describe commands, subroutines and related files. Slightly different variations of this language are used to describe the three different aspects of writing a man page. First, there is the description of -mdoc macro request usage. Second is the description of a UNIX command with -mdoc macros and third, the description of a command to a user in the verbal sense; that is, discussion of a command in the text of a man page.

In the first case, troff(1) macros are themselves a type of command; the general syntax for a troff command is:

.Va argument1 argument2 ... argument9

The `.is ' a macro command or request, and anything following it is an argument to be processed. In the second case, the description of a UNIX command using the content macros is a bit more involved; a typical Sx SYNOPSIS command line might be displayed as:

filter [-flag ] infile outfile

Here, filter is the command name and the bracketed string -flag is a flag argument designated as optional by the option brackets. In -mdoc terms, infile and outfile are called arguments The macros which formatted the above example:

.Nm filter
.Op Fl flag
.Ar infile outfile

In the third case, discussion of commands and command syntax includes both examples above, but may add more detail. The arguments infile and outfile from the example above might be referred to as operands or file arguments Some command line argument lists are quite long:

make
[-eiknqrstv ] [-D variable ] [-d flags ] [-f makefile ] -words [-I directory ] [-j max_jobs ] [variable=value ] -words [target ... ]

Here one might talk about the command make and qualify the argument makefile as an argument to the flag, -f or discuss the optional file operand target In the verbal context, such detail can prevent confusion, however the -mdoc package does not have a macro for an argument to a flag. Instead the `file ... ' argument macro is used for an operand or file argument like target as well as an argument to a flag like variable The make command line was produced from:

.Nm make
.Op Fl eiknqrstv
.Op Fl D Ar variable
.Op Fl d Ar flags
.Op Fl f Ar makefile
.Op Fl I Ar directory
.Op Fl j Ar max_jobs
.Op Ar variable=value
.Bk -words
.Op Ar target ...
.Ek

The `.and ' `.macros ' are explained in Sx Keeps .

General Syntax

The manual domain and general text domain macros share a similar syntax with a few minor deviations: `.file ... ' `.- ' `.man mdoc.samples ' and `.differ ' only when called without arguments; `.Fn and ' `.impose ' an order on their argument lists and the `.[and] ' `.Fn macros ' have nesting limitations. All content macros are capable of recognizing and properly handling punctuation, provided each punctuation character is separated by a leading space. If an request is given:

.sptr, ptr),

The result is:

sptr, ptr),

The punctuation is not recognized and all is output in the literal font. If the punctuation is separated by a leading white space:

.sptr , ptr ) ,

The result is:

sptr , ptr

The punctuation is now recognized and is output in the default font distinguishing it from the strings in literal font.

To remove the special meaning from a punctuation character escape it with `\&' Troff is limited as a macro language, and has difficulty when presented with a string containing a member of the mathematical, logical or quotation set:

{+,-,/,*,%,<,>,<=,>=,=,==,&,`,',"}

The problem is that troff may assume it is supposed to actually perform the operation or evaluation suggested by the characters. To prevent the accidental evaluation of these characters, escape them with `\&' Typical syntax is shown in the first content macro displayed below, `. '

MANUAL DOMAIN

Address Macro

The address macro identifies an address construct of the form addr1[,addr2[,addr3]].

Usage: .address ...

.addr1
addr1
.addr1
addr1
.addr1 , file2
addr1 , file2
.f1 , f2 , f3:
f1 , f2 , f3
.addr ) ),
addr ) )

It is an error to call `.without ' arguments. `.is ' callable by other macros and is parsed.

Author Name

The `.An macro ' is used to specify the name of the author of the item being documented, or the name of the author of the actual manual page. Any remaining arguments after the name information are assumed to be punctuation.

Usage: .An author_name

.An Joe Author
An Joe Author
.An Joe Author,
An Joe Author ,
.An Joe Author Aq nobody@FreeBSD.ORG
An Joe Author Aq nobody@FreeBSD.ORG
.An Joe Author ) ),
An Joe Author ) ) ,

The `.An macro ' is parsed and is callable. It is an error to call `.An without ' any arguments.

Argument Macro

The `.file ... ' argument macro may be used whenever a command line argument is referenced.

Usage: .argument ...

.file ...
file ...
.file1
file1
.file1
file1
.file1 file2
file1 file2
.f1 f2 f3:
f1 f2 f3
.file ) ),
file ) )

If `.file ... ' is called without arguments `file ... ' is assumed. The `.file ... ' macro is parsed and is callable.

Configuration Declaration (section four only)

The `.macro ' is used to demonstrate a config(8) declaration for a device interface in a section four manual. This macro accepts quoted arguments (double quotes only).

device le0 at scode?
produced by: `.device ' le0 at scode? .

Command Modifier

The command modifier is identical to the `.- ' (flag) command with the exception the `.macro ' does not assert a dash in front of every argument. Traditionally flags are marked by the preceding dash, some commands or subsets of commands do not use them. Command modifiers may also be specified in conjunction with interactive commands such as editor commands. See Sx Flags .

Defined Variables

A variable which is defined in an include file is specified by the macro `. '

Usage: .defined_variable ...

.MAXHOSTNAMELEN
MAXHOSTNAMELEN
.TIOCGPGRP )
TIOCGPGRP

It is an error to call `.without ' arguments. `.is ' parsed and is callable.

Errno's (Section two only)

The `.Er errno ' macro specifies the error return value for section two library routines. The second example below shows `.Er used ' with the `.Bq general ' text domain macro, as it would be used in a section two manual page.

Usage: .Er ERRNOTYPE ...

.Er ENOENT
Er ENOENT
.Er ENOENT );
Er ENOENT ) ;
.Bq Er ENOTDIR
Bq Er ENOTDIR

It is an error to call `.Er without ' arguments. The `.Er macro ' is parsed and is callable.

Environment Variables

The `.macro ' specifies an environment variable.

Usage: .argument ...

.DISPLAY
DISPLAY
.PATH
PATH
.PRINTER ) ),
PRINTER ) )

It is an error to call `.without ' arguments. The `.macro ' is parsed and is callable.

Function Argument

The `.Fa macro ' is used to refer to function arguments (parameters) outside of the Sx SYNOPSIS section of the manual or inside the Sx SYNOPSIS section should a parameter list be too long for the `.Fn macro ' and the enclosure macros `.Fo and ' `.Fc must ' be used. `.Fa may ' also be used to refer to structure members.

Usage: .Fa function_argument ...

.Fa d_namlen ) ),
Fa d_namlen ) ) ,
.Fa iov_len
Fa iov_len

It is an error to call `.Fa without ' arguments. `.Fa is ' parsed and is callable.

Function Declaration

The `.Fd macro ' is used in the Sx SYNOPSIS section with section two or three functions. The `.Fd macro ' does not call other macros and is not callable by other macros.

Usage: .Fd include_file (or defined variable)

In the Sx SYNOPSIS section a `.Fd request ' causes a line break if a function has already been presented and a break has not occurred. This leaves a nice vertical space in between the previous function call and the declaration for the next function.

Flags

The `.- ' macro handles command line flags. It prepends a dash, `-' , to the flag. For interactive command flags, which are not prepended with a dash, the `.(command ' modifier) macro is identical, but without the dash.

Usage: .-argument ...

.-
-
.-cfv
-cfv
.-cfv
-cfv
.-s v t
-s v t
.--,
--
.-xyz ),
-xyz )

The `.- ' macro without any arguments results in a dash representing stdin/stdout. Note that giving `.- ' a single dash, will result in two dashes. The `.- ' macro is parsed and is callable.

Functions (library routines)

The .Fn macro is modeled on ANSI C conventions.
Usage: .Fn [type] function [[type] parameters ... ]

.Fn getchar
Fn getchar
.Fn strlen ) ,
Fn strlen ) ,
.Fn \*qint align\*q \*qconst * char *sptrs\*q
Fn int align const * char *sptrs ,

It is an error to call `.Fn without ' any arguments. The `.Fn macro ' is parsed and is callable, note that any call to another macro signals the end of the `.Fn call ' (it will close-parenthesis at that point).

For functions that have more than eight parameters (and this is rare), the macros `.Fo (function ' open) and `.Fc (function ' close) may be used with `.Fa (function ' argument) to get around the limitation. For example:

.Fo "int res_mkquery"
.Fa "int op"
.Fa "char *dname"
.Fa "int class"
.Fa "int type"
.Fa "char *data"
.Fa "int datalen"
.Fa "struct rrec *newrr"
.Fa "char *buf"
.Fa "int buflen"
.Fc

Produces:

Fo int res_mkquery Fa int op Fa char *dname Fa int class Fa int type Fa char *data Fa int datalen Fa struct rrec *newrr Fa char *buf Fa int buflen Fc

The `.Fo and ' `.Fc macros ' are parsed and are callable. In the Sx SYNOPSIS section, the function will always begin at the beginning of line. If there is more than one function presented in the Sx SYNOPSIS section and a function type has not been given, a line break will occur, leaving a nice vertical space between the current function name and the one prior. At the moment, `.Fn does ' not check its word boundaries against troff line lengths and may split across a newline ungracefully. This will be fixed in the near future.

Function Type

This macro is intended for the Sx SYNOPSIS section. It may be used anywhere else in the man page without problems, but its main purpose is to present the function type in kernel normal form for the Sx SYNOPSIS of sections two and three (it causes a line break allowing the function name to appear on the next line).

Usage: .Ft type ...

.Ft struct stat
Ft struct stat

The `.Ft request ' is not callable by other macros.

Interactive Commands

The `.macro ' designates an interactive or internal command.

Usage: .argument ...

.:wq
:wq
.do while {...}
do while {...}
.setenv , unsetenv
setenv , unsetenv

It is an error to call `.without ' arguments. The `.macro ' is parsed and is callable.

Name Macro

The `.man mdoc.samples ' macro is used for the document title or subject name. It has the peculiarity of remembering the first argument it was called with, which should always be the subject name of the page. When called without arguments, `.man mdoc.samples ' regurgitates this initial name for the sole purpose of making less work for the author. Note: a section two or three document function name is addressed with the `.man mdoc.samples ' in the Sx NAME section, and with `.Fn in ' the Sx SYNOPSIS and remaining sections. For interactive commands, such as the `while' command keyword in csh(1), the `.macro ' should be used. While the `.is ' nearly identical to `.man mdoc.samples ' it can not recall the first argument it was invoked with.

Usage: .argument ...

.mdoc.sample
mdoc.sample
.\-mdoc
-mdoc
.foo ) ),
foo ) )
.man mdoc.samples
man mdoc.samples

The `.man mdoc.samples ' macro is parsed and is callable.

Options

The `.[macro] ' places option brackets around the any remaining arguments on the command line, and places any trailing punctuation outside the brackets. The macros `.] ' and `.[may ' be used across one or more lines.

Usage: .[options ... ]

.[[
.[-k ]
] ]
[-k ]
.[-k ) . ]
[-k ]
.[-k kookfile ]
[-k kookfile ]
.[-k kookfile , ]
[-k kookfile ]
.[objfil [corfil ] ]
[objfil [corfil ] ]
.[-c objfil [corfil , ] ]
[-c objfil [corfil ] ]
.[word1 word2]
[word1 word2]

The `.] ' and `.[macros: '

.Oo
.Op Fl k Ar kilobytes
.Op Fl i Ar interval
.Op Fl c Ar count
.Oc

Produce: [[-k kilobytes ] [-i interval ] [-c count ] ]

The macros `.[,] ' `.] ' and `.[are ' parsed and are callable.

Pathnames

The `.macro ' formats pathnames or filenames.

Usage: .pathname

./usr/share
/usr/share
./tmp/fooXXXXX )
/tmp/fooXXXXX )

The `.macro ' is parsed and is callable.

Variables

Generic variable reference:

Usage: .variable ...

.count
count
.settimer
settimer
.int *prt ):
int *prt )
.char s ] ) ),
char s ] ) )

It is an error to call `.without ' any arguments. The `.macro ' is parsed and is callable.

Manual Page Cross References

The `.macro ' expects the first argument to be a manual page name, and the second argument, if it exists, to be either a section page number or punctuation. Any remaining arguments are assumed to be punctuation.

Usage: .man_page[1,...,8]

.mdoc
mdoc
.mdoc
mdoc,
.mdoc(7)
mdoc(7)
.mdoc(7)))
mdoc(7))),

The `.macro ' is parsed and is callable. It is an error to call `.without ' any arguments.

GENERAL TEXT DOMAIN

AT&T Macro

Usage: .At [v6 | v7 | 32v | V.1 | V.4] ...

.At
AT&T System
.AT&T System v6 .
AT&T System v6 .

The `.AT&T System ' macro is not parsed and not callable It accepts at most two arguments.

BSD Macro

Usage: .BSD [Version/release] ...

.Bx
BSD
.BSD 4.3 .
BSD 4.3

The `.BSD macro ' is parsed and is callable.

FreeBSD Macro

Usage: .Fx Version.release ...

.Fx 2.2 .
Fx 2.2 .

The `.Fx macro ' is not parsed and not callable It accepts at most two arguments.

UNIX Macro

Usage: .UNIX

.Ux
UNIX

The `.UNIX ' macro is parsed and is callable.

Enclosure and Quoting Macros

The concept of enclosure is similar to quoting. The object being to enclose one or more strings between a pair of characters like quotes or parentheses. The terms quoting and enclosure are used interchangeably throughout this document. Most of the one line enclosure macros end in small letter `q' to give a hint of quoting, but there are a few irregularities. For each enclosure macro there is also a pair of open and close macros which end in small letters `o' and `c' respectively. These can be used across one or more lines of text and while they have nesting limitations, the one line quote macros can be used inside of them.

Quote         Close   Open   Function        Result .Aq    .Ac     .Ao     Angle Bracket Enclosure<string>
.Bq     .Bc     .Bo     Bracket Enclosure       [string]
.Dq     .Dc     .Do     Double Quote    ``string''
        .Ec     .Eo     Enclose String (in XX)  XXstringXX
.Pq     .Pc     .Po     Parenthesis Enclosure   (string)
.Ql                     Quoted Literal  `st' or string
.Qq     .Qc     .Qo     Straight Double Quote   "string"
.Sq     .Sc     .So     Single Quote    `string'

Except for the irregular macros noted below, all of the quoting macros are parsed and callable. All handle punctuation properly, as long as it is presented one character at a time and separated by spaces. The quoting macros examine opening and closing punctuation to determine whether it comes before or after the enclosing string This makes some nesting possible.

.Ec , .Eo These macros expect the first argument to be the
opening and closing strings respectively.
.`The'
quoted literal macro behaves differently for troff than nroff. If formatted with nroff, a quoted literal is always quoted. If formatted with troff, an item is only quoted if the width of the item is less than three constant width characters. This is to make short strings more visible where the font change to literal (constant width) is less noticeable.
.The prefix macro is not callable, but it is parsed:

.( Fa name2
becomes ( Fa name2

The `.(no ' space) macro performs the analogous suffix function.

Examples of quoting:

.Aq Aq
.Aq ctype.h ),
Aq Ar ctype.h ) ,
.Bq Bq
.Bq Greek , French .
Bq Em Greek , French .
.````
.``string abc .''
'' ''
``string abc''
.``'^[A-Z]'''
``'^[A-Z]'''
.`man'
mdoc `man' mdoc
.Qq Qq
.Qq string ) ,
Qq string ) ,
.Qq string ),
Qq string Ns ),
.``
.`string'
' '
`string'

For a good example of nested enclosure macros, see the `.[option] ' macro. It was created from the same underlying enclosure macros as those presented in the list above. The `. ' and `. ' extended argument list macros were also built from the same underlying routines and are a good example of -mdoc macro usage at its worst.

No-[or Normal Text Macro]

The macro `.is ' a hack for words in a macro command line which should not be formatted and follows the conventional syntax for content macros.

Space Macro

The `.macro ' eliminates unwanted spaces in between macro requests. It is useful for old style argument lists where there is no space between the flag and argument:

.[-I directory ]
produces [-I directory ]

Note: the `.macro ' always invokes the `.macro ' after eliminating the space unless another macro name follows it. The macro `.is ' parsed and is callable.

Section Cross References

The `.Sx macro ' designates a reference to a section header within the same document. It is parsed and is callable.

.Sx FILES
Sx FILES

References and Citations

The following macros make a modest attempt to handle references. At best, the macros make it convenient to manually drop in a subset of refer style references.

.Rs
Reference Start. Causes a line break and begins collection of reference information until the reference end macro is read.
.Re
Reference End. The reference is printed.
.%A
Reference author name, one name per invocation.
.%B
Book title.
.%C
City/place.
.%D
Date.
.%J
Journal name.
.%N
Issue number.
.%O
Optional information.
.%P
Page number.
.%R
Report name.
.%T
Title of article.
.%V
Volume(s).

The macros beginning with `%' are not callable, and are parsed only for the trade name macro which returns to its caller. (And not very predictably at the moment either.) The purpose is to allow trade names to be pretty printed in troffNs/NsXrditroff output.

Return Values

The `.Rv macro ' generates text for use in the Sx RETURN VALUE section.

Usage: .Rv [-std function]

`.Rv -std ' atexit will generate the following text:

Rv -std atexit

The -std option is valid only for manual page sections 2 and 3.

Trade Names (or Acronyms and Type Names)

The trade name macro is generally a small caps macro for all upper case words longer than two characters.

Usage: .symbol ...

.DEC
DEC
.ASCII
ASCII

The `.macro ' is parsed and is callable by other macros.

Extended Arguments

The `. ' and `. ' macros allow one to extend an argument list on a macro boundary. Argument lists cannot be extended within a macro which expects all of its arguments on one line such as `.[] '

Here is an example of `. ' using the space mode macro to turn spacing off:

.Sm off
.It Xo Sy I Ar operation
.No \en Ar count No \en
.Xc
.Sm on

Produces

I operation \n count \n

Another one:
.Sm off
.It Cm S No / Ar old_pattern Xo
.No / Ar new_pattern
.No / Op Cm g
.Xc
.Sm on

Produces

S / old_pattern / new_pattern / [g ]

Another example of `. ' and using enclosure macros: Test the value of an variable.
.It Xo
.Ic .ifndef
.Oo \&! Oc Ns Ar variable
.Op Ar operator variable ...
.Xc

Produces

.ifndef [! variable ] [operator variable ... ]

All of the above examples have used the `. ' macro on the argument list of the `. ' (list-item) macro. The extend macros are not used very often, and when they are it is usually to extend the list-item argument list. Unfortunately, this is also where the extend macros are the most finicky. In the first two examples, spacing was turned off; in the third, spacing was desired in part of the output but not all of it. To make these macros work in this situation make sure the `. ' and `. ' macros are placed as shown in the third example. If the `. ' macro is not alone on the `. ' argument list, spacing will be unpredictable. The `.(no ' space macro) must not occur as the first or last macro on a line in this situation. Out of 900 manual pages (about 1500 actual pages) currently released with BSD only fifteen use the `. ' macro.

PAGE STRUCTURE DOMAIN

Section Headers

The first three `.

section

' header macros list below are required in every man page. The remaining section headers are recommended at the discretion of the author writing the manual page. The `.

macro

' can take up to nine arguments. It is parsed and but is not callable.

.

NAME

The `.

NAME

' macro is mandatory. If not specified, the headers, footers and page layout defaults will not be set and things will be rather unpleasant. The Sx NAME section consists of at least three items. The first is the `.man mdoc.samples ' name macro naming the subject of the man page. The second is the Name Description macro, `. - , ' which separates the subject name from the third item, which is the description. The description should be the most terse and lucid possible, as the space available is small. .Sh SYNOPSIS The Sx SYNOPSIS section describes the typical usage of the subject of a man page. The macros required are either `.Nm' , `.Cd' , `.Fn' , (and possibly `.Fo' , `.Fc' , `.Fd' , `.Ft' macros). The function name macro `.Fn' is required for manual page sections 2 and 3, the command and general name macro `.man mdoc.samples ' is required for sections 1, 5, 6, 7, 8. Section 4 manuals require a `.Nm' , `.Fd' or a `.Cd' configuration device usage macro. Several other macros may be necessary to produce the synopsis line as shown below:

cat [-benstuv ] [- ] file ...

The following macros were used:

.cat
.[-benstuv ]
.[- ]
.file ...

Note The macros `.[,] ' `.- ' and `.file ... ' recognize the pipe bar character `' so a command line such as:

".[-a | -b ]

will not go orbital. Troff normally interprets a as a special operator. See Sx PREDEFINED STRINGS for a usable character in other situations. .Sh DESCRIPTION In most cases the first text in the Sx DESCRIPTION section is a brief paragraph on the command, function or file, followed by a lexical list of options and respective explanations. To create such a list, the `.

' begin-list, `.

list-item '
and `.

' end-list macros are used (see Sx Lists and Columns below).

The following `.

section

' headers are part of the preferred manual page layout and must be used appropriately to maintain consistency. They are listed in the order in which they would be used.

.

ENVIRONMENT

The Sx ENVIRONMENT section should reveal any related environment variables and clues to their behavior and/or usage. .Sh EXAMPLES There are several ways to create examples. See the Sx EXAMPLES section below for details. .Sh FILES Files which are used or created by the man page subject should be listed via the `.macro ' in the Sx FILES section. .Sh SEE ALSO References to other material on the man page topic and cross references to other relevant man pages should be placed in the Sx SEE ALSO section. Cross references are specified using the `.macro. ' Cross references in the Sx SEE ALSO section should be sorted by section number, and then placed in alphabetical order and comma separated. For example:

ls(1),

ps(1),

group(5),

passwd(5).

At this time refer(1) style references are not accommodated. .Sh CONFORMING TO If the command, library function or file adheres to a specific implementation such as St -p1003.2 or St -ansiC this should be noted here. If the command does not adhere to any standard, its history should be noted in the Sx HISTORY section. .Sh HISTORY Any command which does not adhere to any specific standards should be outlined historically in this section. .Sh AUTHORS Credits, if need be, should be placed here. .Sh DIAGNOSTICS Diagnostics from a command should be placed in this section. .Sh ERRORS Specific error handling, especially from library functions (man page sections 2 and 3) should go here. The `.Er macro ' is used to specify an errno. .Sh BUGS Blatant problems with the topic go here...

User specified `.

sections

' may be added, for example, this section was set with:
.Sh PAGE STRUCTURE DOMAIN

Paragraphs and Line Spacing.

.

The `.

' paragraph command may be used to specify a line space where necessary. The macro is not necessary after a `.

or

' `.

macro

' or before a `.

' macro. (The `.

' macro asserts a vertical distance unless the -compact flag is given).

Keeps

The only keep that is implemented at this time is for words. The macros are `.(begin-keep) ' and `.(end-keep). ' The only option that `.accepts ' is -words and is useful for preventing line breaks in the middle of options. In the example for the make command line arguments (see Sx What's in a name ) , the keep prevented nroff from placing up the flag and the argument on separate lines. (Actually, the option macro used to prevent this from occurring, but was dropped when the decision (religious) was made to force right justified margins in troff as options in general look atrocious when spread across a sparse line. More work needs to be done with the keep macros, a -line option needs to be added.)

Examples and Displays

There are five types of displays, a quickie one line indented display `.D1' , a quickie one line literal display `.
,
' and a block literal, block filled and block ragged which use the `. ' begin-display and `. ' end-display macros.

.D1 (D-one) Display one line of indented text.
This macro is parsed, but it is not callable.

-ldghfstru

The above was produced by: .

-ldghfstru
.
(D-ell)
Display one line of indented literal text. The `.
example
' macro has been used throughout this file. It allows the indent (display) of one line of text. Its default font is set to constant width (literal) however it is parsed and will recognized other macros. It is not callable however.

% ls -ldg /usr/local/bin

The above was produced by .

% ls -ldg /usr/local/bin
.
Begin-display. The `. ' display must be ended with the `. ' macro. Displays may be nested within displays and lists. `. ' has the following syntax:

".

The display-type must be one of the following four types and may have an offset specifier for indentation: `. '

-ragged
Display a block of text as typed, right (and left) margin edges are left ragged.
-filled
Display a filled (formatted) block. The block of text is formatted (the edges are filled - not left unjustified).
-literal
Display a literal block, useful for source code or simple tabbed or spaced text.
-file file_name
The filename following the -file flag is read and displayed. Literal mode is asserted and tabs are set at 8 constant width character intervals, however any troff/NsNm-mdoc commands in file will be processed.
-offset string
If -offset is specified with one of the following strings, the string is interpreted to indicate the level of indentation for the forthcoming block of text:

left
Align block on the current left margin, this is the default mode of `. '
center
Supposedly center the block. At this time unfortunately, the block merely gets left aligned about an imaginary center margin.
indent
Indents by one default indent value or tab. The default indent value is also used for the `.D1' display so one is guaranteed the two types of displays will line up. This indent is normally set to 6n or about two thirds of an inch (six constant width characters).
indent-two
Indents two times the default indent value.
right
This left aligns the block about two inches from the right side of the page. This macro needs work and perhaps may never do the right thing by troff.

".Ed"
End-display.

Font Modes

There are five macros for changing the appearance of the manual page text:

.Text may be stressed or emphasized with the `.
macro. ' The usual font for emphasis is italic.

Usage: .argument ...

.does not does not
.exceed 1024 . exceed 1024
.vide infra ) ) , vide infra ) )

The `.macro ' is parsed and is callable. It is an error to call `.without ' arguments.
.The `.
literal ' macro may be used for special characters, variable constants, anything which should be displayed as it would be typed.

Usage: .argument ...

.\en \n
.M1 M2 M3; M1 M2 M3
.cntrl-D ), cntrl-D )
.1024 ... 1024 ...

The `.macro ' is parsed and is callable.
.The symbolic emphasis macro is generally a boldface macro in
either the symbolic sense or the traditional English usage.

Usage: .symbol ...

.Important Notice Important Notice

The `.macro ' is parsed and is callable. Arguments to `.may ' be quoted.
.Bf Begin font mode.
The `.Bf font ' mode must be ended with the `.Ef macro. ' Font modes may be nested within other font modes. `.Bf has ' the following syntax:

".Bf font-mode

The font-mode must be one of the following three types: `.Bf '

| -emphasis
Same as if the `.macro ' was used for the entire block of text.
| -literal
Same as if the `.macro ' was used for the entire block of text.
| -symbolic
Same as if the `.macro ' was used for the entire block of text.

".Ef"
End font mode.

Tagged Lists and Columns

There are several types of lists which may be initiated with the `.Bl' begin-list macro. Items within the list are specified with the `.It' item macro and each list must end with the `.El' macro. Lists may be nested within themselves and within displays. Columns may be used inside of lists, but lists are unproven inside of columns.

In addition, several list attributes may be specified such as the width of a tag, the list offset, and compactness (blank lines between items allowed or disallowed). Most of this document has been formatted with a tag style list (-tag ) For a change of pace, the list-type used to present the list-types is an over-hanging list (-ohang ) This type of list is quite popular with TeX users, but might look a bit funny after having read many pages of tagged lists. The following list types are accepted by `.Bl' :

-bullet
-item
-enum
These three are the simplest types of lists. Once the `.Bl' macro has been given, items in the list are merely indicated by a line consisting solely of the `.It' macro. For example, the source text for a simple enumerated list would look like:
.Bl -enum -compact
.It
Item one goes here.
.It
And item two here.
.It
Lastly item three goes here.
.El

The results:

  1. Item one goes here.
  2. And item two here.
  3. Lastly item three goes here.

A simple bullet list construction:

.Bl -bullet -compact
.It
Bullet one goes here.
.It
Bullet two here.
.El

Produces:

  • Bullet one goes here.
  • Bullet two here.

-tag
-diag
-hang
-ohang
-inset
These list-types collect arguments specified with the `.
macro '
and create a label which may be inset into the forthcoming text, hanged from the forthcoming text, overhanged from above and not indented or tagged This list was constructed with the `-ohang ' list-type. The `.
macro '
is parsed only for the inset, hang and tag list-types and is not callable. Here is an example of inset labels:

Tag
The tagged list (also called a tagged paragraph) is the most common type of list used in the Berkeley manuals.
Diag
Diag lists create section four diagnostic lists and are similar to inset lists except callable macros are ignored.
Hang
Hanged labels are a matter of taste.
Ohang
Overhanging labels are nice when space is constrained.
Inset
Inset labels are useful for controlling blocks of paragraphs and are valuable for converting -mdoc manuals to other formats.

Here is the source text which produced the above example:

.Bl -inset -offset indent
.It Em Tag
The tagged list (also called a tagged paragraph) is the
most common type of list used in the Berkeley manuals.
.It Em Diag
Diag lists create section four diagnostic lists
and are similar to inset lists except callable
macros are ignored.
.It Em Hang
Hanged labels are a matter of taste.
.It Em Ohang
Overhanging labels are nice when space is constrained.
.It Em Inset
Inset labels are useful for controlling blocks of
paragraphs and are valuable for converting
.Nm -mdoc
manuals to other formats.
.El

Here is a hanged list with two items:

Hanged
labels appear similar to tagged lists when the label is smaller than the label width.
Longer hanged list labels
blend in to the paragraph unlike tagged paragraph labels.

And the unformatted text which created it:

.Bl -hang -offset indent
.It Em Hanged
labels appear similar to tagged lists when the
label is smaller than the label width.
.It Em Longer hanged list labels
blend in to the paragraph unlike
tagged paragraph labels.
.El

The tagged list which follows uses an optional width specifier to control the width of the tag.

SL
sleep time of the process (seconds blocked)
PAGEIN
number of disk I/O 's resulting from references by the process to pages not loaded in core.
UID
numerical user-id of process owner
PPID
numerical ID of parent of process process priority (non-positive when in non-interruptible wait)

The raw text:

.Bl -tag -width "PAGEIN" -compact -offset indent
.It SL
sleep time of the process (seconds blocked)
.It PAGEIN
number of disk
.Tn I/O Ns 's
resulting from references
by the process to pages not loaded in core.
.It UID
numerical user ID of process owner
.It PPID
numerical ID of parent of process process priority
(non-positive when in non-interruptible wait)
.El

Acceptable width specifiers:

-width Fl
sets the width to the default width for a flag. All callable macros have a default width value. The `.- ' value is presently set to ten constant width characters or about five sixth of an inch.
-width 24n
sets the width to 24 constant width characters or about two inches. The `n' is absolutely necessary for the scaling to work correctly.
-width ENAMETOOLONG
sets width to the constant width length of the string given.
-width \*qint mkfifo\*q
again, the width is set to the constant width of the string given.

If a width is not specified for the tag list type, the first time `. ' is invoked, an attempt is made to determine an appropriate width. If the first argument to `.It' is a callable macro, the default width for that macro will be used as if the macro name had been supplied as the width. However, if another item in the list is given with a different callable macro name, a new and nested list is assumed.

PREDEFINED STRINGS

The following strings are predefined as may be used by preceding with the troff string interpreting sequence `\*(xx' where xx is the name of the defined string or as `\*x' where x is the name of the string. The interpreting sequence may be used any where in the text.

String        Nroff   Troff
<= Ta <= Ta
>= Ta >= Ta
Rq Ta '' Ta
Lq Ta `` Ta
ua Ta ^ Ta
aa Ta ' Ta
ga Ta ` Ta
q Ta Ta
Pi Ta pi Ta
Ne Ta != Ta
Le Ta <= Ta
Ge Ta >= Ta
Lt Ta < Ta
Gt Ta > Ta
Pm Ta +- Ta
If Ta infinity Ta
Na Ta NaN Ta
Ba Ta | Ta

Note

The string named `q' should be written as `\*q' since it is only one char.

DIAGNOSTICS

The debugging facilities for -mdoc are limited, but can help detect subtle errors such as the collision of an argument name with an internal register or macro name. (A what?) A register is an arithmetic storage class for troff with a one or two character name. All registers internal to -mdoc for troff and ditroff are two characters and of the form <upper_case><lower_case> such as `file ... ' <lower_case><upper_case> as `aR' or <upper or lower letter><digit> as `C1' And adding to the muddle, troff has its own internal registers all of which are either two lower case characters or a dot plus a letter or meta-character character. In one of the introduction examples, it was shown how to prevent the interpretation of a macro name with the escape sequence `\&' This is sufficient for the internal register names also.

If a non-escaped register name is given in the argument list of a request unpredictable behavior will occur. In general, any time huge portions of text do not appear where expected in the output, or small strings such as list tags disappear, chances are there is a misunderstanding about an argument type in the argument list. Your mother never intended for you to remember this evil stuff - so here is a way to find out whether or not your arguments are valid: The `.Db (debug) ' macro displays the interpretation of the argument list for most macros. Macros such as the `.

' (paragraph) macro do not contain debugging information. All of the callable macros do, and it is strongly advised whenever in doubt, turn on the `.Db macro. '

Usage: .Db [on | off]

An example of a portion of text with the debug macro placed above and below an artificially created problem (a flag argument `aC' which should be `\&aC' in order to work):

.Db on
.Op Fl aC Ar file )
.Db off

The resulting output:

DEBUGGING ON
DEBUG(argv) MACRO: `.Op'  Line #: 2
        Argc: 1  Argv: `Fl'  Length: 2
        Space: `'  Class: Executable
        Argc: 2  Argv: `aC'  Length: 2
        Space: `'  Class: Executable
        Argc: 3  Argv: `Ar'  Length: 2
        Space: `'  Class: Executable
        Argc: 4  Argv: `file'  Length: 4
        Space: ` '  Class: String
        Argc: 5  Argv: `)'  Length: 1
        Space: ` '  Class: Closing Punctuation or suffix
        MACRO REQUEST: .Op Fl aC Ar file )
DEBUGGING OFF

The first line of information tells the name of the calling macro, here `.[,] ' and the line number it appears on. If one or more files are involved (especially if text from another file is included) the line number may be bogus. If there is only one file, it should be accurate. The second line gives the argument count, the argument (`- ' ) and its length. If the length of an argument is two characters, the argument is tested to see if it is executable (unfortunately, any register which contains a non-zero value appears executable). The third line gives the space allotted for a class, and the class type. The problem here is the argument aC should not be executable. The four types of classes are string, executable, closing punctuation and opening punctuation. The last line shows the entire argument list as it was read. In this next example, the offending `aC' is escaped:

.Db on
.Em An escaped \&aC
.Db off

DEBUGGING ON
DEBUG(fargv) MACRO: `.Em'  Line #: 2
        Argc: 1  Argv: `An'  Length: 2
        Space: ` '  Class: String
        Argc: 2  Argv: `escaped'  Length: 7
        Space: ` '  Class: String
        Argc: 3  Argv: `aC'  Length: 2
        Space: ` '  Class: String
        MACRO REQUEST: .Em An escaped &aC
DEBUGGING OFF

The argument `\&aC' shows up with the same length of 2 as the `\&' sequence produces a zero width, but a register named `\&aC' was not found and the type classified as string.

Other diagnostics consist of usage statements and are self explanatory.

GROFF, TROFF AND NROFF

The -mdoc package does not need compatibility mode with groff.

The package inhibits page breaks, and the headers and footers which normally occur at those breaks with nroff, to make the manual more efficient for viewing on-line. At the moment, groff with -T ascii does eject the imaginary remainder of the page at end of file. The inhibiting of the page breaks makes nroffNs'd files unsuitable for hardcopy. There is a register named `cR' which can be set to zero in the site dependent style file /usr/src/share/tmac/doc-nroff to restore the old style behavior.

FILES

/usr/share/tmac/tmac.doc
manual macro package
/usr/share/misc/mdoc.template
template for writing a man page
/usr/share/examples/mdoc/*
several example man pages

BUGS

Undesirable hyphenation on the dash of a flag argument is not yet resolved, and causes occasional mishaps in the Sx DESCRIPTION section. (line break on the hyphen).

Predefined strings are not declared in documentation.

Section 3f has not been added to the header routines.

`.man mdoc.samples ' font should be changed in Sx NAME section.

`.Fn needs ' to have a check to prevent splitting up if the line length is too short. Occasionally it separates the last parenthesis, and sometimes looks ridiculous if a line is in fill mode.

The method used to prevent header and footer page breaks (other than the initial header and footer) when using nroff occasionally places an unsightly partially filled line (blank) at the would be bottom of the page.

The list and display macros to not do any keeps and certainly should be able to.

SEE ALSO

man(1), troff(1), groff_mdoc7, mdoc(7)


uri(7)

URI

Section: Linux Programmer's Manual (7)
Updated: 2000-03-14 Return to Main Contents

NAME

uri, url, urn - uniform resource identifier (URI), including a URL or URN

SYNOPSIS

URI = [ absoluteURI | relativeURI ] [ "#" fragment ]

absoluteURI = scheme ":" ( hierarchical_part | opaque_part )

relativeURI = ( net_path | absolute_path | relative_path ) [ "?" query ]

scheme = "http" | "ftp" | "gopher" | "mailto" | "news" | "telnet" | "file" | "man" | "info" | "whatis" | "ldap" | "wais" | ...

hierarchical_part = ( net_path | absolute_path ) [ "?" query ]

net_path = "//" authority [ absolute_path ]

absolute_path = "/"  path_segments

relative_path = relative_segment [ absolute_path ]

DESCRIPTION

A Uniform Resource Identifier (URI) is a short string of characters identifying an abstract or physical resource (for example, a web page). A Uniform Resource Locator (URL) is a URI that identifies a resource through its primary access mechanism (e.g., its network "location"), rather than by name or some other attribute of that resource. A Uniform Resource Name (URN) is a URI that must remain globally unique and persistent even when the resource ceases to exist or becomes unavailable.

URIs are the standard way to name hypertext link destinations for tools such as web browsers. The string "http://www.kernelnotes.org" is a URL (and thus it is also a URI). Many people use the term URL loosely as a synonym for URI (though technically URLs are a subset of URIs).

URIs can be absolute or relative. An absolute identifier refers to a resource independent of context, while a relative identifier refers to a resource by describing the difference from the current context. Within a relative path reference, the complete path segments "." and ".." have special meanings: "the current hierarchy level" and "the level above this hierarchy level", respectively, just like they do in Unix-like systems. A path segment which contains a colon character can't be used as the first segment of a relative URI path (e.g., "this:that"), because it would be mistaken for a scheme name; precede such segments with ./ (e.g., "./this:that"). Note that descendants of MS-DOS (e.g., Microsoft Windows) replace devicename colons with the vertical bar ("|") in URIs, so "C:" becomes "C|".

A fragment identifier, if included, refers to a particular named portion (fragment) of a resource; text after a '#' identifies the fragment. A URI beginning with '#' refers to that fragment in the current resource.

USAGE

There are many different URI schemes, each with specific additional rules and meanings, but they are intentionally made to be as similar as possible. For example, many URL schemes permit the authority to be the following format, called here an ip_server (square brackets show what's optional):
ip_server = [user [ : password ] @ ] host [ : port]

This format allows you to optionally insert a user name, a user plus password, and/or a port number. The host is the name of the host computer, either its name as determined by DNS or an IP address (numbers separated by periods). Thus the URI <http://fred:fredpassword@xyz.com:8080/> logs into a web server on host xyz.com as fred (using fredpassword) using port 8080. Avoid including a password in a URI if possible because of the many security risks of having a password written down. If the URL supplies a user name but no password, and the remote server requests a password, the program interpreting the URL should request one from the user.

Here are some of the most common schemes in use on Unix-like systems that are understood by many tools. Note that many tools using URIs also have internal schemes or specialized schemes; see those tools' documentation for information on those schemes.

http - Web (HTTP) server

http://ip_server/path
http://ip_server/path?query

This is a URL accessing a web (HTTP) server. The default port is 80. If the path refers to a directory, the web server will choose what to return; usually if there is a file named "index.html" or "index.htm" its content is returned, otherwise, a list of the files in the current directory (with appropriate links) is generated and returned. An example is <http://lwn.net>.

A query can be given in the archaic "isindex" format, consisting of a word or phrase and not including an equal sign (=). A query can also be in the longer "GET" format, which has one or more query entries of the form key=value separated by the ampersand character (&). Note that key can be repeated more than once, though it's up to the web server and its application programs to determine if there's any meaning to that. There is an unfortunate interaction with HTML/XML/SGML and the GET query format; when such URIs with more than one key are embedded in SGML/XML documents (including HTML), the ampersand (&) has to be rewritten as &amp;. Note that not all queries use this format; larger forms may be too long to store as a URI, so they use a different interaction mechanism (called POST) which does not include the data in the URI. See the Common Gateway Interface specification at <http://www.w3.org/CGI> for more information.

ftp - File Transfer Protocol (FTP)

ftp://ip_server/path

This is a URL accessing a file through the file transfer protocol (FTP). The default port (for control) is 21. If no username is included, the user name "anonymous" is supplied, and in that case many clients provide as the password the requestor's Internet email address. An example is <ftp://ftp.is.co.za/rfc/rfc1808.txt>.

gopher - Gopher server

gopher://ip_server/gophertype selector
gopher://ip_server/gophertype selector%09search
gopher://ip_server/gophertype selector%09search%09gopher+_string

The default gopher port is 70. gophertype is a single-character field to denote the Gopher type of the resource to which the URL refers. The entire path may also be empty, in which case the delimiting "/" is also optional and the gophertype defaults to "1".

selector is the Gopher selector string. In the Gopher protocol, Gopher selector strings are a sequence of octets which may contain any octets except 09 hexadecimal (US-ASCII HT or tab), 0A hexadecimal (US-ASCII character LF), and 0D (US-ASCII character CR).

mailto - Email address

mailto:email-address

This is an email address, usually of the form name@hostname. See mailaddr(7) for more information on the correct format of an email address. Note that any % character must be rewritten as %25. An example is <mailto:dwheeler@dwheeler.com>.

news - Newsgroup or News message

news:newsgroup-name
news:message-id

A newsgroup-name is a period-delimited hierarchical name, such as "comp.infosystems.www.misc". If <newsgroup-name> is "*" (as in <news:*>), it is used to refer to "all available news groups". An example is <news:comp.lang.ada>.

A message-id corresponds to the Message-ID of IETF RFC 1036, without the enclosing "<" and ">"; it takes the form unique@full_domain_name. A message identifier may be distinguished from a news group name by the presence of the "@" character.

telnet - Telnet login

telnet://ip_server/

The Telnet URL scheme is used to designate interactive text services that may be accessed by the Telnet protocol. The final "/" character may be omitted. The default port is 23. An example is <telnet://melvyl.ucop.edu/>.

file - Normal file

file://ip_server/path_segments
file:path_segments

This represents a file or directory accessible locally. As a special case, host can be the string "localhost" or the empty string; this is interpreted as `the machine from which the URL is being interpreted'. If the path is to a directory, the viewer should display the directory's contents with links to each containee; not all viewers currently do this. KDE supports generated files through the URL <file:/cgi-bin>. If the given file isn't found, browser writers may want to try to expand the filename via filename globbing (see glob(7) and glob(3)).

The second format (e.g., <file:/etc/passwd>) is a correct format for referring to a local file. However, older standards did not permit this format, and some programs don't recognize this as a URI. A more portable syntax is to use an empty string as the server name, for example, <file:///etc/passwd>; this form does the same thing and is easily recognized by pattern matchers and older programs as a URI. Note that if you really mean to say "start from the current location," don't specify the scheme at all; use a relative address like <../test.txt>, which has the side-effect of being scheme-independent. An example of this scheme is <file:///etc/passwd>.

man - Man page documentation

man:command-name
man:command-name(section)

This refers to local online manual (man) reference pages. The command name can optionally be followed by a parenthesis and section number; see man(7) for more information on the meaning of the section numbers. This URI scheme is unique to Unix-like systems (such as Linux) and is not currently registered by the IETF. An example is <man:ls(1)>.

info - Info page documentation

info:virtual-filename
info:virtual-filename#nodename
info:(virtual-filename)
info:(virtual-filename)nodename

This scheme refers to online info reference pages (generated from texinfo files), a documentation format used by programs such as the GNU tools. This URI scheme is unique to Unix-like systems (such as Linux) and is not currently registered by the IETF. As of this writing, GNOME and KDE differ in their URI syntax and do not accept the other's syntax. The first two formats are the GNOME format; in nodenames all spaces are written as underscores. The second two formats are the KDE format; spaces in nodenames must be written as spaces, even though this is forbidden by the URI standards. It's hoped that in the future most tools will understand all of these formats and will always accept underscores for spaces in nodenames. In both GNOME and KDE, if the form without the nodename is used the nodename is assumed to be "Top". Examples of the GNOME format are <info:gcc> and <info:gcc#G++_and_GCC>. Examples of the KDE format are <info:(gcc)> and <info:(gcc)G++ and GCC>.

whatis - Documentation search

whatis:string

This scheme searches the database of short (one-line) descriptions of commands and returns a list of descriptions containing that string. Only complete word matches are returned. See whatis(1). This URI scheme is unique to Unix-like systems (such as Linux) and is not currently registered by the IETF.

ghelp - GNOME help documentation

ghelp:name-of-application

This loads GNOME help for the given application. Note that not much documentation currently exists in this format.

ldap - Lightweight Directory Access Protocol

ldap://hostport
ldap://hostport/
ldap://hostport/dn
ldap://hostport/dn?attributes
ldap://hostport/dn?attributes?scope
ldap://hostport/dn?attributes?scope?filter
ldap://hostport/dn?attributes?scope?filter?extensions

This scheme supports queries to the Lightweight Directory Access Protocol (LDAP), a protocol for querying a set of servers for hierarchically-organized information (such as people and computing resources). More information on the LDAP URL scheme is available in RFC 2255. The components of this URL are:

hostport
the LDAP server to query, written as a hostname optionally followed by a colon and the port number. The default LDAP port is TCP port 389. If empty, the client determines which the LDAP server to use.
dn
the LDAP Distinguished Name, which identifies the base object of the LDAP search (see RFC 2253 section 3).
attributes
a comma-separated list of attributes to be returned; see RFC 2251 section 4.1.5. If omitted, all attributes should be returned.
scope
specifies the scope of the search, which can be one of "base" (for a base object search), "one" (for a one-level search), or "sub" (for a subtree search). If scope is omitted, "base" is assumed.
filter
specifies the search filter (subset of entries to return). If omitted, all entries should be returned. See RFC 2254 section 4.
extensions
a comma-separated list of type=value pairs, where the =value portion may be omitted for options not requiring it. An extension prefixed with a '!' is critical (must be supported to be valid), otherwise it is non-critical (optional).

LDAP queries are easiest to explain by example. Here's a query that asks ldap.itd.umich.edu for information about the University of Michigan in the U.S.:

ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US

To just get its postal address attribute, request:

ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US?postalAddress

To ask a host.com at port 6666 for information about the person with common name (cn) "Babs Jensen" at University of Michigan, request:

ldap://host.com:6666/o=University%20of%20Michigan,c=US??sub?(cn=Babs%20Jensen)

wais - Wide Area Information Servers

wais://hostport/database
wais://hostport/database?search
wais://hostport/database/wtype/wpath

This scheme designates a WAIS database, search, or document (see IETF RFC 1625 for more information on WAIS). Hostport is the hostname, optionally followed by a colon and port number (the default port number is 210).

The first form designates a WAIS database for searching. The second form designates a particular search of the WAIS database database. The third form designates a particular document within a WAIS database to be retrieved. wtype is the WAIS designation of the type of the object and wpath is the WAIS document-id.

other schemes

There are many other URI schemes. Most tools that accept URIs support a set of internal URIs (e.g., Mozilla has the about: scheme for internal information, and the GNOME help browser has the toc: scheme for various starting locations). There are many schemes that have been defined but are not as widely used at the current time (e.g., prospero). The nntp: scheme is deprecated in favor of the news: scheme. URNs are to be supported by the urn: scheme, with a hierarchical name space (e.g., urn:ietf:... would identify IETF documents); at this time URNs are not widely implemented. Not all tools support all schemes.

CHARACTER ENCODING

URIs use a limited number of characters so that they can be typed in and used in a variety of situations.

The following characters are reserved, that is, they may appear in a URI but their use is limited to their reserved purpose (conflicting data must be escaped before forming the URI):

; / ? : @ & = + $ ,

Unreserved characters may be included in a URI. Unreserved characters include upper and lower case English letters, decimal digits, and the following limited set of punctuation marks and symbols:

- _ . ! ~ * ' ( )

All other characters must be escaped. An escaped octet is encoded as a character triplet, consisting of the percent character "%" followed by the two hexadecimal digits representing the octet code (you can use upper or lower case letters for the hexadecimal digits). For example, a blank space must be escaped as "%20", a tab character as "%09", and the "&" as "%26". Because the percent "%" character always has the reserved purpose of being the escape indicator, it must be escaped as "%25". It is common practice to escape space characters as the plus symbol (+) in query text; this practice isn't uniformly defined in the relevant RFCs (which recommend %20 instead) but any tool accepting URIs with query text should be prepared for them. A URI is always shown in its "escaped" form.

Unreserved characters can be escaped without changing the semantics of the URI, but this should not be done unless the URI is being used in a context that does not allow the unescaped character to appear. For example, "%7e" is sometimes used instead of "~" in an http URL path, but the two are equivalent for an http URL.

For URIs which must handle characters outside the US ASCII character set, the HTML 4.01 specification (section B.2) and IETF RFC 2718 (section 2.2.5) recommend the following approach:

1.
translate the character sequences into UTF-8 (IETF RFC 2279) --- see utf-8(7) --- and then
2.
use the URI escaping mechanism, that is, use the %HH encoding for unsafe octets.

WRITING A URI

When written, URIs should be placed inside double quotes (e.g., "http://www.kernelnotes.org"), enclosed in angle brackets (e.g., <http://lwn.net>), or placed on a line by themselves. A warning for those who use double-quotes: never move extraneous punctuation (such as the period ending a sentence or the comma in a list) inside a URI, since this will change the value of the URI. Instead, use angle brackets instead, or switch to a quoting system that never includes extraneous characters inside quotation marks. This latter system, called the 'new' or 'logical' quoting system by "Hart's Rules" and the "Oxford Dictionary for Writers and Editors", is preferred practice in Great Britain and hackers worldwide (see the Jargon File's section on Hacker Writing Style, http://www.fwi.uva.nl/~mes/jargon/h/HackerWritingStyle.html, for more information). Older documents suggested inserting the prefix "URL:" just before the URI, but this form has never caught on.

The URI syntax was designed to be unambiguous. However, as URIs have become commonplace, traditional media (television, radio, newspapers, billboards, etc.) have increasingly used abbreviated URI references consisting of only the authority and path portions of the identified resource (e.g., <www.w3.org/Addressing>). Such references are primarily intended for human interpretation rather than machine, with the assumption that context-based heuristics are sufficient to complete the URI (e.g., hostnames beginning with "www" are likely to have a URI prefix of "http://" and hostnames beginning with "ftp" likely to have a prefix of "ftp://"). Many client implementations heuristically resolve these references. Such heuristics may change over time, particularly when new schemes are introduced. Since an abbreviated URI has the same syntax as a relative URL path, abbreviated URI references cannot be used where relative URIs are permitted, and can only be used when there is no defined base (such as in dialog boxes). Don't use abbreviated URIs as hypertext links inside a document; use the standard format as described here.

CONFORMING TO

http://www.ietf.org/rfc/rfc2396.txt (IETF RFC 2396), http://www.w3.org/TR/REC-html40 (HTML 4.0).

NOTES

Any tool accepting URIs (e.g., a web browser) on a Linux system should be able to handle (directly or indirectly) all of the schemes described here, including the man: and info: schemes. Handling them by invoking some other program is fine and in fact encouraged.

Technically the fragment isn't part of the URI.

For information on how to embed URIs (including URLs) in a data format, see documentation on that format. HTML uses the format <A HREF="uri"> text </A>. Texinfo files use the format @uref{uri}. Man and mdoc have the recently-added UR macro, or just include the URI in the text (viewers should be able to detect :// as part of a URI).

The GNOME and KDE desktop environments currently vary in the URIs they accept, in particular in their respective help browsers. To list man pages, GNOME uses <toc:man> while KDE uses <man:(index)>, and to list info pages, GNOME uses <toc:info> while KDE uses <info:(dir)> (the author of this man page prefers the KDE approach here, though a more regular format would be even better). In general, KDE uses <file:/cgi-bin/> as a prefix to a set of generated files. KDE prefers documentation in HTML, accessed via the <file:/cgi-bin/helpindex>. GNOME prefers the ghelp scheme to store and find documentation. Neither browser handles file: references to directories at the time of this writing, making it difficult to refer to an entire directory with a browsable URI. As noted above, these environments differ in how they handle the info: scheme, probably the most important variation. It is expected that GNOME and KDE will converge to common URI formats, and a future version of this man page will describe the converged result. Efforts to aid this convergence are encouraged.

Security

A URI does not in itself pose a security threat. There is no general guarantee that a URL, which at one time located a given resource, will continue to do so. Nor is there any guarantee that a URL will not locate a different resource at some later point in time; such a guarantee can only be obtained from the person(s) controlling that namespace and the resource in question.

It is sometimes possible to construct a URL such that an attempt to perform a seemingly harmless operation, such as the retrieval of an entity associated with the resource, will in fact cause a possibly damaging remote operation to occur. The unsafe URL is typically constructed by specifying a port number other than that reserved for the network protocol in question. The client unwittingly contacts a site that is in fact running a different protocol. The content of the URL contains instructions that, when interpreted according to this other protocol, cause an unexpected operation. An example has been the use of a gopher URL to cause an unintended or impersonating message to be sent via a SMTP server.

Caution should be used when using any URL that specifies a port number other than the default for the protocol, especially when it is a number within the reserved space.

Care should be taken when a URI contains escaped delimiters for a given protocol (for example, CR and LF characters for telnet protocols) that these are not unescaped before transmission. This might violate the protocol, but avoids the potential for such characters to be used to simulate an extra operation or parameter in that protocol, which might lead to an unexpected and possibly harmful remote operation to be performed.

It is clearly unwise to use a URI that contains a password which is intended to be secret. In particular, the use of a password within the 'userinfo' component of a URI is strongly recommended against except in those rare cases where the 'password' parameter is intended to be public.

BUGS

Documentation may be placed in a variety of locations, so there currently isn't a good URI scheme for general online documentation in arbitrary formats. References of the form <file:///usr/doc/ZZZ> don't work because different distributions and local installation requirements may place the files in different directories (it may be in /usr/doc, or /usr/local/doc, or /usr/share, or somewhere else). Also, the directory ZZZ usually changes when a version changes (though filename globbing could partially overcome this). Finally, using the file: scheme doesn't easily support people who dynamically load documentation from the Internet (instead of loading the files onto a local filesystem). A future URI scheme may be added (e.g., "userdoc:") to permit programs to include cross-references to more detailed documentation without having to know the exact location of that documentation. Alternatively, a future version of the filesystem specification may specify file locations sufficiently so that the file: scheme will be able to locate documentation.

Many programs and file formats don't include a way to incorporate or implement links using URIs.

Many programs can't handle all of these different URI formats; there should be a standard mechanism to load an arbitrary URI that automatically detects the users' environment (e.g., text or graphics, desktop environment, local user preferences, and currently-executing tools) and invokes the right tool for any URI.

SEE ALSO

lynx(1), man2html(1), mailaddr(7), utf-8(7), IETF RFC 2255.


url (7)

 Continue to this page.


iso_8859_1(7)

Status: 403 Forbidden iso_8859_1(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso_8859_1.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso_8859_15(7)

Status: 403 Forbidden iso_8859_15(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso_8859_15.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso_8859-1(7)

ISO_8859-1

Section: Linux Programmer's Manual (7)
Updated: 1999-05-31 Return to Main Contents

NAME

iso_8859-1 - the ISO 8859-1 character set encoded in octal, decimal, and hexadecimal

DESCRIPTION

The ISO 8859 standard includes several 8-bit extensions to the ASCII character set (also known as ISO 646-IRV). Especially important is ISO 8859-1, the "Latin Alphabet No. 1", which has become widely implemented and may already be seen as the de-facto standard ASCII replacement. ISO 8859-1 supports the following languages: Afrikaans, Basque, Catalan, Danish, Dutch, English, Faeroese, Finnish, French, Galician, German, Icelandic, Irish, Italian, Norwegian, Portuguese, Scottish, Spanish, and Swedish. Note that the ISO 8859-1 characters are also the first 256 characters of ISO 10646 (Unicode).

ISO 8859 Alphabets

The full set of ISO 8859 alphabets includes:
ISO 8859-1 | West European languages (Latin-1)
ISO 8859-2 | Central and East European languages (Latin-2)
ISO 8859-3 | Southeast European and miscellaneous languages (Latin-3)
ISO 8859-4 | Scandinavian/Baltic languages (Latin-4)
ISO 8859-5 | Latin/Cyrillic
ISO 8859-6 | Latin/Arabic
ISO 8859-7 | Latin/Greek
ISO 8859-8 | Latin/Hebrew
ISO 8859-9 | Latin-1 modification for Turkish (Latin-5)
ISO 8859-10 | Lappish/Nordic/Eskimo languages (Latin-6)
ISO 8859-11 | Latin/Thai
ISO 8859-13 | Baltic Rim languages (Latin-7)
ISO 8859-14 | Celtic (Latin-8)
ISO 8859-15 | West European languages (Latin-9)
ISO 8859-16 | Romanian (Latin-10)

ISO 8859-1 Characters

The following table displays the characters in ISO 8859-1 (Latin-1), which are printable and unlisted in the ascii(7) manual page. The fourth column will only show the proper glyphs in an environment configured for ISO 8859-1.
Oct | Dec | Hex | Char | Description
240 | 160 | A0 |  | NO-BREAK SPACE
241 | 161 | A1 | ¡ | INVERTED EXCLAMATION MARK
242 | 162 | A2 | ¢ | CENT SIGN
243 | 163 | A3 | £ | POUND SIGN
244 | 164 | A4 | ¤ | CURRENCY SIGN
245 | 165 | A5 | ¥ | YEN SIGN
246 | 166 | A6 | ¦ | BROKEN BAR
247 | 167 | A7 | § | SECTION SIGN
250 | 168 | A8 | ¨ | DIAERESIS
251 | 169 | A9 | © | COPYRIGHT SIGN
252 | 170 | AA | ª | FEMININE ORDINAL INDICATOR
253 | 171 | AB | « | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
254 | 172 | AC | ¬ | NOT SIGN
255 | 173 | AD |  | SOFT HYPHEN
256 | 174 | AE | ® | REGISTERED SIGN
257 | 175 | AF | ¯ | MACRON
260 | 176 | B0 | ° | DEGREE SIGN
261 | 177 | B1 | ± | PLUS-MINUS SIGN
262 | 178 | B2 | ² | SUPERSCRIPT TWO
263 | 179 | B3 | ³ | SUPERSCRIPT THREE
264 | 180 | B4 | ´ | ACUTE ACCENT
265 | 181 | B5 | µ | MICRO SIGN
266 | 182 | B6 | ¶ | PILCROW SIGN
267 | 183 | B7 | · | MIDDLE DOT
270 | 184 | B8 | ¸ | CEDILLA
271 | 185 | B9 | ¹ | SUPERSCRIPT ONE
272 | 186 | BA | º | MASCULINE ORDINAL INDICATOR
273 | 187 | BB | » | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
274 | 188 | BC | ¼ | VULGAR FRACTION ONE QUARTER
275 | 189 | BD | ½ | VULGAR FRACTION ONE HALF
276 | 190 | BE | ¾ | VULGAR FRACTION THREE QUARTERS
277 | 191 | BF | ¿ | INVERTED QUESTION MARK
300 | 192 | C0 | À | LATIN CAPITAL LETTER A WITH GRAVE
301 | 193 | C1 | Á | LATIN CAPITAL LETTER A WITH ACUTE
302 | 194 | C2 | Â | LATIN CAPITAL LETTER A WITH CIRCUMFLEX
303 | 195 | C3 | Ã | LATIN CAPITAL LETTER A WITH TILDE
304 | 196 | C4 | Ä | LATIN CAPITAL LETTER A WITH DIAERESIS
305 | 197 | C5 | Å | LATIN CAPITAL LETTER A WITH RING ABOVE
306 | 198 | C6 | Æ | LATIN CAPITAL LETTER AE
307 | 199 | C7 | Ç | LATIN CAPITAL LETTER C WITH CEDILLA
310 | 200 | C8 | È | LATIN CAPITAL LETTER E WITH GRAVE
311 | 201 | C9 | É | LATIN CAPITAL LETTER E WITH ACUTE
312 | 202 | CA | Ê | LATIN CAPITAL LETTER E WITH CIRCUMFLEX
313 | 203 | CB | Ë | LATIN CAPITAL LETTER E WITH DIAERESIS
314 | 204 | CC | Ì | LATIN CAPITAL LETTER I WITH GRAVE
315 | 205 | CD | Í | LATIN CAPITAL LETTER I WITH ACUTE
316 | 206 | CE | Î | LATIN CAPITAL LETTER I WITH CIRCUMFLEX
317 | 207 | CF | Ï | LATIN CAPITAL LETTER I WITH DIAERESIS
320 | 208 | D0 | Ð | LATIN CAPITAL LETTER ETH
321 | 209 | D1 | Ñ | LATIN CAPITAL LETTER N WITH TILDE
322 | 210 | D2 | Ò | LATIN CAPITAL LETTER O WITH GRAVE
323 | 211 | D3 | Ó | LATIN CAPITAL LETTER O WITH ACUTE
324 | 212 | D4 | Ô | LATIN CAPITAL LETTER O WITH CIRCUMFLEX
325 | 213 | D5 | Õ | LATIN CAPITAL LETTER O WITH TILDE
326 | 214 | D6 | Ö | LATIN CAPITAL LETTER O WITH DIAERESIS
327 | 215 | D7 | × | MULTIPLICATION SIGN
330 | 216 | D8 | Ø | LATIN CAPITAL LETTER O WITH STROKE
331 | 217 | D9 | Ù | LATIN CAPITAL LETTER U WITH GRAVE
332 | 218 | DA | Ú | LATIN CAPITAL LETTER U WITH ACUTE
333 | 219 | DB | Û | LATIN CAPITAL LETTER U WITH CIRCUMFLEX
334 | 220 | DC | Ü | LATIN CAPITAL LETTER U WITH DIAERESIS
335 | 221 | DD | Ý | LATIN CAPITAL LETTER Y WITH ACUTE
336 | 222 | DE | Þ | LATIN CAPITAL LETTER THORN
337 | 223 | DF | ß | LATIN SMALL LETTER SHARP S
340 | 224 | E0 | à | LATIN SMALL LETTER A WITH GRAVE
341 | 225 | E1 | á | LATIN SMALL LETTER A WITH ACUTE
342 | 226 | E2 | â | LATIN SMALL LETTER A WITH CIRCUMFLEX
343 | 227 | E3 | ã | LATIN SMALL LETTER A WITH TILDE
344 | 228 | E4 | ä | LATIN SMALL LETTER A WITH DIAERESIS
345 | 229 | E5 | å | LATIN SMALL LETTER A WITH RING ABOVE
346 | 230 | E6 | æ | LATIN SMALL LETTER AE
347 | 231 | E7 | ç | LATIN SMALL LETTER C WITH CEDILLA
350 | 232 | E8 | è | LATIN SMALL LETTER E WITH GRAVE
351 | 233 | E9 | é | LATIN SMALL LETTER E WITH ACUTE
352 | 234 | EA | ê | LATIN SMALL LETTER E WITH CIRCUMFLEX
353 | 235 | EB | ë | LATIN SMALL LETTER E WITH DIAERESIS
354 | 236 | EC | ì | LATIN SMALL LETTER I WITH GRAVE
355 | 237 | ED | í | LATIN SMALL LETTER I WITH ACUTE
356 | 238 | EE | î | LATIN SMALL LETTER I WITH CIRCUMFLEX
357 | 239 | EF | ï | LATIN SMALL LETTER I WITH DIAERESIS
360 | 240 | F0 | ð | LATIN SMALL LETTER ETH
361 | 241 | F1 | ñ | LATIN SMALL LETTER N WITH TILDE
362 | 242 | F2 | ò | LATIN SMALL LETTER O WITH GRAVE
363 | 243 | F3 | ó | LATIN SMALL LETTER O WITH ACUTE
364 | 244 | F4 | ô | LATIN SMALL LETTER O WITH CIRCUMFLEX
365 | 245 | F5 | õ | LATIN SMALL LETTER O WITH TILDE
366 | 246 | F6 | ö | LATIN SMALL LETTER O WITH DIAERESIS
367 | 247 | F7 | ÷ | DIVISION SIGN
370 | 248 | F8 | ø | LATIN SMALL LETTER O WITH STROKE
371 | 249 | F9 | ù | LATIN SMALL LETTER U WITH GRAVE
372 | 250 | FA | ú | LATIN SMALL LETTER U WITH ACUTE
373 | 251 | FB | û | LATIN SMALL LETTER U WITH CIRCUMFLEX
374 | 252 | FC | ü | LATIN SMALL LETTER U WITH DIAERESIS
375 | 253 | FD | ý | LATIN SMALL LETTER Y WITH ACUTE
376 | 254 | FE | þ | LATIN SMALL LETTER THORN
377 | 255 | FF | ÿ | LATIN SMALL LETTER Y WITH DIAERESIS

SEE ALSO

ascii(7), iso_8859-15(7)


iso_8859-15(7)

ISO_8859-15

Section: Linux Programmer's Manual (7)
Updated: 1999-05-31 Return to Main Contents

NAME

iso_8859-15 - the ISO 8859-15 character set encoded in octal, decimal, and hexadecimal

DESCRIPTION

The ISO 8859 standard includes several 8-bit extensions to the ASCII character set (also known as ISO 646-IRV). Especially important is ISO 8859-1, the "Latin Alphabet No. 1", which has become widely implemented and may already be seen as the de-facto standard ASCII replacement. However, it lacks the EURO symbol and does not fully cover Finnish and French. ISO 8859-15 is a modification of ISO 8859-1 that covers these needs. ISO 8859-15 supports the following languages: Albanian, Basque, Breton, Catalan, Danish, Dutch, English, Estonian, Faroese, Finnish, French, Frisian, Galician, German, Greenlandic, Icelandic, Irish Gaelic, Italian, Latin, Luxemburgish, Norwegian, Portuguese, Rhaeto-Romanic, Scottish Gaelic, Spanish, and Swedish.

ISO 8859 Alphabets

The full set of ISO 8859 alphabets includes:
ISO 8859-1 | West European languages (Latin-1)
ISO 8859-2 | Central and East European languages (Latin-2)
ISO 8859-3 | Southeast European and miscellaneous languages (Latin-3)
ISO 8859-4 | Scandinavian/Baltic languages (Latin-4)
ISO 8859-5 | Latin/Cyrillic
ISO 8859-6 | Latin/Arabic
ISO 8859-7 | Latin/Greek
ISO 8859-8 | Latin/Hebrew
ISO 8859-9 | Latin-1 modification for Turkish (Latin-5)
ISO 8859-10 | Lappish/Nordic/Eskimo languages (Latin-6)
ISO 8859-11 | Latin/Thai
ISO 8859-13 | Baltic Rim languages (Latin-7)
ISO 8859-14 | Celtic (Latin-8)
ISO 8859-15 | West European languages (Latin-9)
ISO 8859-16 | Romanian (Latin-10)

ISO 8859-15 Characters

The following table displays the characters in ISO 8859-15 (Latin-9), which are printable and unlisted in the ascii(7) manual page. The fourth column will only show the proper glyphs in an environment configured for ISO 8859-15.
Oct | Dec | Hex | Char | Description
240 | 160 | A0 |  | NO-BREAK SPACE
241 | 161 | A1 | ¡ | INVERTED EXCLAMATION MARK
242 | 162 | A2 | ¢ | CENT SIGN
243 | 163 | A3 | £ | POUND SIGN
244 | 164 | A4 | ¤ | EURO SIGN
245 | 165 | A5 | ¥ | YEN SIGN
246 | 166 | A6 | ¦ | LATIN CAPITAL LETTER S WITH CARON
247 | 167 | A7 | § | SECTION SIGN
250 | 168 | A8 | ¨ | LATIN SMALL LETTER S WITH CARON
251 | 169 | A9 | © | COPYRIGHT SIGN
252 | 170 | AA | ª | FEMININE ORDINAL INDICATOR
253 | 171 | AB | « | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
254 | 172 | AC | ¬ | NOT SIGN
255 | 173 | AD |  | SOFT HYPHEN
256 | 174 | AE | ® | REGISTERED SIGN
257 | 175 | AF | ¯ | MACRON
260 | 176 | B0 | ° | DEGREE SIGN
261 | 177 | B1 | ± | PLUS-MINUS SIGN
262 | 178 | B2 | ² | SUPERSCRIPT TWO
263 | 179 | B3 | ³ | SUPERSCRIPT THREE
264 | 180 | B4 | ´ | LATIN CAPITAL LETTER Z WITH CARON
265 | 181 | B5 | µ | MICRO SIGN
266 | 182 | B6 | ¶ | PILCROW SIGN
267 | 183 | B7 | · | MIDDLE DOT
270 | 184 | B8 | ¸ | LATIN SMALL LETTER Z WITH CARON
271 | 185 | B9 | ¹ | SUPERSCRIPT ONE
272 | 186 | BA | º | MASCULINE ORDINAL INDICATOR
273 | 187 | BB | » | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
274 | 188 | BC | ¼ | LATIN CAPITAL LIGATURE OE
275 | 189 | BD | ½ | LATIN SMALL LIGATURE OE
276 | 190 | BE | ¾ | LATIN CAPITAL LETTER Y WITH DIAERESIS
277 | 191 | BF | ¿ | INVERTED QUESTION MARK
300 | 192 | C0 | À | LATIN CAPITAL LETTER A WITH GRAVE
301 | 193 | C1 | Á | LATIN CAPITAL LETTER A WITH ACUTE
302 | 194 | C2 | Â | LATIN CAPITAL LETTER A WITH CIRCUMFLEX
303 | 195 | C3 | Ã | LATIN CAPITAL LETTER A WITH TILDE
304 | 196 | C4 | Ä | LATIN CAPITAL LETTER A WITH DIAERESIS
305 | 197 | C5 | Å | LATIN CAPITAL LETTER A WITH RING ABOVE
306 | 198 | C6 | Æ | LATIN CAPITAL LETTER AE
307 | 199 | C7 | Ç | LATIN CAPITAL LETTER C WITH CEDILLA
310 | 200 | C8 | È | LATIN CAPITAL LETTER E WITH GRAVE
311 | 201 | C9 | É | LATIN CAPITAL LETTER E WITH ACUTE
312 | 202 | CA | Ê | LATIN CAPITAL LETTER E WITH CIRCUMFLEX
313 | 203 | CB | Ë | LATIN CAPITAL LETTER E WITH DIAERESIS
314 | 204 | CC | Ì | LATIN CAPITAL LETTER I WITH GRAVE
315 | 205 | CD | Í | LATIN CAPITAL LETTER I WITH ACUTE
316 | 206 | CE | Î | LATIN CAPITAL LETTER I WITH CIRCUMFLEX
317 | 207 | CF | Ï | LATIN CAPITAL LETTER I WITH DIAERESIS
320 | 208 | D0 | Ð | LATIN CAPITAL LETTER ETH
321 | 209 | D1 | Ñ | LATIN CAPITAL LETTER N WITH TILDE
322 | 210 | D2 | Ò | LATIN CAPITAL LETTER O WITH GRAVE
323 | 211 | D3 | Ó | LATIN CAPITAL LETTER O WITH ACUTE
324 | 212 | D4 | Ô | LATIN CAPITAL LETTER O WITH CIRCUMFLEX
325 | 213 | D5 | Õ | LATIN CAPITAL LETTER O WITH TILDE
326 | 214 | D6 | Ö | LATIN CAPITAL LETTER O WITH DIAERESIS
327 | 215 | D7 | × | MULTIPLICATION SIGN
330 | 216 | D8 | Ø | LATIN CAPITAL LETTER O WITH STROKE
331 | 217 | D9 | Ù | LATIN CAPITAL LETTER U WITH GRAVE
332 | 218 | DA | Ú | LATIN CAPITAL LETTER U WITH ACUTE
333 | 219 | DB | Û | LATIN CAPITAL LETTER U WITH CIRCUMFLEX
334 | 220 | DC | Ü | LATIN CAPITAL LETTER U WITH DIAERESIS
335 | 221 | DD | Ý | LATIN CAPITAL LETTER Y WITH ACUTE
336 | 222 | DE | Þ | LATIN CAPITAL LETTER THORN
337 | 223 | DF | ß | LATIN SMALL LETTER SHARP S
340 | 224 | E0 | à | LATIN SMALL LETTER A WITH GRAVE
341 | 225 | E1 | á | LATIN SMALL LETTER A WITH ACUTE
342 | 226 | E2 | â | LATIN SMALL LETTER A WITH CIRCUMFLEX
343 | 227 | E3 | ã | LATIN SMALL LETTER A WITH TILDE
344 | 228 | E4 | ä | LATIN SMALL LETTER A WITH DIAERESIS
345 | 229 | E5 | å | LATIN SMALL LETTER A WITH RING ABOVE
346 | 230 | E6 | æ | LATIN SMALL LETTER AE
347 | 231 | E7 | ç | LATIN SMALL LETTER C WITH CEDILLA
350 | 232 | E8 | è | LATIN SMALL LETTER E WITH GRAVE
351 | 233 | E9 | é | LATIN SMALL LETTER E WITH ACUTE
352 | 234 | EA | ê | LATIN SMALL LETTER E WITH CIRCUMFLEX
353 | 235 | EB | ë | LATIN SMALL LETTER E WITH DIAERESIS
354 | 236 | EC | ì | LATIN SMALL LETTER I WITH GRAVE
355 | 237 | ED | í | LATIN SMALL LETTER I WITH ACUTE
356 | 238 | EE | î | LATIN SMALL LETTER I WITH CIRCUMFLEX
357 | 239 | EF | ï | LATIN SMALL LETTER I WITH DIAERESIS
360 | 240 | F0 | ð | LATIN SMALL LETTER ETH
361 | 241 | F1 | ñ | LATIN SMALL LETTER N WITH TILDE
362 | 242 | F2 | ò | LATIN SMALL LETTER O WITH GRAVE
363 | 243 | F3 | ó | LATIN SMALL LETTER O WITH ACUTE
364 | 244 | F4 | ô | LATIN SMALL LETTER O WITH CIRCUMFLEX
365 | 245 | F5 | õ | LATIN SMALL LETTER O WITH TILDE
366 | 246 | F6 | ö | LATIN SMALL LETTER O WITH DIAERESIS
367 | 247 | F7 | ÷ | DIVISION SIGN
370 | 248 | F8 | ø | LATIN SMALL LETTER O WITH STROKE
371 | 249 | F9 | ù | LATIN SMALL LETTER U WITH GRAVE
372 | 250 | FA | ú | LATIN SMALL LETTER U WITH ACUTE
373 | 251 | FB | û | LATIN SMALL LETTER U WITH CIRCUMFLEX
374 | 252 | FC | ü | LATIN SMALL LETTER U WITH DIAERESIS
375 | 253 | FD | ý | LATIN SMALL LETTER Y WITH ACUTE
376 | 254 | FE | þ | LATIN SMALL LETTER THORN
377 | 255 | FF | ÿ | LATIN SMALL LETTER Y WITH DIAERESIS

SEE ALSO

ascii(7), iso_8859-1(7)


iso_8859_7(7)

Status: 403 Forbidden iso_8859_7(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso_8859_7.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso-8859-1(7)

Status: 403 Forbidden iso-8859-1(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso-8859-1.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso-8859-15(7)

Status: 403 Forbidden iso-8859-15(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso-8859-15.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso-8859-7(7)

Status: 403 Forbidden iso-8859-7(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso-8859-7.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


latin2(7)

Status: 403 Forbidden latin2(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/latin2.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


charsets(7)

CHARSETS

Section: Linux Programmer's Manual (7)
Updated: 2001-05-07 Return to Main Contents

NAME

charsets - programmer's view of character sets and internationalization

DESCRIPTION

Linux is an international operating system. Various of its utilities and device drivers (including the console driver) support multilingual character sets including Latin-alphabet letters with diacritical marks, accents, ligatures, and entire non-Latin alphabets including Greek, Cyrillic, Arabic, and Hebrew.

This manual page presents a programmer's-eye view of different character-set standards and how they fit together on Linux. Standards discussed include ASCII, ISO 8859, KOI8-R, Unicode, ISO 2022 and ISO 4873. The primary emphasis is on character sets actually used as locale character sets, not the myriad others that can be found in data from other systems.

A complete list of charsets used in a officially supported locale in glibc 2.2.3 is: ISO-8859-{1,2,3,5,6,7,8,9,13,15}, CP1251, UTF-8, EUC-{KR,JP,TW}, KOI8-{R,U}, GB2312, GB18030, GBK, BIG5, BIG5-HKSCS and TIS-620 (in no particular order.) (Romanian may be switching to ISO-8859-16.)

ASCII

ASCII (American Standard Code For Information Interchange) is the original 7-bit character set, originally designed for American English. It is currently described by the ECMA-6 standard.

Various ASCII variants replacing the dollar sign with other currency symbols and replacing punctuation with non-English alphabetic characters to cover German, French, Spanish and others in 7 bits exist. All are deprecated; GNU libc doesn't support locales whose character sets aren't true supersets of ASCII. (These sets are also known as ISO-646, a close relative of ASCII that permitted replacing these characters.)

As Linux was written for hardware designed in the US, it natively supports ASCII.

ISO 8859

ISO 8859 is a series of 15 8-bit character sets all of which have US ASCII in their low (7-bit) half, invisible control characters in positions 128 to 159, and 96 fixed-width graphics in positions 160-255.

Of these, the most important is ISO 8859-1 (Latin-1). It is natively supported in the Linux console driver, fairly well supported in X11R6, and is the base character set of HTML.

Console support for the other 8859 character sets is available under Linux through user-mode utilities (such as setfont(8)) that modify keyboard bindings and the EGA graphics table and employ the "user mapping" font table in the console driver.

Here are brief descriptions of each set:

8859-1 (Latin-1)
Latin-1 covers most Western European languages such as Albanian, Catalan, Danish, Dutch, English, Faroese, Finnish, French, German, Galician, Irish, Icelandic, Italian, Norwegian, Portuguese, Spanish, and Swedish. The lack of the ligatures Dutch ij, French oe and old-style ,,German`` quotation marks is considered tolerable.
8859-2 (Latin-2)
Latin-2 supports most Latin-written Slavic and Central European languages: Croatian, Czech, German, Hungarian, Polish, Rumanian, Slovak, and Slovene.
8859-3 (Latin-3)
Latin-3 is popular with authors of Esperanto, Galician, and Maltese. (Turkish is now written with 8859-9 instead.)
8859-4 (Latin-4)
Latin-4 introduced letters for Estonian, Latvian, and Lithuanian. It is essentially obsolete; see 8859-10 (Latin-6) and 8859-13 (Latin-7).
8859-5
Cyrillic letters supporting Bulgarian, Byelorussian, Macedonian, Russian, Serbian and Ukrainian. Ukrainians read the letter `ghe' with downstroke as `heh' and would need a ghe with upstroke to write a correct ghe. See the discussion of KOI8-R below.
8859-6
Supports Arabic. The 8859-6 glyph table is a fixed font of separate letter forms, but a proper display engine should combine these using the proper initial, medial, and final forms.
8859-7
Supports Modern Greek.
8859-8
Supports modern Hebrew without niqud (punctuation signs). Niqud and full-fledged Biblical Hebrew are outside the scope of this character set; under Linux, UTF-8 is the preferred encoding for these.
8859-9 (Latin-5)
This is a variant of Latin-1 that replaces Icelandic letters with Turkish ones.
8859-10 (Latin-6)
Latin 6 adds the last Inuit (Greenlandic) and Sami (Lappish) letters that were missing in Latin 4 to cover the entire Nordic area. RFC 1345 listed a preliminary and different `latin6'. Skolt Sami still needs a few more accents than these.
8859-11
This only exists as a rejected draft standard. The draft standard was identical to TIS-620, which is used under Linux for Thai.
8859-12
This set does not exist. While Vietnamese has been suggested for this space, it does not fit within the 96 (non-combining) characters ISO 8859 offers. UTF-8 is the preferred character set for Vietnamese use under Linux.
8859-13 (Latin-7)
Supports the Baltic Rim languages; in particular, it includes Latvian characters not found in Latin-4.
8859-14 (Latin-8)
This is the Celtic character set, covering Gaelic and Welsh. This charset also contains the dotted characters needed for Old Irish.
8859-15 (Latin-9)
This adds the Euro sign and French and Finnish letters that were missing in Latin-1.
8859-16 (Latin-10)
This set covers many of the languages covered by 8859-2, and supports Romanian more completely then that set does.

KOI8-R

KOI8-R is a non-ISO character set popular in Russia. The lower half is US ASCII; the upper is a Cyrillic character set somewhat better designed than ISO 8859-5. KOI8-U is a common character set, based off KOI8-R, that has better support for Ukrainian. Neither of these sets are ISO-2022 compatible, unlike the ISO-8859 series.

Console support for KOI8-R is available under Linux through user-mode utilities that modify keyboard bindings and the EGA graphics table, and employ the "user mapping" font table in the console driver.

JIS X 0208

JIS X 0208 is a Japanese national standard character set. Though there are some more Japanese national standard character sets (like JIS X 0201, JIS X 0212, and JIS X 0213), this is the most important one. Characters are mapped into a 94x94 two-byte matrix, whose each byte is in the range 0x21-0x7e. Note that JIS X 0208 is a character set, not an encoding. This means that JIS X 0208 itself is not used for expressing text data. JIS X 0208 is used as a component to construct encodings such as EUC-JP, Shift_JIS, and ISO-2022-JP. EUC-JP is the most important encoding for Linux and includes US ASCII and JIS X 0208. In EUC-JP, JIS X 0208 characters are expressed in two bytes, each of which is the JIS X 0208 code plus 0x80.

KS X 1001

KS X 1001 is a Korean national standard character set. Just as JIS X 0208, characters are mapped into a 94x94 two-byte matrix. KS X 1001 is used like JIS X 0208, as a component to construct encodings such as EUC-KR, Johab, and ISO-2022-KR. EUC-KR is the most important encoding for Linux and includes US ASCII and KS X 1001. KS C 5601 is an older name for KS X 1001.

GB 2312

GB 2312 is a mainland Chinese national standard character set used to express simplified Chinese. Just like JIS X 0208, characters are mapped into a 94x94 two-byte matrix used to construct EUC-CN. EUC-CN is the most important encoding for Linux and includes US ASCII and GB 2312. Note that EUC-CN is often called as GB, GB 2312, or CN-GB.

Big5

Big5 is a popular character set in Taiwan to express traditional Chinese. (Big5 is both a character set and an encoding.) It is a superset of US ASCII. Non-ASCII characters are expressed in two bytes. Bytes 0xa1-0xfe are used as leading bytes for two-byte characters. Big5 and its extension is widely used in Taiwan and Hong Kong. It is not ISO 2022-compliant.

TIS 620

TIS 620 is a Thai national standard character set and a superset of US ASCII. Like ISO 8859 series, Thai characters are mapped into 0xa1-0xfe. TIS 620 is the only commonly used character set under Linux besides UTF-8 to have combining characters.

UNICODE

Unicode (ISO 10646) is a standard which aims to unambiguously represent every character in every human language. Unicode's structure permits 20.1 bits to encode every character. Since most computers don't include 20.1-bit integers, Unicode is usually encoded as 32-bit integers internally and either a series of 16-bit integers (UTF-16) (needing two 16-bit integers only when encoding certain rare characters) or a series of 8-bit bytes (UTF-8). Information on Unicode is available at <http://www.unicode.com>.

Linux represents Unicode using the 8-bit Unicode Transformation Format (UTF-8). UTF-8 is a variable length encoding of Unicode. It uses 1 byte to code 7 bits, 2 bytes for 11 bits, 3 bytes for 16 bits, 4 bytes for 21 bits, 5 bytes for 26 bits, 6 bytes for 31 bits.

Let 0,1,x stand for a zero, one, or arbitrary bit. A byte 0xxxxxxx stands for the Unicode 00000000 0xxxxxxx which codes the same symbol as the ASCII 0xxxxxxx. Thus, ASCII goes unchanged into UTF-8, and people using only ASCII do not notice any change: not in code, and not in file size.

A byte 110xxxxx is the start of a 2-byte code, and 110xxxxx 10yyyyyy is assembled into 00000xxx xxyyyyyy. A byte 1110xxxx is the start of a 3-byte code, and 1110xxxx 10yyyyyy 10zzzzzz is assembled into xxxxyyyy yyzzzzzz. (When UTF-8 is used to code the 31-bit ISO 10646 then this progression continues up to 6-byte codes.)

For most people who use ISO-8859 character sets, this means that the characters outside of ASCII are now coded with two bytes. This tends to expand ordinary text files by only one or two percent. For Russian or Greek users, this expands ordinary text files by 100%, since text in those languages is mostly outside of ASCII. For Japanese users this means that the 16-bit codes now in common use will take three bytes. While there are algorithmic conversions from some character sets (esp. ISO-8859-1) to Unicode, general conversion requires carrying around conversion tables, which can be quite large for 16-bit codes.

Note that UTF-8 is self-synchronizing: 10xxxxxx is a tail, any other byte is the head of a code. Note that the only way ASCII bytes occur in a UTF-8 stream, is as themselves. In particular, there are no embedded NULs ('\0') or '/'s that form part of some larger code.

Since ASCII, and, in particular, NUL and '/', are unchanged, the kernel does not notice that UTF-8 is being used. It does not care at all what the bytes it is handling stand for.

Rendering of Unicode data streams is typically handled through `subfont' tables which map a subset of Unicode to glyphs. Internally the kernel uses Unicode to describe the subfont loaded in video RAM. This means that in UTF-8 mode one can use a character set with 512 different symbols. This is not enough for Japanese, Chinese and Korean, but it is enough for most other purposes.

At the current time, the console driver does not handle combining characters. So Thai, Sioux and any other script needing combining characters can't be handled on the console.

ISO 2022 AND ISO 4873

The ISO 2022 and 4873 standards describe a font-control model based on VT100 practice. This model is (partially) supported by the Linux kernel and by xterm(1). It is popular in Japan and Korea.

There are 4 graphic character sets, called G0, G1, G2 and G3, and one of them is the current character set for codes with high bit zero (initially G0), and one of them is the current character set for codes with high bit one (initially G1). Each graphic character set has 94 or 96 characters, and is essentially a 7-bit character set. It uses codes either 040-0177 (041-0176) or 0240-0377 (0241-0376). G0 always has size 94 and uses codes 041-0176.

Switching between character sets is done using the shift functions ^N (SO or LS1), ^O (SI or LS0), ESC n (LS2), ESC o (LS3), ESC N (SS2), ESC O (SS3), ESC ~ (LS1R), ESC } (LS2R), ESC | (LS3R). The function LSn makes character set Gn the current one for codes with high bit zero. The function LSnR makes character set Gn the current one for codes with high bit one. The function SSn makes character set Gn (n=2 or 3) the current one for the next character only (regardless of the value of its high order bit).

A 94-character set is designated as Gn character set by an escape sequence ESC ( xx (for G0), ESC ) xx (for G1), ESC * xx (for G2), ESC + xx (for G3), where xx is a symbol or a pair of symbols found in the ISO 2375 International Register of Coded Character Sets. For example, ESC ( @ selects the ISO 646 character set as G0, ESC ( A selects the UK standard character set (with pound instead of number sign), ESC ( B selects ASCII (with dollar instead of currency sign), ESC ( M selects a character set for African languages, ESC ( ! A selects the Cuban character set, etc. etc.

A 96-character set is designated as Gn character set by an escape sequence ESC - xx (for G1), ESC . xx (for G2) or ESC / xx (for G3). For example, ESC - G selects the Hebrew alphabet as G1.

A multibyte character set is designated as Gn character set by an escape sequence ESC $ xx or ESC $ ( xx (for G0), ESC $ ) xx (for G1), ESC $ * xx (for G2), ESC $ + xx (for G3). For example, ESC $ ( C selects the Korean character set for G0. The Japanese character set selected by ESC $ B has a more recent version selected by ESC & @ ESC $ B.

ISO 4873 stipulates a narrower use of character sets, where G0 is fixed (always ASCII), so that G1, G2 and G3 can only be invoked for codes with the high order bit set. In particular, ^N and ^O are not used anymore, ESC ( xx can be used only with xx=B, and ESC ) xx, ESC * xx, ESC + xx are equivalent to ESC - xx, ESC . xx, ESC / xx, respectively.

SEE ALSO

console(4), console_codes(4), console_ioctl(4), ascii(7), iso_8859-1(7), unicode(7), utf-8(7)


iso_8859_2(7)

Status: 403 Forbidden iso_8859_2(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso_8859_2.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso-8859-2(7)

Status: 403 Forbidden iso-8859-2(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso-8859-2.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso_8859-2(7)

ISO_8859-2

Section: Linux Programmer's Manual (7)
Updated: 1999-11-13 Return to Main Contents

NAME

iso_8859-2 - the ISO 8859-2 character set encoded in octal, decimal, and hexadecimal

DESCRIPTION

The ISO 8859 standard includes several 8-bit extensions to the ASCII character set (also known as ISO 646-IRV). ISO 8859-2, the "Latin Alphabet No. 2" is used to encode Central and Eastern European Latin characters and is implemented by several program vendors. ISO 8859-2 supports the following languages: Albanian, Bosnian, Croatian, Czech, English, Finnish, German, Hungarian, Irish, Polish, Slovak, Slovenian and Sorbian. Also note that the following Cyrillic-based languages have one-to-one transliterations to Latin 2: Macedonian and Serbian.

ISO 8859 Alphabets

The full set of ISO 8859 alphabets includes:
ISO 8859-1 | West European languages (Latin-1)
ISO 8859-2 | Central and East European languages (Latin-2)
ISO 8859-3 | Southeast European and miscellaneous languages (Latin-3)
ISO 8859-4 | Scandinavian/Baltic languages (Latin-4)
ISO 8859-5 | Latin/Cyrillic
ISO 8859-6 | Latin/Arabic
ISO 8859-7 | Latin/Greek
ISO 8859-8 | Latin/Hebrew
ISO 8859-9 | Latin-1 modification for Turkish (Latin-5)
ISO 8859-10 | Lappish/Nordic/Eskimo languages (Latin-6)
ISO 8859-11 | Latin/Thai
ISO 8859-13 | Baltic Rim languages (Latin-7)
ISO 8859-14 | Celtic (Latin-8)
ISO 8859-15 | West European languages (Latin-9)
ISO 8859-16 | Romanian (Latin-10)

ISO 8859-2 Characters

The following table displays the characters in ISO 8859-2 (Latin-2), which are printable and unlisted in the ascii(7) manual page. The fourth column will only show the proper glyphs in an environment configured for ISO 8859-2.
Oct | Dec | Hex | Char | Description
240 | 160 | A0 |  | NO-BREAK SPACE
241 | 161 | A1 | ¡ | LATIN CAPITAL LETTER A WITH OGONEK
242 | 162 | A2 | ¢ | BREVE
243 | 163 | A3 | £ | LATIN CAPITAL LETTER L WITH STROKE
244 | 164 | A4 | ¤ | CURRENCY SIGN
245 | 165 | A5 | ¥ | LATIN CAPITAL LETTER L WITH CARON
246 | 166 | A6 | ¦ | LATIN CAPITAL LETTER S WITH ACUTE
247 | 167 | A7 | § | SECTION SIGN
250 | 168 | A8 | ¨ | DIAERESIS
251 | 169 | A9 | © | LATIN CAPITAL LETTER S WITH CARON
252 | 170 | AA | ª | LATIN CAPITAL LETTER S WITH CEDILLA
253 | 171 | AB | « | LATIN CAPITAL LETTER T WITH CARON
254 | 172 | AC | ¬ | LATIN CAPITAL LETTER Z WITH ACUTE
255 | 173 | AD | [shc] | SOFT HYPHEN
256 | 174 | AE | ® | LATIN CAPITAL LETTER Z WITH CARON
257 | 175 | AF | ¯ | LATIN CAPITAL LETTER Z WITH DOT ABOVE
260 | 176 | B0 | ° | DEGREE SIGN
261 | 177 | B1 | ± | LATIN SMALL LETTER A WITH OGONEK
262 | 178 | B2 | ² | OGONEK
263 | 179 | B3 | ³ | LATIN SMALL LETTER L WITH STROKE
264 | 180 | B4 | ´ | ACUTE ACCENT
265 | 181 | B5 | µ | LATIN SMALL LETTER L WITH CARON
266 | 182 | B6 | ¶ | LATIN SMALL LETTER S WITH ACUTE
267 | 183 | B7 | · | CARON
270 | 184 | B8 | ¸ | CEDILLA
271 | 185 | B9 | ¹ | LATIN SMALL LETTER S WITH CARON
272 | 186 | BA | º | LATIN SMALL LETTER S WITH CEDILLA
273 | 187 | BB | » | LATIN SMALL LETTER T WITH CARON
274 | 188 | BC | ¼ | LATIN SMALL LETTER Z WITH ACUTE
275 | 189 | BD | ½ | DOUBLE ACUTE ACCENT
276 | 190 | BE | ¾ | LATIN SMALL LETTER Z WITH CARON
277 | 191 | BF | ¿ | LATIN SMALL LETTER Z WITH DOT ABOVE
300 | 192 | C0 | À | LATIN CAPITAL LETTER R WITH ACUTE
301 | 193 | C1 | Á | LATIN CAPITAL LETTER A WITH ACUTE
302 | 194 | C2 | Â | LATIN CAPITAL LETTER A WITH CIRCUMFLEX
303 | 195 | C3 | Ã | LATIN CAPITAL LETTER A WITH BREVE
304 | 196 | C4 | Ä | LATIN CAPITAL LETTER A WITH DIAERESIS
305 | 197 | C5 | Å | LATIN CAPITAL LETTER L WITH ACUTE
306 | 198 | C6 | Æ | LATIN CAPITAL LETTER C WITH ACUTE
307 | 199 | C7 | Ç | LATIN CAPITAL LETTER C WITH CEDILLA
310 | 200 | C8 | È | LATIN CAPITAL LETTER C WITH CARON
311 | 201 | C9 | É | LATIN CAPITAL LETTER E WITH ACUTE
312 | 202 | CA | Ê | LATIN CAPITAL LETTER E WITH OGONEK
313 | 203 | CB | Ë | LATIN CAPITAL LETTER E WITH DIAERESIS
314 | 204 | CC | Ì | LATIN CAPITAL LETTER E WITH CARON
315 | 205 | CD | Í | LATIN CAPITAL LETTER I WITH ACUTE
316 | 206 | CE | Î | LATIN CAPITAL LETTER I WITH CIRCUMFLEX
317 | 207 | CF | Ï | LATIN CAPITAL LETTER D WITH CARON
320 | 208 | D0 | Ð | LATIN CAPITAL LETTER D WITH STROKE
321 | 209 | D1 | Ñ | LATIN CAPITAL LETTER N WITH ACUTE
322 | 210 | D2 | Ò | LATIN CAPITAL LETTER N WITH CARON
323 | 211 | D3 | Ó | LATIN CAPITAL LETTER O WITH ACUTE
324 | 212 | D4 | Ô | LATIN CAPITAL LETTER O WITH CIRCUMFLEX
325 | 213 | D5 | Õ | LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
326 | 214 | D6 | Ö | LATIN CAPITAL LETTER O WITH DIAERESIS
327 | 215 | D7 | × | MULTIPLICATION SIGN
330 | 216 | D8 | Ø | LATIN CAPITAL LETTER R WITH CARON
331 | 217 | D9 | Ù | LATIN CAPITAL LETTER U WITH RING ABOVE
332 | 218 | DA | Ú | LATIN CAPITAL LETTER U WITH ACUTE
333 | 219 | DB | Û | LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
334 | 220 | DC | Ü | LATIN CAPITAL LETTER U WITH DIAERESIS
335 | 221 | DD | Ý | LATIN CAPITAL LETTER Y WITH ACUTE
336 | 222 | DE | Þ | LATIN CAPITAL LETTER T WITH CEDILLA
337 | 223 | DF | ß | LATIN SMALL LETTER SHARP S
340 | 224 | E0 | à | LATIN SMALL LETTER R WITH ACUTE
341 | 225 | E1 | á | LATIN SMALL LETTER A WITH ACUTE
342 | 226 | E2 | â | LATIN SMALL LETTER A WITH CIRCUMFLEX
343 | 227 | E3 | ã | LATIN SMALL LETTER A WITH BREVE
344 | 228 | E4 | ä | LATIN SMALL LETTER A WITH DIAERESIS
345 | 229 | E5 | å | LATIN SMALL LETTER L WITH ACUTE
346 | 230 | E6 | æ | LATIN SMALL LETTER C WITH ACUTE
347 | 231 | E7 | ç | LATIN SMALL LETTER C WITH CEDILLA
350 | 232 | E8 | è | LATIN SMALL LETTER C WITH CARON
351 | 233 | E9 | é | LATIN SMALL LETTER E WITH ACUTE
352 | 234 | EA | ê | LATIN SMALL LETTER E WITH OGONEK
353 | 235 | EB | ë | LATIN SMALL LETTER E WITH DIAERESIS
354 | 236 | EC | ì | LATIN SMALL LETTER E WITH CARON
355 | 237 | ED | í | LATIN SMALL LETTER I WITH ACUTE
356 | 238 | EE | î | LATIN SMALL LETTER I WITH CIRCUMFLEX
357 | 239 | EF | ï | LATIN SMALL LETTER D WITH CARON
360 | 240 | F0 | ð | LATIN SMALL LETTER D WITH STROKE
361 | 241 | F1 | ñ | LATIN SMALL LETTER N WITH ACUTE
362 | 242 | F2 | ò | LATIN SMALL LETTER N WITH CARON
363 | 243 | F3 | ó | LATIN SMALL LETTER O WITH ACUTE
364 | 244 | F4 | ô | LATIN SMALL LETTER O WITH CIRCUMFLEX
365 | 245 | F5 | õ | LATIN SMALL LETTER O WITH DOUBLE ACUTE
366 | 246 | F6 | ö | LATIN SMALL LETTER O WITH DIAERESIS
367 | 247 | F7 | ÷ | DIVISION SIGN
370 | 248 | F8 | ø | LATIN SMALL LETTER R WITH CARON
371 | 249 | F9 | ù | LATIN SMALL LETTER U WITH RING ABOVE
372 | 250 | FA | ú | LATIN SMALL LETTER U WITH ACUTE
373 | 251 | FB | û | LATIN SMALL LETTER U WITH DOUBLE ACUTE
374 | 252 | FC | ü | LATIN SMALL LETTER U WITH DIAERESIS
375 | 253 | FD | ý | LATIN SMALL LETTER Y WITH ACUTE
376 | 254 | FE | þ | LATIN SMALL LETTER T WITH CEDILLA
377 | 255 | FF | ÿ | DOT ABOVE

SEE ALSO

ascii(7), iso_8859-1(7), iso_8859-16(7) Additional information: ISO 8859-2 (Latin 2) Resources (http://sizif.mf.uni-lj.si/linux/cee/iso8859-2.html).


utf8(7)

Status: 403 Forbidden utf8(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/utf8.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


LDP(7)

LDP Introduction

Section: Environments, Tables, and Troff Macros (7)
Updated: 2001-11-15 Return to Main Contents

NAME

LDP - Intro to the Linux Documentation Project, with help, guides and documents

SYNOPSIS

The Linux Documentation Project (LDP) provides a variety of free documentation resources including guides, FAQs, HOWTOs, and man-pages to the Linux community.

AUTHORS

The various documents in the LDP archives are maintained by individual authors, and are listed in the beginning of each HOWTO. If you have any questions or inputs to a document we encourage you to contact the authors directly.

WEB PAGES

The LDP has its own dedicated web site as do many of the various translations projects which are linked from the main LDP web site at
http://www.tldp.org/
which you may wish to bookmark.

MAN PAGES

A web page with status information for manual pages and translations is found at
http://www.win.tue.nl/~aeb/linux/man/

MAILING LISTS

LDP has a number of mailing lists, such as

<announce@en.tlpd.org> Announcements from the LDP project
<discuss@en.tldp.org>
General discussion on the LDP project
<docbook@en.tldp.org>
Questions about the use of DocBook

For subscription information, see the website.

If you are interested in DocBook beyond the simple markup of your LDP document, you may want to consider joining one of the OASIS DocBook mailing lists. Please see http://docbook.org/mailinglist/index.html for more information.

FILES

Most distributions include the HOWTOs and mini-HOWTOs in the installation
/usr/doc/ (old place for documentation)
/usr/share/doc/ (new place for documentation)
/usr/share/doc/HOWTO/ (HOWTO files)
/usr/share/doc/HOWTO/mini/ (mini-HOWTO files)

SEE ALSO

info(1), man(1), xman(1x)

info pages as read with emacs(1) or info(1)


ipv6(7)

IPV6

Section: Linux Programmer's Manual (7)
Updated: 1999-06-29 Return to Main Contents

NAME

ipv6, PF_INET6 - Linux IPv6 protocol implementation

SYNOPSIS

#include <sys/socket.h>
#include <netinet/in.h>

tcp6_socket = socket(PF_INET6, SOCK_STREAM, 0);
raw6_socket = socket(PF_INET6, SOCK_RAW, protocol);
udp6_socket = socket(PF_INET6, SOCK_DGRAM, protocol);

DESCRIPTION

Linux 2.2 optionally implements the Internet Protocol, version 6. This man page contains a description of the IPv6 basic API as implemented by the Linux kernel and glibc 2.1. The interface is based on the BSD sockets interface; see socket(7).

The IPv6 API aims to be mostly compatible with the ip(7) v4 API. Only differences are described in this man page.

To bind an AF_INET6 socket to any process the local address should be copied from the in6addr_any variable which has in6_addr type. In static initializations IN6ADDR_ANY_INIT may also be used, which expands to a constant expression. Both of them are in network order.

The IPv6 loopback address (::1) is available in the global in6addr_loopback variable. For initializations IN6ADDR_LOOPBACK_INIT should be used.

IPv4 connections can be handled with the v6 API by using the v4-mapped-on-v6 address type; thus a program only needs only to support this API type to support both protocols. This is handled transparently by the address handling functions in libc.

IPv4 and IPv6 share the local port space. When you get an IPv4 connection or packet to a IPv6 socket its source address will be mapped to v6 and it will be mapped to v6.

Address Format

struct sockaddr_in6 {
    u_int16_t       sin6_family;   /* AF_INET6 */
    u_int16_t       sin6_port;     /* port number */
    u_int32_t       sin6_flowinfo; /* IPv6 flow information */
    struct in6_addr sin6_addr;     /* IPv6 address */
    u_int32_t       sin6_scope_id; /* Scope ID (new in 2.4) */
};

struct in6_addr {
    unsigned char   s6_addr[16];   /* IPv6 address */
};

sin6_family is always set to AF_INET6; sin6_port is the protocol port (see sin_port in ip(7)); sin6_flowinfo is the IPv6 flow identifier; sin6_addr is the 128bit IPv6 address. sin6_scope_id is an ID of depending of on the scope of the address. It is new in Linux 2.4. Linux only supports it for link scope addresses, in that case sin6_scope_id contains the interface index (see netdevice(7))

IPv6 supports several address types: unicast to address a single host, multicast to address a group of hosts, anycast to address the nearest member of a group of hosts (not implemented in Linux), IPv4-on-IPv6 to address a IPv4 host, and other reserved address types.

The address notation for IPv6 is a group of 16 2 digit hexadecimal numbers, separated with a ':'. '::' stands for a string of 0 bits. Special addresses are ::1 for loopback and ::FFFF:<IPv4 address> for IPv4-mapped-on-IPv6.

The port space of IPv6 is shared with IPv4.

Socket Options

IPv6 supports some protocol specific socket options that can be set with setsockopt(2) and read with getsockopt(2). The socket option level for IPv6 is IPPROTO_IPV6. A boolean integer flag is zero when it is false, otherwise true.
IPV6_ADDRFORM
Turn an AF_INET6 socket into a socket of a different address family. Only AF_INET is currently supported for that. It is only allowed for IPv6 sockets that are connected and bound to a v4-mapped-on-v6 address. The argument is a pointer to a integer containing AF_INET. This is useful to pass v4-mapped sockets as file descriptors to programs that don't know how to deal with the IPv6 API.
IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP
Control membership in multicast groups. Argument is a pointer to a struct ipv6_mreq structure.
IPV6_MTU
Set the MTU to be used for the socket. The MTU is limited by the device MTU or the path mtu when path mtu discovery is enabled. Argument is a pointer to integer.
IPV6_MTU_DISCOVER
Control path mtu discovery on the socket. See IP_MTU_DISCOVER in ip(7) for details.
IPV6_MULTICAST_HOPS
Set the multicast hop limit for the socket. Argument is a pointer to an integer. -1 in the value means use the route default, otherwise it should be between 0 and 255.
IPV6_MULTICAST_IF
Set the device for outgoing multicast packets on the socket. This is only allowed for SOCK_DGRAM and SOCK_RAW socket. The argument is an pointer to an interface index (see netdevice(7)) in an integer.
IPV6_MULTICAST_LOOP
Control whether the socket sees multicast packets that it has send itself. Argument is a pointer to boolean.
IPV6_PKTINFO
Set delivery of the IPV6_PKTINFO control message on incoming datagrams. Only allowed for SOCK_DGRAM or SOCK_RAW sockets. Argument is a pointer to a boolean value in an integer.
IPV6_RTHDR, IPV6_AUTHHDR, IPV6_DSTOPS, IPV6_HOPOPTS, IPV6_FLOWINFO, IPV6_HOPLIMIT Set delivery of control messages for incoming datagrams containing extension headers from the received packet. IPV6_RTHDR delivers the routing header, IPV6_AUTHHDR delivers the authentication header, IPV6_DSTOPTS delivers the destination options, IPV6_HOPOPTS delivers the hop options, IPV6_FLOWINFO delivers an integer containing the flow ID, IPV6_HOPLIMIT delivers an integer containing the hop count of the packet. The control messages have the same type as the socket option. All these header options can also be set for outgoing packets by putting the appropriate control message into the control buffer of sendmsg(2). Only allowed for SOCK_DGRAM or SOCK_RAW sockets. Argument is a pointer to a boolean value.
IPV6_RECVERR
Control receiving of asynchronous error options. See IP_RECVERR in ip(7) for details. Argument is a pointer to boolean.
IPV6_ROUTER_ALERT
Pass all forwarded packets containing an router alert option to this socket. Only allowed for datagram sockets and for root. Argument is a pointer to boolean.
IPV6_UNICAST_HOPS
Set the unicast hop limit for the socket. Argument is an pointer to an integer. -1 in the value means use the route default, otherwise it should be between 0 and 255.

VERSIONS

The older libinet6 libc5 based IPv6 API implementation for Linux is not described here and may vary in details.

Linux 2.4 will break binary compatibility for the sockaddr_in6 for 64bit hosts by changing the alignment of in6_addr and adding an additional sin6_scope_id field. The kernel interfaces stay compatible, but a program including sockaddr_in6 or in6_addr into other structures may not be. This is not a problem for 32bit hosts like i386.

The sin6_flowinfo field is new in Linux 2.4. It is transparently passed/read by the kernel when the passed address length contains it. Some programs that pass a longer address buffer and then check the outgoing address length may break.

NOTES

The sockaddr_in6 structure is bigger than the generic sockaddr. Programs that assume that all address types can be stored safely in a struct sockaddr need to be changed to use struct sockaddr_storage for that instead.

BUGS

The IPv6 extended API as in RFC 2292 is currently only partly implemented; although the 2.2 kernel has near complete support for receiving options, the macros for generating IPv6 options are missing in glibc 2.1.

IPSec support for EH and AH headers is missing.

Flow label management is not complete and not documented here.

This man page is not complete.

SEE ALSO

cmsg(3), ip(7)

RFC 2553: IPv6 BASIC API. Linux tries to be compliant to this.

RFC 2460: IPv6 specification.


koi8-r(7)

KOI8-R

Section: Linux Programmer's Manual (7)
Updated: 2001-05-28 Return to Main Contents

NAME

koi8-r - Russian Net Character Set encoded in octal, decimal, and hexadecimal

DESCRIPTION

KOI8-R is the character set of choice for encoding Russian texts for many Unix-like operation systems. KOI8-R is a successor for KOI-8, a de-facto standard for Internet Mail, News, WWW and other interactive services at least all over the ex-SU territory.

KOI8-R is defined by RFC 1489 (Registration of a Cyrillic Character Set).

NOTES

KOI8-R was designed for mixed Russian/English texts and covers only Russian Cyrillic characters, so if you're looking for Ukrainian, Byelorussian, etc. Cyrillic characters, try ISO-IR-111, or KOI8-U (Ukrainian Character Set), or KOI8-C (for ancient Russian texts) instead, which are identical to KOI8-R in the Russian Cyrillic letters area.

A more complete set of Cyrillic characters is also defined by the ISO-8859-5 character set.

KOI8-R Characters

The following table displays the characters in KOI8-R, which are printable and unlisted in the ascii(7) manual page.

Oct | Dec | Hex | Char | Description
200 | 128 | 80 | € | FORMS LIGHT HORIZONTAL
201 | 129 | 81 |  | FORMS LIGHT VERTICAL
202 | 130 | 82 | ‚ | FORMS LIGHT DOWN AND RIGHT
203 | 131 | 83 | ƒ | FORMS LIGHT DOWN AND LEFT
204 | 132 | 84 | „ | FORMS LIGHT UP AND RIGHT
205 | 133 | 85 | … | FORMS LIGHT UP AND LEFT
206 | 134 | 86 | † | FORMS LIGHT VERTICAL AND RIGHT
207 | 135 | 87 | ‡ | FORMS LIGHT VERTICAL AND LEFT
210 | 136 | 88 | ˆ | FORMS LIGHT DOWN AND HORIZONTAL
211 | 137 | 89 | ‰ | FORMS LIGHT UP AND HORIZONTAL
212 | 138 | 8A | Š | FORMS LIGHT VERTICAL AND HORIZONTAL
213 | 139 | 8B | ‹ | UPPER HALF BLOCK
214 | 140 | 8C | Œ | LOWER HALF BLOCK
215 | 141 | 8D |  | FULL BLOCK
216 | 142 | 8E | Ž | LEFT HALF BLOCK
217 | 143 | 8F |  | RIGHT HALF BLOCK
220 | 144 | 90 |  | LIGHT SHADE
221 | 145 | 91 | ‘ | MEDIUM SHADE
222 | 146 | 92 | ’ | DARK SHADE
223 | 147 | 93 | “ | TOP HALF INTEGRAL
224 | 148 | 94 | ” | BLACK SMALL SQUARE
225 | 149 | 95 | • | BULLET OPERATOR
226 | 150 | 96 | – | SQUARE ROOT
227 | 151 | 97 | — | ALMOST EQUAL TO
230 | 152 | 98 | ˜ | LESS THAN OR EQUAL TO
231 | 153 | 99 | ™ | GREATER THAN OR EQUAL TO
232 | 154 | 9A | š | NON-BREAKING SPACE
233 | 155 | 9B | › | BOTTOM HALF INTEGRAL
234 | 156 | 9C | œ | DEGREE SIGN
235 | 157 | 9D |  | SUPERSCRIPT DIGIT TWO
236 | 158 | 9E | ž | MIDDLE DOT
237 | 159 | 9F | Ÿ | DIVISION SIGN
240 | 160 | A0 |  | FORMS DOUBLE HORIZONTAL
241 | 161 | A1 | ¡ | FORMS DOUBLE VERTICAL
242 | 162 | A2 | ¢ | FORMS DOWN SINGLE AND RIGHT DOUBLE
243 | 163 | A3 | £ | CYRILLIC SMALL LETTER IO
244 | 164 | A4 | ¤ | FORMS DOWN DOUBLE AND RIGHT SINGLE
245 | 165 | A5 | ¥ | FORMS DOUBLE DOWN AND RIGHT
246 | 166 | A6 | ¦ | FORMS DOWN SINGLE AND LEFT DOUBLE
247 | 167 | A7 | § | FORMS DOWN DOUBLE AND LEFT SINGLE
250 | 168 | A8 | ¨ | FORMS DOUBLE DOWN AND LEFT
251 | 169 | A9 | © | FORMS UP SINGLE AND RIGHT DOUBLE
252 | 170 | AA | ª | FORMS UP DOUBLE AND RIGHT SINGLE
253 | 171 | AB | « | FORMS DOUBLE UP AND RIGHT
254 | 172 | AC | ¬ | FORMS UP SINGLE AND LEFT DOUBLE
255 | 173 | AD |  | FORMS UP DOUBLE AND LEFT SINGLE
256 | 174 | AE | ® | FORMS DOUBLE UP AND LEFT
257 | 175 | AF | ¯ | FORMS VERTICAL SINGLE AND RIGHT DOUBLE
260 | 176 | B0 | ° | FORMS VERTICAL DOUBLE AND RIGHT SINGLE
261 | 177 | B1 | ± | FORMS DOUBLE VERTICAL AND RIGHT
262 | 178 | B2 | ² | FORMS VERTICAL SINGLE AND LEFT DOUBLE
263 | 179 | B3 | ³ | CYRILLIC CAPITAL LETTER IO
264 | 180 | B4 | ´ | FORMS VERTICAL DOUBLE AND LEFT SINGLE
265 | 181 | B5 | µ | FORMS DOUBLE VERTICAL AND LEFT
266 | 182 | B6 | ¶ | FORMS DOWN SINGLE AND HORIZONTAL DOUBLE
267 | 183 | B7 | · | FORMS DOWN DOUBLE AND HORIZONTAL SINGLE
270 | 184 | B8 | ¸ | FORMS DOUBLE DOWN AND HORIZONTAL
271 | 185 | B9 | ¹ | FORMS UP SINGLE AND HORIZONTAL DOUBLE
272 | 186 | BA | º | FORMS UP DOUBLE AND HORIZONTAL SINGLE
273 | 187 | BB | » | FORMS DOUBLE UP AND HORIZONTAL
274 | 188 | BC | ¼ | FORMS VERTICAL SINGLE AND HORIZONTAL DOUBLE
275 | 189 | BD | ½ | FORMS VERTICAL DOUBLE AND HORIZONTAL SINGLE
276 | 190 | BE | ¾ | FORMS DOUBLE VERTICAL AND HORIZONTAL
277 | 191 | BF | ¿ | COPYRIGHT SIGN
300 | 192 | C0 | À | CYRILLIC SMALL LETTER IU
301 | 193 | C1 | Á | CYRILLIC SMALL LETTER A
302 | 194 | C2 | Â | CYRILLIC SMALL LETTER BE
303 | 195 | C3 | Ã | CYRILLIC SMALL LETTER TSE
304 | 196 | C4 | Ä | CYRILLIC SMALL LETTER DE
305 | 197 | C5 | Å | CYRILLIC SMALL LETTER IE
306 | 198 | C6 | Æ | CYRILLIC SMALL LETTER EF
307 | 199 | C7 | Ç | CYRILLIC SMALL LETTER GE
310 | 200 | C8 | È | CYRILLIC SMALL LETTER KHA
311 | 201 | C9 | É | CYRILLIC SMALL LETTER II
312 | 202 | CA | Ê | CYRILLIC SMALL LETTER SHORT II
313 | 203 | CB | Ë | CYRILLIC SMALL LETTER KA
314 | 204 | CC | Ì | CYRILLIC SMALL LETTER EL
315 | 205 | CD | Í | CYRILLIC SMALL LETTER EM
316 | 206 | CE | Î | CYRILLIC SMALL LETTER EN
317 | 207 | CF | Ï | CYRILLIC SMALL LETTER O
320 | 208 | D0 | Ð | CYRILLIC SMALL LETTER PE
321 | 209 | D1 | Ñ | CYRILLIC SMALL LETTER IA
322 | 210 | D2 | Ò | CYRILLIC SMALL LETTER ER
323 | 211 | D3 | Ó | CYRILLIC SMALL LETTER ES
324 | 212 | D4 | Ô | CYRILLIC SMALL LETTER TE
325 | 213 | D5 | Õ | CYRILLIC SMALL LETTER U
326 | 214 | D6 | Ö | CYRILLIC SMALL LETTER ZHE
327 | 215 | D7 | × | CYRILLIC SMALL LETTER VE
330 | 216 | D8 | Ø | CYRILLIC SMALL LETTER SOFT SIGN
331 | 217 | D9 | Ù | CYRILLIC SMALL LETTER YERI
332 | 218 | DA | Ú | CYRILLIC SMALL LETTER ZE
333 | 219 | DB | Û | CYRILLIC SMALL LETTER SHA
334 | 220 | DC | Ü | CYRILLIC SMALL LETTER REVERSED E
335 | 221 | DD | Ý | CYRILLIC SMALL LETTER SHCHA
336 | 222 | DE | Þ | CYRILLIC SMALL LETTER CHE
337 | 223 | DF | ß | CYRILLIC SMALL LETTER HARD SIGN
340 | 224 | E0 | à | CYRILLIC CAPITAL LETTER IU
341 | 225 | E1 | á | CYRILLIC CAPITAL LETTER A
342 | 226 | E2 | â | CYRILLIC CAPITAL LETTER BE
343 | 227 | E3 | ã | CYRILLIC CAPITAL LETTER TSE
344 | 228 | E4 | ä | CYRILLIC CAPITAL LETTER DE
345 | 229 | E5 | å | CYRILLIC CAPITAL LETTER IE
346 | 230 | E6 | æ | CYRILLIC CAPITAL LETTER EF
347 | 231 | E7 | ç | CYRILLIC CAPITAL LETTER GE
350 | 232 | E8 | è | CYRILLIC CAPITAL LETTER KHA
351 | 233 | E9 | é | CYRILLIC CAPITAL LETTER II
352 | 234 | EA | ê | CYRILLIC CAPITAL LETTER SHORT II
353 | 235 | EB | ë | CYRILLIC CAPITAL LETTER KA
354 | 236 | EC | ì | CYRILLIC CAPITAL LETTER EL
355 | 237 | ED | í | CYRILLIC CAPITAL LETTER EM
356 | 238 | EE | î | CYRILLIC CAPITAL LETTER EN
357 | 239 | EF | ï | CYRILLIC CAPITAL LETTER O
360 | 240 | F0 | ð | CYRILLIC CAPITAL LETTER PE
361 | 241 | F1 | ñ | CYRILLIC CAPITAL LETTER IA
362 | 242 | F2 | ò | CYRILLIC CAPITAL LETTER ER
363 | 243 | F3 | ó | CYRILLIC CAPITAL LETTER ES
364 | 244 | F4 | ô | CYRILLIC CAPITAL LETTER TE
365 | 245 | F5 | õ | CYRILLIC CAPITAL LETTER U
366 | 246 | F6 | ö | CYRILLIC CAPITAL LETTER ZHE
367 | 247 | F7 | ÷ | CYRILLIC CAPITAL LETTER VE
370 | 248 | F8 | ø | CYRILLIC CAPITAL LETTER SOFT SIGN
371 | 249 | F9 | ù | CYRILLIC CAPITAL LETTER YERI
372 | 250 | FA | ú | CYRILLIC CAPITAL LETTER ZE
373 | 251 | FB | û | CYRILLIC CAPITAL LETTER SHA
374 | 252 | FC | ü | CYRILLIC CAPITAL LETTER REVERSED E
375 | 253 | FD | ý | CYRILLIC CAPITAL LETTER SHCHA
376 | 254 | FE | þ | CYRILLIC CAPITAL LETTER CHE
377 | 255 | FF | ÿ | CYRILLIC CAPITAL LETTER HARD SIGN

SEE ALSO

ascii(7), iso-8859-7(7) (not yet written), RFC 1489, http://koi8.pp.ru/


units(7)

UNITS

Section: Linux Programmer's Manual (7)
Updated: 2001-12-22 Return to Main Contents

NAME

units, kilo, kibi, mega, mebi, giga, gibi - decimal and binary prefixes

DESCRIPTION

Decimal prefixes

The SI system of units uses prefixes that indicate powers of ten. A kilometer is 1000 meter, and a megawatt is 1000000 watt. Below the standard prefixes.
Prefix Name Value
y yocto 10^-24 = 0.000000000000000000000001
z zepto 10^-21 = 0.000000000000000000001
a atto 10^-18 = 0.000000000000000001
f femto 10^-15 = 0.000000000000001
p pico 10^-12 = 0.000000000001
n nano 10^-9 = 0.000000001
u micro 10^-6 = 0.000001
m milli 10^-3 = 0.001
c centi 10^-2 = 0.01
d deci 10^-1 = 0.1
da deka 10^ 1 = 10
h hecto 10^ 2 = 100
k kilo 10^ 3 = 1000
M mega 10^ 6 = 1000000
G giga 10^ 9 = 1000000000
T tera 10^12 = 1000000000000
P peta 10^15 = 1000000000000000
E exa 10^18 = 1000000000000000000
Z zetta 10^21 = 1000000000000000000000
Y yotta 10^24 = 1000000000000000000000000

The symbol for micro is the Greek letter mu, often written u in an ASCII context where this Greek letter is not available. See also

http://physics.nist.gov/cuu/Units/prefixes.html

Binary prefixes

The binary prefixes resemble the decimal ones, but have an additional 'i' (and "Ki" starts with a capital 'K'). The names are formed by taking the first syllable of the names of the decimal prefix with roughly the same size, followed by "bi" for "binary".
Prefix Name Value
Ki kibi 2^10 = 1024
Mi mebi 2^20 = 1048576
Gi gibi 2^30 = 1073741824
Ti tebi 2^40 = 1099511627776
Pi pebi 2^50 = 1125899906842624
Ei exbi 2^60 = 1152921504606846976

See also

http://physics.nist.gov/cuu/Units/binary.html

Discussion

Before these binary prefixes were introduced, it was fairly common to use k=1000 and K=1024, just like b=bit, B=byte. Unfortunately, the M is capital already, and cannot be capitalized to indicate binary-ness.

At first that didn't matter too much, since memory modules and disks came in sizes that were powers of two, so everyone knew that in such contexts "kilobyte" and "megabyte" meant 1024 and 1048576 bytes, respectively. What originally was a sloppy use of the prefixes "kilo" and "mega" started to become regarded as the "real true meaning" when computers were involved. But then disk technology changed, and disk sizes became arbitrary numbers. After a period of uncertainty all disk manufacturers settled on the standard, namely k=1000, M=1000k, G=1000M.

The situation was messy: in the 14k4 modems, k=1000; in the 1.44MB diskettes, M=1024000; etc. In 1998 the IEC approved the standard that defines the binary prefixes given above, enabling people to be precise and unambiguous.

Thus, today, MB = 1000000B and MiB = 1048576B.

In the free software world programs are slowly being changed to conform. When the Linux kernel boots and says

hda: 120064896 sectors (61473 MB) w/2048KiB Cache

the MB are megabytes and the KiB are kibibytes.


boot(7)

BOOT

Section: Linux Programmer's Manual (7)
Updated: 2007-06-03 Return to Main Contents

NAME

boot-scripts - General description of boot sequence

DESCRIPTION

The boot sequence varies in details among systems but can be roughly divided to the following steps: (i) hardware boot, (ii) OS loader, (iii) kernel startup, (iv) init and inittab, (v) boot scripts. We will describe each of these in more detail below.

Hardware-boot

After power-on or hard reset, control is given to a program stored on read only memory (normally PROM). In PC we usually call this program the BIOS.

This program normally makes a basic self-test of the machine and accesses non-volatile memory to read further parameters. This memory in the PC is battery-backed CMOS memory, so most people refer to it as the CMOS, although outside of the PC world, it is usually called nvram (non-volatile ram).

The parameters stored in the nvram vary between systems, but as a minimum, the hardware boot program should know what is the boot device, or which devices to probe as possible boot devices.

Then the hardware boot stage accesses the boot device, loads the OS Loader, which is located on a fixed position on the boot device, and transfers control to it.

Note:
We do not cover here booting from network. Those who want to investigate this subject may want to research: DHCP, TFTP, PXE, Etherboot.

OS Loader

In PC, the OS Loader is located in the first sector of the boot device - this is the MBR (Master Boot Record).

In most systems, this primary loader is very limited due to various constraints. Even on non-PC systems there are some limitations to the size and complexity of this loader, but the size limitation of the PC MBR (512 bytes including the partition table) makes it almost impossible to squeeze a full OS Loader into it.

Therefore, most operating systems make the primary loader call a secondary OS loader which may be located on a specified disk partition.

In Linux the OS loader is normally lilo(8) or grub(8). Both of them may install either as secondary loaders (where the DOS installed MBR points to them), or as a two part loader where they provide special MBR containing the bootstrap code to load the second part of the loader from the root partition.

The main job of the OS Loader is to locate the kernel on the disk, load it and run it. Most OS loaders allow interactive use, to enable specification of alternative kernel (maybe a backup in case the last compiled one isn't functioning) and to pass optional parameters to the kernel.

Kernel Startup

When the kernel is loaded, it initializes the devices (via their drivers), starts the swapper (it is a "kernel process", called kswapd in modern Linux kernels), and mounts the root file system (/).

Some of the parameters that may be passed to the kernel relate to these activities (e.g: You can override the default root file system). For further information on Linux kernel parameters read bootparam(7).

Only then the kernel creates the first (user land) process which is numbered 1. This process executes the program /sbin/init, passing any parameters that weren't handled by the kernel already.

init and inittab

When init starts it reads /etc/inittab for further instructions. This file defines what should be run in different run-levels.

This gives the system administrator an easy management scheme, where each run-level is associated with a set of services (e.g: S is single-user, on 2 most network services start, etc.). The administrator may change the current run-level via init(8) and query the current run-level via runlevel(8).

However, since it is not convenient to manage individual services by editing this file, inittab only bootstraps a set of scripts that actually start/stop the individual services.

Boot Scripts

Note:
The following description applies to System V release 4 based system, which currently covers most commercial Unix systems (Solaris, HP-UX, Irix, Tru64) as well as the major Linux distributions (RedHat, Debian, Mandrake, Suse, Caldera). Some systems (Slackware Linux, FreeBSD, OpenBSD) have a somewhat different scheme of boot scripts.

For each managed service (mail, nfs server, cron, etc.) there is a single startup script located in a specific directory (/etc/init.d in most versions of Linux). Each of these scripts accepts as a single argument the word 'start' -- causing it to start the service, or the word 'stop' -- causing it to stop the service. The script may optionally accept other "convenience" parameters (e.g: 'restart', to stop and then start, 'status' do display the service status). Running the script without parameters displays the possible arguments.

Sequencing Directories

To make specific scripts start/stop at specific run-levels and in specific order, there are sequencing directories. These are normally in /etc/rc[0-6S].d. In each of these directories there are links (usually symbolic) to the scripts in the init.d directory.

A primary script (usually /etc/rc) is called from inittab(5) and calls the services scripts via the links in the sequencing directories. All links with names that begin with 'S' are being called with the argument 'start' (thereby starting the service). All links with names that begin with 'K' are being called with the argument 'stop' (thereby stopping the service).

To define the starting or stopping order within the same run-level, the names of the links contain order-numbers. Also, to make the names clearer, they usually end with the name of the service they refer to. Example: the link /etc/rc2.d/S80sendmail starts the sendmail service on runlevel 2. This happens after /etc/rc2.d/S12syslog is run but before /etc/rc2.d/S90xfs is run.

To manage the boot order and run-levels, we have to manage these links. However, on many versions of Linux, there are tools to help with this task (e.g: chkconfig(8)).

Boot Configuration

Usually the daemons started may optionally receive command line options and parameters. To allow system administrators to change these parameters without editing the boot scripts themselves, configuration files are used. These are located in a specific directory (/etc/sysconfig on RedHat systems) and are used by the boot scripts.

In older Unix systems, these files contained the actual command line options for the daemons, but in modern Linux systems (and also in HP-UX), these files just contain shell variables. The boot scripts in /etc/init.d source the configuration files, and then use the variable values.

FILES

/etc/init.d/, /etc/rc[S0-6].d/, /etc/sysconfig/

SEE ALSO

inittab(5), bootparam(7), init(8), runlevel(8), shutdown(8)


iso-8859-9(7)

Status: 403 Forbidden iso-8859-9(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso-8859-9.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


iso_8859-9(7)

ISO_8859-9

Section: Linux Programmer's Manual (7)
Updated: 2002-09-24 Return to Main Contents

NAME

iso_8859-9 - the ISO 8859-9 character set encoded in octal, decimal, and hexadecimal

DESCRIPTION

The ISO 8859 standard includes several 8-bit extensions to the ASCII character set (also known as ISO 646-IRV). ISO 8859-9, also known as the "Latin Alphabet No. 5", encodes the characters used in Turkish.

ISO 8859 Alphabets

The full set of ISO 8859 alphabets includes:
ISO 8859-1 | West European languages (Latin-1)
ISO 8859-2 | Central and East European languages (Latin-2)
ISO 8859-3 | Southeast European and miscellaneous languages (Latin-3)
ISO 8859-4 | Scandinavian/Baltic languages (Latin-4)
ISO 8859-5 | Latin/Cyrillic
ISO 8859-6 | Latin/Arabic
ISO 8859-7 | Latin/Greek
ISO 8859-8 | Latin/Hebrew
ISO 8859-9 | Latin-1 modification for Turkish (Latin-5)
ISO 8859-10 | Lappish/Nordic/Eskimo languages (Latin-6)
ISO 8859-11 | Latin/Thai
ISO 8859-13 | Baltic Rim languages (Latin-7)
ISO 8859-14 | Celtic (Latin-8)
ISO 8859-15 | West European languages (Latin-9)
ISO 8859-16 | Romanian (Latin-10)

ISO 8859-9 Characters

The following table displays the characters in ISO 8859-9 (Latin-5), which are printable and unlisted in the ascii(7) manual page. The fourth column will only show the proper glyphs in an environment configured for ISO 8859-9.
Oct | Dec | Hex | Char | Description
240 | 160 | A0 |  | NO-BREAK SPACE
241 | 161 | A1 | ¡ | INVERTED EXCLAMATION MARK
242 | 162 | A2 | ¢ | CENT SIGN
243 | 163 | A3 | £ | POUND SIGN
244 | 164 | A4 | ¤ | CURRENCY SIGN
245 | 165 | A5 | ¥ | YEN SIGN
246 | 166 | A6 | ¦ | BROKEN BAR
247 | 167 | A7 | § | SECTION SIGN
250 | 168 | A8 | ¨ | DIAERESIS
251 | 169 | A9 | © | COPYRIGHT SIGN
252 | 170 | AA | ª | FEMININE ORDINAL INDICATOR
253 | 171 | AB | « | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
254 | 172 | AC | ¬ | NOT SIGN
255 | 173 | AD |  | SOFT HYPHEN
256 | 174 | AE | ® | REGISTERED SIGN
257 | 175 | AF | ¯ | MACRON
260 | 176 | B0 | ° | DEGREE SIGN
261 | 177 | B1 | ± | PLUS-MINUS SIGN
262 | 178 | B2 | ² | SUPERSCRIPT TWO
263 | 179 | B3 | ³ | SUPERSCRIPT THREE
264 | 180 | B4 | ´ | ACUTE ACCENT
265 | 181 | B5 | µ | MICRO SIGN
266 | 182 | B6 | ¶ | PILCROW SIGN
267 | 183 | B7 | · | MIDDLE DOT
270 | 184 | B8 | ¸ | CEDILLA
271 | 185 | B9 | ¹ | SUPERSCRIPT ONE
272 | 186 | BA | º | MASCULINE ORDINAL INDICATOR
273 | 187 | BB | » | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
274 | 188 | BC | ¼ | VULGAR FRACTION ONE QUARTER
275 | 189 | BD | ½ | VULGAR FRACTION ONE HALF
276 | 190 | BE | ¾ | VULGAR FRACTION THREE QUARTERS
277 | 191 | BF | ¿ | INVERTED QUESTION MARK
300 | 192 | C0 | À | LATIN CAPITAL LETTER A WITH GRAVE
301 | 193 | C1 | Á | LATIN CAPITAL LETTER A WITH ACUTE
302 | 194 | C2 | Â | LATIN CAPITAL LETTER A WITH CIRCUMFLEX
303 | 195 | C3 | Ã | LATIN CAPITAL LETTER A WITH TILDE
304 | 196 | C4 | Ä | LATIN CAPITAL LETTER A WITH DIAERESIS
305 | 197 | C5 | Å | LATIN CAPITAL LETTER A WITH RING ABOVE
306 | 198 | C6 | Æ | LATIN CAPITAL LETTER AE
307 | 199 | C7 | Ç | LATIN CAPITAL LETTER C WITH CEDILLA
310 | 200 | C8 | È | LATIN CAPITAL LETTER E WITH GRAVE
311 | 201 | C9 | É | LATIN CAPITAL LETTER E WITH ACUTE
312 | 202 | CA | Ê | LATIN CAPITAL LETTER E WITH CIRCUMFLEX
313 | 203 | CB | Ë | LATIN CAPITAL LETTER E WITH DIAERESIS
314 | 204 | CC | Ì | LATIN CAPITAL LETTER I WITH GRAVE
315 | 205 | CD | Í | LATIN CAPITAL LETTER I WITH ACUTE
316 | 206 | CE | Î | LATIN CAPITAL LETTER I WITH CIRCUMFLEX
317 | 207 | CF | Ï | LATIN CAPITAL LETTER I WITH DIAERESIS
320 | 208 | D0 | Ð | LATIN CAPITAL LETTER G WITH BREVE
321 | 209 | D1 | Ñ | LATIN CAPITAL LETTER N WITH TILDE
322 | 210 | D2 | Ò | LATIN CAPITAL LETTER O WITH GRAVE
323 | 211 | D3 | Ó | LATIN CAPITAL LETTER O WITH ACUTE
324 | 212 | D4 | Ô | LATIN CAPITAL LETTER O WITH CIRCUMFLEX
325 | 213 | D5 | Õ | LATIN CAPITAL LETTER O WITH TILDE
326 | 214 | D6 | Ö | LATIN CAPITAL LETTER O WITH DIAERESIS
327 | 215 | D7 | × | MULTIPLICATION SIGN
330 | 216 | D8 | Ø | LATIN CAPITAL LETTER O WITH STROKE
331 | 217 | D9 | Ù | LATIN CAPITAL LETTER U WITH GRAVE
332 | 218 | DA | Ú | LATIN CAPITAL LETTER U WITH ACUTE
333 | 219 | DB | Û | LATIN CAPITAL LETTER U WITH CIRCUMFLEX
334 | 220 | DC | Ü | LATIN CAPITAL LETTER U WITH DIAERESIS
335 | 221 | DD | Ý | LATIN CAPITAL LETTER I WITH DOT ABOVE
336 | 222 | DE | Þ | LATIN CAPITAL LETTER S WITH CEDILLA
337 | 223 | DF | ß | LATIN SMALL LETTER SHARP S
340 | 224 | E0 | à | LATIN SMALL LETTER A WITH GRAVE
341 | 225 | E1 | á | LATIN SMALL LETTER A WITH ACUTE
342 | 226 | E2 | â | LATIN SMALL LETTER A WITH CIRCUMFLEX
343 | 227 | E3 | ã | LATIN SMALL LETTER A WITH TILDE
344 | 228 | E4 | ä | LATIN SMALL LETTER A WITH DIAERESIS
345 | 229 | E5 | å | LATIN SMALL LETTER A WITH RING ABOVE
346 | 230 | E6 | æ | LATIN SMALL LETTER AE
347 | 231 | E7 | ç | LATIN SMALL LETTER C WITH CEDILLA
350 | 232 | E8 | è | LATIN SMALL LETTER E WITH GRAVE
351 | 233 | E9 | é | LATIN SMALL LETTER E WITH ACUTE
352 | 234 | EA | ê | LATIN SMALL LETTER E WITH CIRCUMFLEX
353 | 235 | EB | ë | LATIN SMALL LETTER E WITH DIAERESIS
354 | 236 | EC | ì | LATIN SMALL LETTER I WITH GRAVE
355 | 237 | ED | í | LATIN SMALL LETTER I WITH ACUTE
356 | 238 | EE | î | LATIN SMALL LETTER I WITH CIRCUMFLEX
357 | 239 | EF | ï | LATIN SMALL LETTER I WITH DIAERESIS
360 | 240 | F0 | ð | LATIN SMALL LETTER G WITH BREVE
361 | 241 | F1 | ñ | LATIN SMALL LETTER N WITH TILDE
362 | 242 | F2 | ò | LATIN SMALL LETTER O WITH GRAVE
363 | 243 | F3 | ó | LATIN SMALL LETTER O WITH ACUTE
364 | 244 | F4 | ô | LATIN SMALL LETTER O WITH CIRCUMFLEX
365 | 245 | F5 | õ | LATIN SMALL LETTER O WITH TILDE
366 | 246 | F6 | ö | LATIN SMALL LETTER O WITH DIAERESIS
367 | 247 | F7 | ÷ | DIVISION SIGN
370 | 248 | F8 | ø | LATIN SMALL LETTER O WITH STROKE
371 | 249 | F9 | ù | LATIN SMALL LETTER U WITH GRAVE
372 | 250 | FA | ú | LATIN SMALL LETTER U WITH ACUTE
373 | 251 | FB | û | LATIN SMALL LETTER U WITH CIRCUMFLEX
374 | 252 | FC | ü | LATIN SMALL LETTER U WITH DIAERESIS
375 | 253 | FD | ý | LATIN SMALL LETTER DOTLESS I
376 | 254 | FE | þ | LATIN SMALL LETTER S WITH CEDILLA
377 | 255 | FF | ÿ | LATIN SMALL LETTER Y WITH DIAERESIS

SEE ALSO

ascii(7)


iso_8859_9(7)

Status: 403 Forbidden iso_8859_9(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso_8859_9.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


capabilities(7)

CAPABILITIES

Section: Linux Programmer's Manual (7)
Updated: 2006-07-31 Return to Main Contents

NAME

capabilities - overview of Linux capabilities

DESCRIPTION

For the purpose of performing permission checks, traditional Unix implementations distinguish two categories of processes: privileged processes (whose effective user ID is 0, referred to as superuser or root), and unprivileged processes (whose effective UID is non-zero). Privileged processes bypass all kernel permission checks, while unprivileged processes are subject to full permission checking based on the process's credentials (usually: effective UID, effective GID, and supplementary group list).

Starting with kernel 2.2, Linux divides the privileges traditionally associated with superuser into distinct units, known as capabilities, which can be independently enabled and disabled. Capabilities are a per-thread attribute.

Capabilities List

As at Linux 2.6.14, the following capabilities are implemented:

CAP_AUDIT_CONTROL (since Linux 2.6.11)
Enable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules.
CAP_AUDIT_WRITE (since Linux 2.6.11)
Allow records to be written to kernel auditing log.
CAP_CHOWN
Allow arbitrary changes to file UIDs and GIDs (see chown(2)).
CAP_DAC_OVERRIDE
Bypass file read, write, and execute permission checks. (DAC = "discretionary access control".)
CAP_DAC_READ_SEARCH
Bypass file read permission checks and directory read and execute permission checks.
CAP_FOWNER
Bypass permission checks on operations that normally require the file system UID of the process to match the UID of the file (e.g., chmod(2), utime(2)), excluding those operations covered by the CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH; set extended file attributes (see chattr(1)) on arbitrary files; set Access Control Lists (ACLs) on arbitrary files; ignore directory sticky bit on file deletion; specify O_NOATIME for arbitrary files in open(2) and fcntl(2).
CAP_FSETID
Don't clear set-user-ID and set-group-ID bits when a file is modified; permit setting of the set-group-ID bit for a file whose GID does not match the file system or any of the supplementary GIDs of the calling process.
CAP_IPC_LOCK
Permit memory locking
(mlock(2),

mlockall(2),

mmap(2),

shmctl(2)).
CAP_IPC_OWNER
Bypass permission checks for operations on System V IPC objects.
CAP_KILL
Bypass permission checks for sending signals (see kill(2)). This includes use of the KDSIGACCEPT ioctl.
CAP_LEASE
(Linux 2.4 onwards) Allow file leases to be established on arbitrary files (see fcntl(2)).
CAP_LINUX_IMMUTABLE
Allow setting of the EXT2_APPEND_FL and EXT2_IMMUTABLE_FL extended file attributes (see chattr(1)).
CAP_MKNOD
(Linux 2.4 onwards) Allow creation of special files using mknod(2).
CAP_NET_ADMIN
Allow various network-related operations (e.g., setting privileged socket options, enabling multicasting, interface configuration, modifying routing tables).
CAP_NET_BIND_SERVICE
Allow binding to Internet domain reserved socket ports (port numbers less than 1024).
CAP_NET_BROADCAST
(Unused) Allow socket broadcasting, and listening multicasts.
CAP_NET_RAW
Permit use of RAW and PACKET sockets.
CAP_SETGID
Allow arbitrary manipulations of process GIDs and supplementary GID list; allow forged GID when passing socket credentials via Unix domain sockets.
CAP_SETPCAP
Grant or remove any capability in the caller's permitted capability set to or from any other process.
CAP_SETUID
Allow arbitrary manipulations of process UIDs
(setuid(2),

setreuid(2),

setresuid(2),

setfsuid(2));

allow forged UID when passing socket credentials via Unix domain sockets.
CAP_SYS_ADMIN
Permit a range of system administration operations including: quotactl(2), mount(2), umount(2), swapon(2), swapoff(2), sethostname(2), setdomainname(2), IPC_SET and IPC_RMID operations on arbitrary System V IPC objects; perform operations on trusted and security Extended Attributes (see attr(5)); call lookup_dcookie(2); use ioprio_set(2) to assign IOPRIO_CLASS_RT and IOPRIO_CLASS_IDLE I/O scheduling classes; perform keyctl(2) KEYCTL_CHOWN and KEYCTL_SETPERM operations. allow forged UID when passing socket credentials; exceed /proc/sys/fs/file-max, the system-wide limit on the number of open files, in system calls that open files (e.g., accept(2), execve(2), open(2), pipe(2); without this capability these system calls will fail with the error ENFILE if this limit is encountered); employ CLONE_NEWNS flag with clone(2) and unshare(2); perform KEYCTL_CHOWN and KEYCTL_SETPERM keyctl(2) operations.
CAP_SYS_BOOT
Permit calls to reboot(2) and kexec_load(2).
CAP_SYS_CHROOT
Permit calls to chroot(2).
CAP_SYS_MODULE
Allow loading and unloading of kernel modules; allow modifications to capability bounding set (see init_module(2) and delete_module(2)).
CAP_SYS_NICE
Allow raising process nice value (nice(2), setpriority(2)) and changing of the nice value for arbitrary processes; allow setting of real-time scheduling policies for calling process, and setting scheduling policies and priorities for arbitrary processes (sched_setscheduler(2), sched_setparam(2)); set CPU affinity for arbitrary processes (sched_setaffinity(2)); set I/O scheduling class and priority for arbitrary processes (ioprio_set(2)); allow migrate_pages(2) to be applied to arbitrary processes and allow processes to be migrated to arbitrary nodes; allow move_pages(2) to be applied to arbitrary processes; use the MPOL_MF_MOVE_ALL flag with mbind(2) and move_pages(2).
CAP_SYS_PACCT
Permit calls to acct(2).
CAP_SYS_PTRACE
Allow arbitrary processes to be traced using ptrace(2)
CAP_SYS_RAWIO
Permit I/O port operations (iopl(2) and ioperm(2)); access /proc/kcore.
CAP_SYS_RESOURCE
Permit: use of reserved space on ext2 file systems; ioctl(2) calls controlling ext3 journaling; disk quota limits to be overridden; resource limits to be increased (see setrlimit(2)); RLIMIT_NPROC resource limit to be overridden; msg_qbytes limit for a message queue to be raised above the limit in /proc/sys/kernel/msgmnb (see msgop(2) and msgctl(2).
CAP_SYS_TIME
Allow modification of system clock
(settimeofday(2),

stime(2),

adjtimex(2));

allow modification of real-time (hardware) clock
CAP_SYS_TTY_CONFIG
Permit calls to vhangup(2).

Capability Sets

Each thread has three capability sets containing zero or more of the above capabilities:
Effective:
the capabilities used by the kernel to perform permission checks for the thread.
Permitted:
the capabilities that the thread may assume (i.e., a limiting superset for the effective and inheritable sets). If a thread drops a capability from its permitted set, it can never re-acquire that capability (unless it execve(2)s a set-user-ID-root program).
inheritable:
the capabilities preserved across an execve(2).

A child created via fork(2) inherits copies of its parent's capability sets. See below for a discussion of the treatment of capabilities during execve(2).

Using capset(2), a thread may manipulate its own capability sets, or, if it has the CAP_SETPCAP capability, those of a thread in another process.

Capability bounding set

When a program is execed, the permitted and effective capabilities are ANDed with the current value of the so-called capability bounding set, defined in the file /proc/sys/kernel/cap-bound. This parameter can be used to place a system-wide limit on the capabilities granted to all subsequently executed programs. (Confusingly, this bit mask parameter is expressed as a signed decimal number in /proc/sys/kernel/cap-bound.)

Only the init process may set bits in the capability bounding set; other than that, the superuser may only clear bits in this set.

On a standard system the capability bounding set always masks out the CAP_SETPCAP capability. To remove this restriction (dangerous!), modify the definition of CAP_INIT_EFF_SET in include/linux/capability.h and rebuild the kernel.

The capability bounding set feature was added to Linux starting with kernel version 2.2.11.

Current and Future Implementation

A full implementation of capabilities requires:
1.
that for all privileged operations, the kernel check whether the thread has the required capability in its effective set.
2.
that the kernel provide system calls allowing a thread's capability sets to be changed and retrieved.
3.
file system support for attaching capabilities to an executable file, so that a process gains those capabilities when the file is execed.

As at Linux 2.6.14, only the first two of these requirements are met.

Eventually, it should be possible to associate three capability sets with an executable file, which, in conjunction with the capability sets of the thread, will determine the capabilities of a thread after an execve(2):

Inheritable (formerly known as allowed):
this set is ANDed with the thread's inheritable set to determine which inheritable capabilities are permitted to the thread after the execve(2).
Permitted (formerly known as forced):
the capabilities automatically permitted to the thread, regardless of the thread's inheritable capabilities.
Effective:
those capabilities in the thread's new permitted set are also to be set in the new effective set. (F(effective) would normally be either all zeroes or all ones.)

In the meantime, since the current implementation does not support file capability sets, during an execve(2):

1.
All three file capability sets are initially assumed to be cleared.
2.
If a set-user-ID-root program is being execed, or the real user ID of the process is 0 (root) then the file inheritable and permitted sets are defined to be all ones (i.e., all capabilities enabled).
3.
If a set-user-ID-root program is being executed, then the file effective set is defined to be all ones.

Transformation of Capabilities During exec()

During an execve(2), the kernel calculates the new capabilities of the process using the following algorithm:

P'(permitted) = (P(inheritable) & F(inheritable)) |
                (F(permitted) & cap_bset)

P'(effective) = P'(permitted) & F(effective)

P'(inheritable) = P(inheritable)    [i.e., unchanged]
where:
P
denotes the value of a thread capability set before the execve(2)
P'
denotes the value of a capability set after the execve(2)
F
denotes a file capability set
cap_bset
is the value of the capability bounding set.

In the current implementation, the upshot of this algorithm is that when a process execve(2)s a set-user-ID-root program, or when a process with an effective UID of 0 execve(2)s a program, it gains all capabilities in its permitted and effective capability sets, except those masked out by the capability bounding set (i.e., CAP_SETPCAP). This provides semantics that are the same as those provided by traditional Unix systems.

Effect of User ID Changes on Capabilities

To preserve the traditional semantics for transitions between 0 and non-zero user IDs, the kernel makes the following changes to a thread's capability sets on changes to the thread's real, effective, saved set, and file system user IDs (using setuid(2), setresuid(2), or similar):
1.
If one or more of the real, effective or saved set user IDs was previously 0, and as a result of the UID changes all of these IDs have a non-zero value, then all capabilities are cleared from the permitted and effective capability sets.
2.
If the effective user ID is changed from 0 to non-zero, then all capabilities are cleared from the effective set.
3.
If the effective user ID is changed from non-zero to 0, then the permitted set is copied to the effective set.
4.
If the file system user ID is changed from 0 to non-zero (see setfsuid(2)) then the following capabilities are cleared from the effective set: CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH, CAP_FOWNER, and CAP_FSETID. If the file system UID is changed from non-zero to 0, then any of these capabilities that are enabled in the permitted set are enabled in the effective set.

If a thread that has a 0 value for one or more of its user IDs wants to prevent its permitted capability set being cleared when it resets all of its user IDs to non-zero values, it can do so using the prctl() PR_SET_KEEPCAPS operation.

CONFORMING TO

No standards govern capabilities, but the Linux capability implementation is based on the withdrawn POSIX.1e draft standard.

NOTES

The libcap package provides a suite of routines for setting and getting capabilities that is more comfortable and less likely to change than the interface provided by capset(2) and capget(2).

BUGS

There is as yet no file system support allowing capabilities to be associated with executable files.

SEE ALSO

capget(2), prctl(2), setfsuid(2), credentials(7), pthreads(7)


iso_8859-16(7)

ISO_8859-16

Section: Linux Programmer's Manual (7)
Updated: 2003-03-05 Return to Main Contents

NAME

iso_8859-16 - the ISO 8859-16 character set encoded in octal, decimal, and hexadecimal

DESCRIPTION

The ISO 8859 standard includes several 8-bit extensions to the ASCII character set (also known as ISO 646-IRV). ISO 8859-16, the "Latin Alphabet No. 10" is used to encode Central and Eastern European Latin characters and is not implemented yet by any program vendors. ISO 8859-16 supports the following languages: Albanian, Bosnian, Croatian, English, Finnish, German, Hungarian, Irish, Polish, Romanian, Slovenian and Serbian. Also note that the following Cyrillic-based languages have one-to-one transliterations to Latin 10: Macedonian and Serbian.

ISO 8859 Alphabets

The full set of ISO 8859 alphabets includes:
ISO 8859-1 | West European languages (Latin-1)
ISO 8859-2 | Central and East European languages (Latin-2)
ISO 8859-3 | Southeast European and miscellaneous languages (Latin-3)
ISO 8859-4 | Scandinavian/Baltic languages (Latin-4)
ISO 8859-5 | Latin/Cyrillic
ISO 8859-6 | Latin/Arabic
ISO 8859-7 | Latin/Greek
ISO 8859-8 | Latin/Hebrew
ISO 8859-9 | Latin-1 modification for Turkish (Latin-5)
ISO 8859-10 | Lappish/Nordic/Eskimo languages (Latin-6)
ISO 8859-11 | Latin/Thai
ISO 8859-13 | Baltic Rim languages (Latin-7)
ISO 8859-14 | Celtic (Latin-8)
ISO 8859-15 | West European languages (Latin-9)
ISO 8859-16 | Romanian (Latin-10)

ISO 8859-16 Characters

The following table displays the characters in ISO 8859-16 (Latin-10), which are printable and unlisted in the ascii(7) manual page. The fourth column will only show the proper glyphs in an environment configured for ISO 8859-16.
Oct | Dec | Hex | Char | Description
240 | 160 | A0 |  | NO-BREAK SPACE
241 | 161 | A1 | ¡ | LATIN CAPITAL LETTER A WITH OGONEK
242 | 162 | A2 | ¢ | LATIN SMALL LETTER A WITH OGONEK
243 | 163 | A3 | £ | LATIN CAPITAL LETTER L WITH STROKE
244 | 164 | A4 | ¤ | EURO SIGN
245 | 165 | A5 | ¥ | DOUBLE LOW-9 QUOTATION MARK
246 | 166 | A6 | ¦ | LATIN CAPITAL LETTER S WITH CARON
247 | 167 | A7 | § | SECTION SIGN
250 | 168 | A8 | ¨ | LATIN SMALL LETTER S WITH CARON
251 | 169 | A9 | © | COPYRIGHT SIGN
252 | 170 | AA | ª | LATIN CAPITAL LETTER S WITH COMMA BELOW
253 | 171 | AB | « | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
254 | 172 | AC | ¬ | LATIN CAPITAL LETTER Z WITH ACUTE
255 | 173 | AD |  | SOFT HYPHEN
256 | 174 | AE | ® | LATIN SMALL LETTER Z WITH ACUTE
257 | 175 | AF | ¯ | LATIN CAPITAL LETTER Z WITH DOT ABOVE
260 | 176 | B0 | ° | DEGREE SIGN
261 | 177 | B1 | ± | PLUS-MINUS SIGN
262 | 178 | B2 | ² | LATIN CAPITAL LETTER C WITH CARON
263 | 179 | B3 | ³ | LATIN SMALL LETTER L WITH STROKE
264 | 180 | B4 | ´ | LATIN CAPITAL LETTER Z WITH CARON
265 | 181 | B5 | µ | LEFT DOUBLE QUOTATION MARK
266 | 182 | B6 | ¶ | PILCROW SIGN
267 | 183 | B7 | · | MIDDLE DOT
270 | 184 | B8 | ¸ | LATIN SMALL LETTER Z WITH CARON
271 | 185 | B9 | ¹ | LATIN SMALL LETTER C WITH CARON
272 | 186 | BA | º | LATIN SMALL LETTER S WITH COMMA BELOW
273 | 187 | BB | » | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
274 | 188 | BC | ¼ | LATIN CAPITAL LIGATURE OE
275 | 189 | BD | ½ | LATIN SMALL LIGATURE OE
276 | 190 | BE | ¾ | LATIN CAPITAL LETTER Y WITH DIAERESIS
277 | 191 | BF | ¿ | LATIN SMALL LETTER Z WITH DOT ABOVE
300 | 192 | C0 | À | LATIN CAPITAL LETTER A WITH GRAVE
301 | 193 | C1 | Á | LATIN CAPITAL LETTER A WITH ACUTE
302 | 194 | C2 | Â | LATIN CAPITAL LETTER A WITH CIRCUMFLEX
303 | 195 | C3 | Ã | LATIN CAPITAL LETTER A WITH BREVE
304 | 196 | C4 | Ä | LATIN CAPITAL LETTER A WITH DIAERESIS
305 | 197 | C5 | Å | LATIN CAPITAL LETTER C WITH ACUTE
306 | 198 | C6 | Æ | LATIN CAPITAL LETTER AE
307 | 199 | C7 | Ç | LATIN CAPITAL LETTER C WITH CEDILLA
310 | 200 | C8 | È | LATIN CAPITAL LETTER E WITH GRAVE
311 | 201 | C9 | É | LATIN CAPITAL LETTER E WITH ACUTE
312 | 202 | CA | Ê | LATIN CAPITAL LETTER E WITH CIRCUMFLEX
313 | 203 | CB | Ë | LATIN CAPITAL LETTER E WITH DIAERESIS
314 | 204 | CC | Ì | LATIN CAPITAL LETTER I WITH GRAVE
315 | 205 | CD | Í | LATIN CAPITAL LETTER I WITH ACUTE
316 | 206 | CE | Î | LATIN CAPITAL LETTER I WITH CIRCUMFLEX
317 | 207 | CF | Ï | LATIN CAPITAL LETTER I WITH DIAERESIS
320 | 208 | D0 | Ð | LATIN CAPITAL LETTER D WITH STROKE
321 | 209 | D1 | Ñ | LATIN CAPITAL LETTER N WITH ACUTE
322 | 210 | D2 | Ò | LATIN CAPITAL LETTER O WITH GRAVE
323 | 211 | D3 | Ó | LATIN CAPITAL LETTER O WITH ACUTE
324 | 212 | D4 | Ô | LATIN CAPITAL LETTER O WITH CIRCUMFLEX
325 | 213 | D5 | Õ | LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
326 | 214 | D6 | Ö | LATIN CAPITAL LETTER O WITH DIAERESIS
327 | 215 | D7 | × | LATIN CAPITAL LETTER S WITH ACUTE
330 | 216 | D8 | Ø | LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
331 | 217 | D9 | Ù | LATIN CAPITAL LETTER U WITH GRAVE
332 | 218 | DA | Ú | LATIN CAPITAL LETTER U WITH ACUTE
333 | 219 | DB | Û | LATIN CAPITAL LETTER U WITH CIRCUMFLEX
334 | 220 | DC | Ü | LATIN CAPITAL LETTER U WITH DIAERESIS
335 | 221 | DD | Ý | LATIN CAPITAL LETTER E WITH OGONEK
336 | 222 | DE | Þ | LATIN CAPITAL LETTER T WITH COMMA BELOW
337 | 223 | DF | ß | LATIN SMALL LETTER SHARP S
340 | 224 | E0 | à | LATIN SMALL LETTER A WITH GRAVE
341 | 225 | E1 | á | LATIN SMALL LETTER A WITH ACUTE
342 | 226 | E2 | â | LATIN SMALL LETTER A WITH CIRCUMFLEX
343 | 227 | E3 | ã | LATIN SMALL LETTER A WITH BREVE
344 | 228 | E4 | ä | LATIN SMALL LETTER A WITH DIAERESIS
345 | 229 | E5 | å | LATIN SMALL LETTER C WITH ACUTE
346 | 230 | E6 | æ | LATIN SMALL LETTER AE
347 | 231 | E7 | ç | LATIN SMALL LETTER C WITH CEDILLA
350 | 232 | E8 | è | LATIN SMALL LETTER E WITH GRAVE
351 | 233 | E9 | é | LATIN SMALL LETTER E WITH ACUTE
352 | 234 | EA | ê | LATIN SMALL LETTER E WITH CIRCUMFLEX
353 | 235 | EB | ë | LATIN SMALL LETTER E WITH DIAERESIS
354 | 236 | EC | ì | LATIN SMALL LETTER I WITH GRAVE
355 | 237 | ED | í | LATIN SMALL LETTER I WITH ACUTE
356 | 238 | EE | î | LATIN SMALL LETTER I WITH CIRCUMFLEX
357 | 239 | EF | ï | LATIN SMALL LETTER I WITH DIAERESIS
360 | 240 | F0 | ð | LATIN SMALL LETTER D WITH STROKE
361 | 241 | F1 | ñ | LATIN SMALL LETTER N WITH ACUTE
362 | 242 | F2 | ò | LATIN SMALL LETTER O WITH GRAVE
363 | 243 | F3 | ó | LATIN SMALL LETTER O WITH ACUTE
364 | 244 | F4 | ô | LATIN SMALL LETTER O WITH CIRCUMFLEX
365 | 245 | F5 | õ | LATIN SMALL LETTER O WITH DOUBLE ACUTE
366 | 246 | F6 | ö | LATIN SMALL LETTER O WITH DIAERESIS
367 | 247 | F7 | ÷ | LATIN SMALL LETTER S WITH ACUTE
370 | 248 | F8 | ø | LATIN SMALL LETTER U WITH DOUBLE ACUTE
371 | 249 | F9 | ù | LATIN SMALL LETTER U WITH GRAVE
372 | 250 | FA | ú | LATIN SMALL LETTER U WITH ACUTE
373 | 251 | FB | û | LATIN SMALL LETTER U WITH CIRCUMFLEX
374 | 252 | FC | ü | LATIN SMALL LETTER U WITH DIAERESIS
375 | 253 | FD | ý | LATIN SMALL LETTER E WITH OGONEK
376 | 254 | FE | þ | LATIN SMALL LETTER T WITH COMMA BELOW
377 | 255 | FF | ÿ | LATIN SMALL LETTER Y WITH DIAERESIS

SEE ALSO

ascii(7), iso_8859-1(7), iso_8859-15(7), iso_8859-2(7) Additional information: ISO 8859-16 (Latin 10) Resources (http://bucovina.chem.tue.nl/fonturi/index-en.html).


iso_8859_16(7)

Status: 403 Forbidden iso_8859_16(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso_8859_16.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


operator(7)

OPERATOR

Section: Environments, Tables, and Troff Macros (7) Return to Main Contents

BSD mandoc

NAME

C operator - C operator precedence and order of evaluation

DESCRIPTION

This manual page lists C operators and their precedence in evaluation.

Operator      Associativity
"--------     -------------"
"() [] -> .     left to right"
"! ~ ++ -- + - (type) * & sizeofright to left"
"* / %left to right"
"+ -left to right"
"<< >>left to right"
"< <= > >=left to right"
"== !=left to right"
"&left to right"
"^left to right"
"|left to right"
"&&left to right"
"||left to right"
"?:right to left"
"= += -= *= /= %= <<= >>= &= ^= |=right to left"
",left to right"


iso-8859-16(7)

Status: 403 Forbidden iso-8859-16(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/iso-8859-16.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


posixoptions(7)

POSIXOPTIONS

Section: Linux Programmer's Manual (7)
Updated: 2003-08-24 Return to Main Contents

NAME

posixoptions - optional parts of the POSIX standard

DESCRIPTION

The POSIX standard (the information below is from POSIX.1-2001) describes a set of behavior and interfaces for a compliant system. However, many interfaces are optional and there are feature test macros to test the availability of interfaces at compile time, and functions sysconf(3), fpathconf(3), pathconf(3), confstr(3) to do this at run time. From shell scripts one can use getconf(1). For more detail, see sysconf(3).

We give the name of the POSIX abbreviation, the option, the name of the sysconf() parameter used to inquire about the option, and possibly a very short description. Much more precise detail can be found in the POSIX standard itself, versions of which can nowadays be accessed freely on the web.

ADV - _POSIX_ADVISORY_INFO - _SC_ADVISORY_INFO

The advisory functions
posix_fadvise(),
posix_fallocate(),
posix_memalign(),
posix_madvise()
are present.

AIO - _POSIX_ASYNCHRONOUS_IO - _SC_ASYNCHRONOUS_IO

The header <aio.h> is present. The functions
aio_cancel(),
aio_error(),
aio_fsync(),
aio_read(),
aio_return(),
aio_suspend(),
aio_write(),
lio_listio()
are present.

BAR - _POSIX_BARRIERS - _SC_BARRIERS

This option implies the _POSIX_THREADS and _POSIX_THREAD_SAFE_FUNCTIONS options. The functions
pthread_barrier_destroy(),
pthread_barrier_init(),
pthread_barrier_wait(),
pthread_barrierattr_destroy(),
pthread_barrierattr_init()
are present.

--- - POSIX_CHOWN_RESTRICTED

If this option is in effect (as it always is under POSIX.1-2001) then only root may change the owner of a file, and non-root can only set the group of a file to one of the groups it belongs to. This affects the functions chown(), fchown().

CS - _POSIX_CLOCK_SELECTION - _SC_CLOCK_SELECTION

This option implies the _POSIX_TIMERS option. The functions
pthread_condattr_getclock(),
pthread_condattr_setclock(),
clock_nanosleep()
are present. If CLOCK_REALTIME is changed by the function clock_settime(), then this affects all timers set for an absolute time.

CPT - _POSIX_CPUTIME - _SC_CPUTIME

The clockID CLOCK_PROCESS_CPUTIME_ID is supported. The initial value of this clock is 0 for each process. This option implies the _POSIX_TIMERS option. The function clock_getcpuclockid() is present.

--- - _POSIX_FILE_LOCKING - _SC_FILE_LOCKING

This option has been deleted. Not in final XPG6.

FSC - _POSIX_FSYNC - _SC_FSYNC

The function fsync() is present.

IP6 - _POSIX_IPV6 - _SC_IPV6

Internet Protocol Version 6 is supported.

--- - _POSIX_JOB_CONTROL - _SC_JOB_CONTROL

If this option is in effect (as it always is under POSIX.1-2001) then the system implements POSIX-style job control, and the functions
setpgid(),
tcdrain(),
tcflush(),
tcgetpgrp(),
tcsendbreak(),
tcsetattr(),
tcsetpgrp()
are present.

MF - _POSIX_MAPPED_FILES - _SC_MAPPED_FILES

Shared memory is supported. The include file <sys/mman.h> is present. The functions mmap(), msync(), munmap() are present.

ML - _POSIX_MEMLOCK - _SC_MEMLOCK

Shared memory can be locked into core. The functions mlockall(), munlockall() are present.

MR/MLR - _POSIX_MEMLOCK_RANGE - _SC_MEMLOCK_RANGE

More precisely, ranges can be locked into core. The functions mlock(), munlock() are present.

MPR - _POSIX_MEMORY_PROTECTION - _SC_MEMORY_PROTECTION

The function mprotect() is present.

MSG - _POSIX_MESSAGE_PASSING - _SC_MESSAGE_PASSING

The include file <mqueue.h> is present. The functions
mq_close(),
mq_getattr(),
mq_notify(),
mq_open(),
mq_receive(),
mq_send(),
mq_setattr(),
mq_unlink()
are present.

MON - _POSIX_MONOTONIC_CLOCK - _SC_MONOTONIC_CLOCK

CLOCK_MONOTONIC is supported.
This option implies the _POSIX_TIMERS option.
Affected functions are
aio_suspend(),
clock_getres(),
clock_gettime(),
clock_settime(),
timer_create().

--- - _POSIX_MULTI_PROCESS - _SC_MULTI_PROCESS

This option has been deleted. Not in final XPG6.

--- - _POSIX_NO_TRUNC

If this option is in effect (as it always is under POSIX.1-2001) then pathname components longer than NAME_MAX are not truncated, but give an error. This property may be dependent on the path prefix of the component.

PIO - _POSIX_PRIORITIZED_IO - _SC_PRIORITIZED_IO

This option says that one can specify priorities for asynchronous I/O. This affects the functions
aio_read(),
aio_write().

PS - _POSIX_PRIORITY_SCHEDULING - _SC_PRIORITY_SCHEDULING

The include file <sched.h> is present. The functions
sched_get_priority_max(),
sched_get_priority_min(),
sched_getparam(),
sched_getscheduler(),
sched_rr_get_interval(),
sched_setparam(),
sched_setscheduler(),
sched_yield()
are present. If also _POSIX_SPAWN is in effect, then the functions
posix_spawnattr_getschedparam(),
posix_spawnattr_getschedpolicy(),
posix_spawnattr_setschedparam(),
posix_spawnattr_setschedpolicy()
are present.

RS - _POSIX_RAW_SOCKETS

Raw sockets are supported. Affected functions are getsockopt(), setsockopt().

--- - _POSIX_READER_WRITER_LOCKS - _SC_READER_WRITER_LOCKS

This option implies the _POSIX_THREADS option. Conversely, under POSIX.1-2001 the _POSIX_THREADS option implies this option.
The functions
pthread_rwlock_destroy(),
pthread_rwlock_init(),
pthread_rwlock_rdlock(),
pthread_rwlock_tryrdlock(),
pthread_rwlock_trywrlock(),
pthread_rwlock_unlock(),
pthread_rwlock_wrlock(),
pthread_rwlockattr_destroy(),
pthread_rwlockattr_init()
are present.

RTS - _POSIX_REALTIME_SIGNALS - _SC_REALTIME_SIGNALS

Realtime signals are supported. The functions
sigqueue(),
sigtimedwait(),
sigwaitinfo()
are present.

--- - _POSIX_REGEXP - _SC_REGEXP

If this option is in effect (as it always is under POSIX.1-2001) then POSIX regular expressions are supported and the functions
regcomp(),
regerror(),
regexec(),
regfree()
are present.

--- - _POSIX_SAVED_IDS - _SC_SAVED_IDS

If this option is in effect (as it always is under POSIX.1-2001) then a process has a saved set-user-ID and a saved set-group-ID. Affected functions are
exec(),
kill(),
seteuid(),
setegid(),
setgid(),
setuid().

SEM - _POSIX_SEMAPHORES - _SC_SEMAPHORES

The include file <semaphore.h> is present. The functions
sem_close(),
sem_destroy(),
sem_getvalue(),
sem_init(),
sem_open(),
sem_post(),
sem_trywait(),
sem_unlink(),
sem_wait()
are present.

SHM - _POSIX_SHARED_MEMORY_OBJECTS - _SC_SHARED_MEMORY_OBJECTS

The functions
mmap(),
munmap(),
shm_open(),
shm_unlink()
are present.

--- - _POSIX_SHELL - _SC_SHELL

If this option is in effect (as it always is under POSIX.1-2001), the function system() is present.

SPN - _POSIX_SPAWN - _SC_SPAWN

This option describes support for process creation in a context where it is difficult or impossible to use fork(), for example, because no MMU is present. If _POSIX_SPAWN is in effect, then the include file <spawn.h> and the functions
posix_spawn(),
posix_spawn_file_actions_addclose(),
posix_spawn_file_actions_adddup2(),
posix_spawn_file_actions_addopen(),
posix_spawn_file_actions_destroy(),
posix_spawn_file_actions_init(),
posix_spawnattr_destroy(),
posix_spawnattr_getsigdefault(),
posix_spawnattr_getflags(),
posix_spawnattr_getpgroup(),
posix_spawnattr_getsigmask(),
posix_spawnattr_init(),
posix_spawnattr_setsigdefault(),
posix_spawnattr_setflags(),
posix_spawnattr_setpgroup(),
posix_spawnattr_setsigmask(),
posix_spawnp()
are present. If also _POSIX_PRIORITY_SCHEDULING is in effect, then the functions
posix_spawnattr_getschedparam(),
posix_spawnattr_getschedpolicy(),
posix_spawnattr_setschedparam(),
posix_spawnattr_setschedpolicy()
are present.

SPI - _POSIX_SPIN_LOCKS - _SC_SPIN_LOCKS

This option implies the _POSIX_THREADS and _POSIX_THREAD_SAFE_FUNCTIONS options. The functions
pthread_spin_destroy(),
pthread_spin_init(),
pthread_spin_lock(),
pthread_spin_trylock(),
pthread_spin_unlock()
are present.

SS - _POSIX_SPORADIC_SERVER - _SC_SPORADIC_SERVER

The scheduling policy SCHED_SPORADIC is supported. This option implies the _POSIX_PRIORITY_SCHEDULING option. Affected functions are
sched_setparam(),
sched_setscheduler().

SIO - _POSIX_SYNCHRONIZED_IO - _SC_SYNCHRONIZED_IO

Affected functions are open(), msync(), fsync(), fdatasync().

TSA - _POSIX_THREAD_ATTR_STACKADDR - _SC_THREAD_ATTR_STACKADDR

Affected functions are
pthread_attr_getstack(),
pthread_attr_getstackaddr(),
pthread_attr_setstack(),
pthread_attr_setstackaddr().

TSS - _POSIX_THREAD_ATTR_STACKSIZE - _SC_THREAD_ATTR_STACKSIZE

Affected functions are
pthread_attr_getstack(),
pthread_attr_getstacksize(),
pthread_attr_setstack(),
pthread_attr_setstacksize().

TCT - _POSIX_THREAD_CPUTIME - _SC_THREAD_CPUTIME

The clockID CLOCK_THREAD_CPUTIME_ID is supported. This option implies the _POSIX_TIMERS option. Affected functions are
pthread_getcpuclockid(),
clock_getres(),
clock_gettime(),
clock_settime(),
timer_create().

TPI - _POSIX_THREAD_PRIO_INHERIT - _SC_THREAD_PRIO_INHERIT

Affected functions are
pthread_mutexattr_getprotocol(),
pthread_mutexattr_setprotocol().

TPP - _POSIX_THREAD_PRIO_PROTECT - _SC_THREAD_PRIO_PROTECT

Affected functions are
pthread_mutex_getprioceiling(),
pthread_mutex_setprioceiling(),
pthread_mutexattr_getprioceiling(),
pthread_mutexattr_getprotocol(),
pthread_mutexattr_setprioceiling(),
pthread_mutexattr_setprotocol().

TPS - _POSIX_THREAD_PRIORITY_SCHEDULING - _SC_THREAD_PRIORITY_SCHEDULING

If this option is in effect, the different threads inside a process can run with different priorities and/or different schedulers. Affected functions are
pthread_attr_getinheritsched(),
pthread_attr_getschedpolicy(),
pthread_attr_getscope(),
pthread_attr_setinheritsched(),
pthread_attr_setschedpolicy(),
pthread_attr_setscope(),
pthread_getschedparam(),
pthread_setschedparam(),
pthread_setschedprio().

TSH - _POSIX_THREAD_PROCESS_SHARED - _SC_THREAD_PROCESS_SHARED

Affected functions are
pthread_barrierattr_getpshared(),
pthread_barrierattr_setpshared(),
pthread_condattr_getpshared(),
pthread_condattr_setpshared(),
pthread_mutexattr_getpshared(),
pthread_mutexattr_setpshared(),
pthread_rwlockattr_getpshared(),
pthread_rwlockattr_setpshared().

TSF - _POSIX_THREAD_SAFE_FUNCTIONS - _SC_THREAD_SAFE_FUNCTIONS

Affected functions are
readdir_r(),
getgrgid_r(),
getgrnam_r(),
getpwnam_r(),
getpwuid_r(),
flockfile(),
ftrylockfile(),
funlockfile(),
getc_unlocked(),
getchar_unlocked(),
putc_unlocked(),
putchar_unlocked(),
rand_r(),
strerror_r(),
strtok_r(),
asctime_r(),
ctime_r(),
gmtime_r(),
localtime_r().

TSP - _POSIX_THREAD_SPORADIC_SERVER - _SC_THREAD_SPORADIC_SERVER

This option implies the _POSIX_THREAD_PRIORITY_SCHEDULING option. Affected functions are
sched_getparam(),
sched_setparam(),
sched_setscheduler().

THR - _POSIX_THREADS - _SC_THREADS

Basic support for POSIX threads is available. The functions
pthread_atfork(),
pthread_attr_destroy(),
pthread_attr_getdetachstate(),
pthread_attr_getschedparam(),
pthread_attr_init(),
pthread_attr_setdetachstate(),
pthread_attr_setschedparam(),
pthread_cancel(),
pthread_cleanup_push(),
pthread_cleanup_pop(),
pthread_cond_broadcast(),
pthread_cond_destroy(),
pthread_cond_init(),
pthread_cond_signal(),
pthread_cond_timedwait(),
pthread_cond_wait(),
pthread_condattr_destroy(),
pthread_condattr_init(),
pthread_create(),
pthread_detach(),
pthread_equal(),
pthread_exit(),
pthread_getspecific(),
pthread_join(),
pthread_key_create(),
pthread_key_delete(),
pthread_mutex_destroy(),
pthread_mutex_init(),
pthread_mutex_lock(),
pthread_mutex_trylock(),
pthread_mutex_unlock(),
pthread_mutexattr_destroy(),
pthread_mutexattr_init(),
pthread_once(),
pthread_rwlock_destroy(),
pthread_rwlock_init(),
pthread_rwlock_rdlock(),
pthread_rwlock_tryrdlock(),
pthread_rwlock_trywrlock(),
pthread_rwlock_unlock(),
pthread_rwlock_wrlock(),
pthread_rwlockattr_destroy(),
pthread_rwlockattr_init(),
pthread_self(),
pthread_setcancelstate(),
pthread_setcanceltype(),
pthread_setspecific(),
pthread_testcancel()
are present.

TMO - _POSIX_TIMEOUTS - _SC_TIMEOUTS

The functions
mq_timedreceive(),
mq_timedsend(),
pthread_mutex_timedlock(),
pthread_rwlock_timedrdlock(),
pthread_rwlock_timedwrlock(),
sem_timedwait(),
posix_trace_timedgetnext_event()
are present.

TMR - _POSIX_TIMERS - _SC_TIMERS

The functions
clock_getres(),
clock_gettime(),
clock_settime(),
nanosleep(),
timer_create(),
timer_delete(),
timer_gettime(),
timer_getoverrun(),
timer_settime()
are present.

TRC - _POSIX_TRACE - _SC_TRACE

POSIX tracing is available. The functions
posix_trace_attr_destroy(),
posix_trace_attr_getclockres(),
posix_trace_attr_getcreatetime(),
posix_trace_attr_getgenversion(),
posix_trace_attr_getmaxdatasize(),
posix_trace_attr_getmaxsystemeventsize(),
posix_trace_attr_getmaxusereventsize(),
posix_trace_attr_getname(),
posix_trace_attr_getstreamfullpolicy(),
posix_trace_attr_getstreamsize(),
posix_trace_attr_init(),
posix_trace_attr_setmaxdatasize(),
posix_trace_attr_setname(),
posix_trace_attr_setstreamsize(),
posix_trace_attr_setstreamfullpolicy(),
posix_trace_clear(),
posix_trace_create(),
posix_trace_event(),
posix_trace_eventid_equal(),
posix_trace_eventid_get_name(),
posix_trace_eventid_open(),
posix_trace_eventtypelist_getnext_id(),
posix_trace_eventtypelist_rewind(),
posix_trace_flush(),
posix_trace_get_attr(),
posix_trace_get_status(),
posix_trace_getnext_event(),
posix_trace_shutdown(),
posix_trace_start(),
posix_trace_stop(),
posix_trace_trygetnext_event()
are present.

TEF - _POSIX_TRACE_EVENT_FILTER - _SC_TRACE_EVENT_FILTER

This option implies the _POSIX_TRACE option. The functions
posix_trace_eventset_add(),
posix_trace_eventset_del(),
posix_trace_eventset_empty(),
posix_trace_eventset_fill(),
posix_trace_eventset_ismember(),
posix_trace_get_filter(),
posix_trace_set_filter(),
posix_trace_trid_eventid_open()
are present.

TRI - _POSIX_TRACE_INHERIT - _SC_TRACE_INHERIT

Tracing children of the traced process is supported. This option implies the _POSIX_TRACE option. The functions
posix_trace_attr_getinherited(),
posix_trace_attr_setinherited()
are present.

TRL - _POSIX_TRACE_LOG - _SC_TRACE_LOG

This option implies the _POSIX_TRACE option. The functions
posix_trace_attr_getlogfullpolicy(),
posix_trace_attr_getlogsize(),
posix_trace_attr_setlogfullpolicy(),
posix_trace_attr_setlogsize(),
posix_trace_close(),
posix_trace_create_withlog(),
posix_trace_open(),
posix_trace_rewind()
are present.

TYM - _POSIX_TYPED_MEMORY_OBJECTS - _SC_TYPED_MEMORY_OBJECT

The functions
posix_mem_offset(),
posix_typed_mem_get_info(),
posix_typed_mem_open()
are present.

--- - _POSIX_VDISABLE

Always present (probably 0). Value to set a changeable special control character to indicate that it is disabled.

XOPEN EXTENSIONS

_XOPEN_CRYPT, _XOPEN_LEGACY, _XOPEN_REALTIME, _XOPEN_REALTIME_THREADS, _XOPEN_UNIX.

SEE ALSO

sysconf(3)


latin10(7)

Status: 403 Forbidden latin10(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/latin10.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


latin5(7)

Status: 403 Forbidden latin5(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/latin5.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


latin9(7)

Status: 403 Forbidden latin9(7)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man7/latin9.7 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


path_resolution(7)

PATH_RESOLUTION

Section: Linux Programmer's Manual (7)
Updated: 2004-06-21 Return to Main Contents

NAME

Unix/Linux path resolution - find the file referred to by a filename

DESCRIPTION

Some Unix/Linux system calls have as parameter one or more filenames. A filename (or pathname) is resolved as follows.

Step 1: Start of the resolution process

If the pathname starts with the '/' character, the starting lookup directory is the root directory of the current process. (A process inherits its root directory from its parent. Usually this will be the root directory of the file hierarchy. A process may get a different root directory by use of the chroot(2) system call. A process may get an entirely private namespace in case it --- or one of its ancestors --- was started by an invocation of the clone(2) system call that had the CLONE_NEWNS flag set.) This handles the '/' part of the pathname.

If the pathname does not start with the '/' character, the starting lookup directory of the resolution process is the current working directory of the process. (This is also inherited from the parent. It can be changed by use of the chdir(2) system call.)

Pathnames starting with a '/' character are called absolute pathnames. Pathnames not starting with a '/' are called relative pathnames.

Step 2: Walk along the path

Set the current lookup directory to the starting lookup directory. Now, for each non-final component of the pathname, where a component is a substring delimited by '/' characters, this component is looked up in the current lookup directory.

If the process does not have search permission on the current lookup directory, an EACCES error is returned ("Permission denied").

If the component is not found, an ENOENT error is returned ("No such file or directory").

If the component is found, but is neither a directory nor a symbolic link, an ENOTDIR error is returned ("Not a directory").

If the component is found and is a directory, we set the current lookup directory to that directory, and go to the next component.

If the component is found and is a symbolic link (symlink), we first resolve this symbolic link (with the current lookup directory as starting lookup directory). Upon error, that error is returned. If the result is not a directory, an ENOTDIR error is returned. If the resolution of the symlink is successful and returns a directory, we set the current lookup directory to that directory, and go to the next component. Note that the resolution process here involves recursion. In order to protect the kernel against stack overflow, and also to protect against denial of service, there are limits on the maximum recursion depth, and on the maximum number of symbolic links followed. An ELOOP error is returned when the maximum is exceeded ("Too many levels of symbolic links").

Step 3: Find the final entry

The lookup of the final component of the pathname goes just like that of all other components, as described in the previous step, with two differences: (i) the final component need not be a directory (at least as far as the path resolution process is concerned --- it may have to be a directory, or a non-directory, because of the requirements of the specific system call), and (ii) it is not necessarily an error if the component is not found --- maybe we are just creating it. The details on the treatment of the final entry are described in the manual pages of the specific system calls.

. and ..

By convention, every directory has the entries "." and "..", which refer to the directory itself and to its parent directory, respectively.

The path resolution process will assume that these entries have their conventional meanings, regardless of whether they are actually present in the physical filesystem.

One cannot walk down past the root: "/.." is the same as "/".

Mount points

After a "mount dev path" command, the pathname "path" refers to the root of the filesystem hierarchy on the device "dev", and no longer to whatever it referred to earlier.

One can walk out of a mounted filesystem: "path/.." refers to the parent directory of "path", outside of the filesystem hierarchy on "dev".

Trailing slashes

If a pathname ends in a '/', that forces resolution of the preceding component as in Step 2: it has to exist and resolve to a directory. Otherwise a trailing '/' is ignored. (Or, equivalently, a pathname with a trailing '/' is equivalent to the pathname obtained by appending '.' to it.)

Final symlink

If the last component of a pathname is a symbolic link, then it depends on the system call whether the file referred to will be the symbolic link or the result of path resolution on its contents. For example, the system call lstat(2) will operate on the symlink, while stat(2) operates on the file pointed to by the symlink.

Length limit

There is a maximum length for pathnames. If the pathname (or some intermediate pathname obtained while resolving symbolic links) is too long, an ENAMETOOLONG error is returned ("File name too long").

Empty pathname

In the original Unix, the empty pathname referred to the current directory. Nowadays POSIX decrees that an empty pathname must not be resolved successfully. Linux returns ENOENT in this case.

Permissions

The permission bits of a file consist of three groups of three bits, cf. chmod(1) and stat(2). The first group of three is used when the effective user ID of the current process equals the owner ID of the file. The second group of three is used when the group ID of the file either equals the effective group ID of the current process, or is one of the supplementary group IDs of the current process (as set by setgroups(2)). When neither holds, the third group is used.

Of the three bits used, the first bit determines read permission, the second write permission, and the last execute permission in case of ordinary files, or search permission in case of directories.

Linux uses the fsuid instead of the effective user ID in permission checks. Ordinarily the fsuid will equal the effective user ID, but the fsuid can be changed by the system call setfsuid(2).

(Here "fsuid" stands for something like "file system user ID". The concept was required for the implementation of a user space NFS server at a time when processes could send a signal to a process with the same effective user ID. It is obsolete now. Nobody should use setfsuid(2).)

Similarly, Linux uses the fsgid ("file system group ID") instead of the effective group ID. See setfsgid(2).

Bypassing permission checks: superuser and capabilities

On a traditional Unix system, the superuser (root, user ID 0) is all-powerful, and bypasses all permissions restrictions when accessing files.

On Linux, superuser privileges are divided into capabilities (see capabilities(7)). Two capabilities are relevant for file permissions checks: CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH. (A process has these capabilities if its fsuid is 0.)

The CAP_DAC_OVERRIDE capability overrides all permission checking, but only grants execute permission when at least one of the file's three execute permission bits is set.

The CAP_DAC_READ_SEARCH capability grants read and search permission on directories, and read permission on ordinary files.

SEE ALSO

capabilities(7), credentials(7)


man-pages(7)

MAN-PAGES

Section: Linux Programmer's Manual (7)
Updated: 2007-05-30 Return to Main Contents

NAME

man-pages - conventions for writing Linux man pages

SYNOPSIS

man [section] title

DESCRIPTION

This page describes the conventions that should be employed when writing man pages for the Linux man-pages project, which comprises Sections 2, 3, 4, 5, and 7 of the Linux manual pages. The conventions described on this page may also be useful for authors writing man pages for other projects.

Sections of the Manual Pages

The manual Sections are traditionally defined as follows:

1 Commands (Programs)
Those commands that can be executed by the user from within a shell.
2 System calls
Those functions which must be performed by the kernel.
3 Library calls
Most of the libc functions.
4 Special files (devices)
Files found in /dev.
5 File formats and conventions
The format for /etc/passwd and other human-readable files.
6 Games
7 Conventions and miscellaneous
Overviews of various topics, conventions and protocols, character set standards, and miscellaneous other things.
8 System management commands
Commands like mount(8), many of which only root can execute.

Macro package

New manual pages should be marked up using the groff tmac.an package described in man(7). This choice is mainly for consistency: the vast majority of existing Linux manual pages are marked up using these macros.

Conventions for source file layout

Please limit source code line length to no more than about 75 characters wherever possible. This helps avoid line-wrapping in some mail clients when patches are submitted inline.

New sentences should be started on new lines. This makes it easier to see the effect of patches, which often operate at the level of individual sentences.

Title line

The first command in a man page should be a TH command:

.TH title section date source manual

where:
title
The title of the man page, written in all caps (e.g., MAN-PAGES).
section
The section number in which the man page should be placed (e.g., 7).
date
The date of the last revision---remember to change this every time a change is made to the man page, since this is the most general way of doing version control. Dates should be written in the form YYYY-MM-DD.
source
The source of the command, function, or system call.

For those few man-pages pages in Sections 1 and 8, probably you just want to write GNU.

For system calls, just write Linux. (An earlier practice was to write the version number of the kernel from which the manual page was being written/checked. However, this was never done consistently, and so was probably worse than including no version number. Henceforth, avoid including a version number.)

For library calls that are part of glibc or one of the other common GNU libraries, just use GNU C Library, GNU, or an empty string.

For Section 4 pages, use Linux.

In cases of doubt, just write Linux, or GNU.

manual
The title of the manual (e.g., for Section 2 and 3 pages in the man-pages package, use Linux Programmer's Manual).

Sections within a manual page

The list below shows conventional or suggested sections. Most manual pages should include at least the highlighted sections. Arrange a new manual page so that sections are placed in the order shown in the list.

NAME
SYNOPSIS
DESCRIPTION
OPTIONS            [Normally only in Sections 1, 8]
EXIT STATUS        [Normally only in Sections 1, 8]
RETURN VALUE       [Normally only in Sections 2, 3]
ERRORS             [Typically only in Sections 2, 3]
ENVIRONMENT
FILES
VERSIONS           [Normally only in Sections 2, 3]
CONFORMING TO
NOTES
BUGS
EXAMPLE
SEE ALSO
Where a traditional heading would apply, please use it; this kind of consistency can make the information easier to understand. If you must, you can create your own headings if they make things easier to understand (this can be especially useful for pages in Sections 4 and 5). However, before doing this, consider whether you could use the traditional headings, with some subsections (.SS) within those sections.

The following list elaborates on the contents of each of the above sections.

NAME
The name of this manual page. See man(7) for important details of the line(s) that should follow the .SH NAME command.
SYNOPSIS
briefly describes the command or function's interface. For commands, this shows the syntax of the command and its arguments (including options); boldface is used for as-is text and italics are used to indicate replaceable arguments. Brackets ([]) surround optional arguments, vertical bars (|) separate choices, and ellipses (...) can be repeated. For functions, it shows any required data declarations or #include directives, followed by the function declaration.
DESCRIPTION
gives an explanation of what the program, function, or format does. Discuss how it interacts with files and standard input, and what it produces on standard output or standard error. Omit internals and implementation details unless they're critical for understanding the interface. Describe the usual case; for information on command-line options of a program use the OPTIONS section.
OPTIONS
describes the command-line options accepted by a program and how they change its behavior. This section should only appear for Section 1 and 8 manual pages.
EXIT STATUS
lists the possible exit status values of a program and the conditions that cause these values to be returned. This section should only appear for Section 1 and 8 manual pages.
RETURN VALUE
For Section 2 and 3 pages, this section gives a list of the values the library routine will return to the caller and the conditions that cause these values to be returned.
ERRORS
For Section 2 and 3 manual pages, this is a list of the values that may be placed in errno in the event of an error, along with information about the cause of the errors. The error list should be in alphabetical order.
ENVIRONMENT
lists all environment variables that affect the program or function and how they affect it.
FILES
lists the files the program or function uses, such as configuration files, startup files, and files the program directly operates on. Give the full pathname of these files, and use the installation process to modify the directory part to match user preferences. For many programs, the default installation location is in /usr/local, so your base manual page should use /usr/local as the base.
VERSIONS
A brief summary of the Linux kernel or glibc versions where a system call or library function appeared, or changed significantly in its operation.
CONFORMING TO
describes any standards or conventions that relate to the function or command described by the manual page. For a page in Section 2 or 3, this section should note the POSIX.1 version(s) that the call conforms to, and also whether the call is specified in C99. (Don't worry too much about other standards like SUS, SUSv2, and XPG, or the SVr4 and 4.xBSD implementation standards, unless the call was specified in those standards, but isn't in the current version of POSIX.1.) (See standards(7).)

If the call is not governed by any standards but commonly exists on other systems, note them. If the call is Linux specific, note this.

NOTES
provides miscellaneous notes. For Section 2 and 3 man pages you may find it useful to include subsections (SS) named Linux Notes and Glibc Notes.
BUGS
lists limitations, known defects or inconveniences, and other questionable activities.
EXAMPLE
provides one or more examples describing how this function, file or command is used. For details on writing example programs, see Example Programs below.
AUTHORS
lists authors of the documentation or program. Use of an AUTHORS section is strongly discouraged. Generally, it is better not to clutter every page with a list of (over time potentially numerous) authors; if you write or significantly amend a page, add a copyright notice as a comment in the source file. If you are the author a device driver and what to include an address for reporting bugs, place this under the BUGS section.
SEE ALSO
lists related man pages, ordered by section number and alphabetically by name, possibly followed by other related pages or documents.

Font conventions

For functions, the arguments are always specified using italics, even in the SYNOPSIS section, where the rest of the function is specified in bold:

int myfunction(int argc, char **argv);

Filenames are always in italics (e.g., /usr/include/stdio.h), except in the SYNOPSIS section, where included files are in bold (e.g., #include <stdio.h>).

Special macros, which are usually in upper case, are in bold (e.g., MAXINT). Exception: don't boldface NULL.

When enumerating a list of error codes, the codes are in bold (this list usually uses the .TP macro).

Any reference to the subject of the current manual page should be written with the name in bold. If the subject is a function (i.e., this is a Section 2 or 3 page), then the name should be followed by a pair of parentheses in Roman (normal) font. For example, in the fcntl(2) man page, references to the subject of the page would be written as: fcntl(). The preferred way to write this in the source file is:

    .BR fcntl ()
(Using this format, rather than the use of "\fB...\fP()" makes it easier to write tools that parse man page source files.)

Any reference to another man page should be written with the name in bold, always followed by the section number, formatted in Roman (normal) font, without any separating spaces (e.g., intro(2)). The preferred way to write this in the source file is:

    .BR intro (2)
(Including the section number in cross references lets tools like man2html(1) create properly hyperlinked pages.)

Spelling

Starting with release 2.59, man-pages follows American spelling conventions; please write all new pages and patches according to these conventions.

Example Programs

Manual pages can include example programs demonstrating how to use a system call or library function. However, note the following:
*
Example programs should be written in C.
*
An example program is only necessary and useful if it demonstrates something beyond what can easily be provided in a textual description of the interface. An example program that does nothing other than call an interface usually serves little purpose.
*
Example programs should be fairly short (preferably < 100 lines; ideally < 50 lines).
*
Example programs should do error checking after system calls and library function calls.
*
Example programs should be complete, and compile without warnings when compiled with cc -Wall.
*
Where possible and appropriate, example programs should allow experimentation, by varying their behavior based on inputs (ideally from command-line arguments, or alternatively, via input read by the program).
*
Example programs should be laid out according to Kernighan and Ritchie style, with 4-space indents. (Avoid the use of TAB characters in source code!)

For some examples of what example programs should look like, see wait(2) and pipe(2).

EXAMPLE

For canonical examples of how man pages in the man-pages package should look, see pipe(2) and fcntl(2).

SEE ALSO

man(1), man2html(1), man(7), mdoc(7)


pty(7)

PTY

Section: Linux Programmer's Manual (7)
Updated: 2005-10-10 Return to Main Contents

NAME

pty - pseudo-terminal interfaces

DESCRIPTION

A pseudo-terminal is a pair of virtual character devices that provide a bidirectional communication channel. One end of the channel is called the master; the other end is called the slave. The slave end of the pseudo-terminal provides an interface that behaves exactly like a classical terminal. A process that expects to be connected to a terminal, can open the slave end of a pseudo-terminal and then be driven by a program that has opened the master end. Anything that is written on the master end is provided to the process on the slave end as though it was input typed on a terminal. For example, writing the interrupt character (usually control-C) to the master device would cause an interrupt signal (SIGINT) to be generated for the foreground process group that is connected to the slave. Conversely, anything that is written to the slave end of the pseudo-terminal can be read by the process that is connected to the master end. Pseudo-terminals are used by applications such as network login services (ssh(1), rlogin(1), telnet(1)), terminal emulators, script(1), screen(1), and expect(1).

Historically, two pseudo-terminal APIs have evolved: BSD and System V. SUSv1 standardized a pseudo-terminal API based on the System V API, and this API should be employed in all new programs that use pseudo-terminals.

Linux provides both BSD-style and (standardized) System V-style pseudo-terminals. System V-style terminals are commonly called Unix 98 pseudo-terminals on Linux systems. Since kernel 2.6.4, BSD-style pseudo-terminals are considered deprecated (they can be disabled when configuring the kernel); Unix 98 pseudo-terminals should be used in new applications.

Unix 98 pseudo-terminals

An unused Unix 98 pseudo-terminal master is opened by calling posix_openpt(3). (This function opens the master clone device, /dev/ptmx; see pts(4).) After performing any program-specific initializations, changing the ownership and permissions of the slave device using grantpt(3), and unlocking the slave using unlockpt(3)), the corresponding slave device can be opened by passing the name returned by ptsname(3) in a call to open(2).

The Linux kernel imposes a limit on the number of available Unix 98 pseudo-terminals. In kernels up to and including 2.6.3, this limit is configured at kernel compilation time (CONFIG_UNIX98_PTYS), and the permitted number of pseudo-terminals can be up to 2048, with a default setting of 256. Since kernel 2.6.4, the limit is dynamically adjustable via /proc/sys/kernel/pty/max, and a corresponding file, /proc/sys/kernel/pty/nr, indicates how many pseudo-terminals are currently in use. For further details on these two files, see proc(5).

BSD pseudo-terminals

BSD-style pseudo-terminals are provided as pre-created pairs, with names of the form /dev/ptyXY (master) and /dev/ttyXY (slave), where X is a letter from the 16-character set [p-za-e], and Y is a letter from the 16-character set [0-9a-f]. (The precise range of letters in these two sets varies across Unix implementations.) For example, /dev/ptyp1 and /dev/ttyp1 constitute a BSD pseudo-terminal pair. A process finds an unused pseudo-terminal pair by trying to open(2) each pseudo-terminal master until an open succeeds. The corresponding pseudo-terminal slave (substitute "tty" for "pty" in the name of the master) can then be opened.

FILES

/dev/ptmx (Unix 98 master clone device)
/dev/pts/* (Unix 98 slave devices)
/dev/pty[p-za-e][0-9a-f] (BSD master devices)
/dev/tty[p-za-e][0-9a-f] (BSD slave devices)

NOTES

A description of the TIOCPKT ioctl(2), which controls packet mode operation, can be found in tty_ioctl(4).

The BSD ioctl(2)s TIOCSTOP, TIOCSTART, TIOCUCNTL, TIOCREMOTE have not been implemented under Linux.

SEE ALSO

select(2), setsid(2), forkpty(3), openpty(3), termios(3), pts(4), tty(4), tty_ioctl(4)


urn (7)

 Continue to this page.


complex(7)

COMPLEX

Section: Linux Programmer's Manual (7)
Updated: 2002-07-28 Return to Main Contents

NAME

complex - basics of complex mathematics

SYNOPSIS

#include <complex.h>

DESCRIPTION

Complex numbers are numbers of the form z = a+b*i, where a and b are real numbers and i = sqrt(-1), so that i*i = -1.
There are other ways to represent that number. The pair (a,b) of real numbers may be viewed as a point in the plane, given by X- and Y-coordinates. This same point may also be described by giving the pair of real numbers (r,phi), where r is the distance to the origin O, and phi the angle between the X-axis and the line Oz. Now z = r*exp(i*phi) = r*(cos(phi)+i*sin(phi)).

The basic operations are defined on z = a+b*i and w = c+d*i as:

addition: z+w = (a+c) + (b+d)*i
multiplication: z*w = (a*c - b*d) + (a*d + b*c)*i
division: z/w = ((a*c + b*d)/(c*c + d*d)) + ((b*c - a*d)/(c*c + d*d))*i

Nearly all math function have a complex counterpart but there are some complex only functions.

EXAMPLE

Your C-compiler can work with complex numbers if it supports the C99 standard. Link with -lm. The imaginary unit is represented by I.

/* check that exp(i * pi) == -1 */
#include <math.h>        /* for atan */
#include <complex.h>

int
main(void)
{
    double pi = 4 * atan(1.0);
    complex z = cexp(I * pi);
    printf("%f + %f * i\n", creal(z), cimag(z));
}

SEE ALSO

cabs(3), carg(3), cexp(3), cimag(3), creal(3)


standards(7)

STANDARDS

Section: Linux Programmer's Manual (7)
Updated: 2006-08-03 Return to Main Contents

NAME

Standards - C and UNIX Standards

DESCRIPTION

The CONFORMING TO section that appears in many manual pages identifies various standards to which the documented interface conforms. The following list briefly describes these standards.
V7
Version 7, the ancestral UNIX from Bell Labs.
4.2BSD
This is an implementation standard defined by the 4.2 release of the Berkeley Software Distribution, released by the University of California at Berkeley. This was the first Berkeley release that contained a TCP/IP stack and the sockets API. 4.2BSD was released in 1983.

Earlier major BSD releases included 3BSD (1980), 4BSD (1980), and 4.1BSD (1981).

4.3BSD
The successor to 4.2BSD, released in 1986.
4.4BSD
The successor to 4.3BSD, released in 1993. This was the last major Berkeley release.
System V
This is an implementation standard defined by AT&T's milestone 1983 release of its commercial System V (five) release. The previous major AT&T release was System III, released in 1981.
System V release 2 (SVr2)
This was the next System V release, made in 1985. The SVr2 was formally described in the System V Interface Definition version 1 (SVID 1) published in 1985.
System V release 3 (SVr3)
This was the successor to SVr2, released in 1986. This release was formally described in the System V Interface Definition version 2 (SVID 2).
System V release 4 (SVr4)
This was the successor to SVr3, released in 1989. This version of System V is described in the "Programmer's Reference Manual: Operating System API (Intel processors)" (Prentice-Hall 1992, ISBN 0-13-951294-2) This release was formally described in the System V Interface Definition version 3 (SVID 3), and is considered the definitive System V release.
SVID 4
System V Interface Definition version 4, issued in 1995. Available online at http://www.sco.com/developers/devspecs/ .
C89
This was the first C language standard, ratified by ANSI (American National Standards Institute) in 1989 (X3.159-1989). Sometimes this is known as ANSI C, but since C99 is also an ANSI standard, this term is ambiguous. This standard was also ratified by ISO (International Standards Organization) in 1990 (ISO/IEC 9899:1990), and is thus occasionally referred to as ISO C90.
C99
This revision of the C language standard was ratified by ISO in 1999 (ISO/IEC 9899:1999).
POSIX.1-1990
"Portable Operating System Interface for Computing Environments". IEEE 1003.1-1990 part 1, ratified by ISO in 1990 (ISO/IEC 9945-1:1990). Further information can be found in Donald Lewine's "POSIX Programmer's Guide" (O'Reilly & Associates, Inc., 1991, ISBN 0-937175-73-0). The term "POSIX" was coined by Richard Stallman.
POSIX.2
IEEE Std 1003.2-1992, describing commands and utilities, ratified by ISO in 1993 (ISO/IEC 9945-2:1993).
POSIX.1b (formerly known as POSIX.4)
IEEE Std 1003.1b-1993 describing real-time facilities for portable operating systems, ratified by ISO in 1996 (ISO/IEC 9945-1:1996). For further information, see "POSIX.4: Programming for the real world" by Bill O. Gallmeister (O'Reilly & Associates, Inc. ISBN 1-56592-074-0).
POSIX.1c
IEEE Std 1003.1c-1995 describing the POSIX threads interfaces.
POSIX.1d
IEEE Std 1003.1c-1999 describing additional real-time extensions.
POSIX.1g
IEEE Std 1003.1g-2000 describing networking APIs (including sockets).
POSIX.1j
IEEE Std 1003.1j-2000 describing advanced real-time extensions.
POSIX.1-1996
A 1996 revision of POSIX.1 which incorporated POSIX.1b and POSIX.1c.
XPG3
Released in 1989, this was the first significant release of the X/Open Portability Guide, produced by the X/Open Company, a multi-vendor consortium. This multi-volume guide was based on the POSIX standards.
XPG4
A revision of the X/Open Portability Guide, released in 1992.
XPG4v2
A 1994 revision of XPG4. This is also referred to as Spec 1170, where 1170 referred to the number of interfaces defined by this standard.
SUS (SUSv1)
Single UNIX Specification. This was a repackaging of XPG4v2 and other X/Open standards (X/Open Curses Issue 4 version 2, X/Open Networking Service (XNS) Issue 4). Systems conforming to this standard can be branded UNIX 95.
SUSv2
Single UNIX Specification version 2. Sometimes also referred to as XPG5. This standard appeared in 1997. Systems conforming to this standard can be branded UNIX 98. See also http://www.UNIX-systems.org/version2/ .)
POSIX.1-2001, SUSv3
This was a 2001 revision and consolidation of the POSIX.1, POSIX.2, and SUS standards into a single document, conducted under the auspices of the Austin group (http://www.opengroup.org/austin/ .) The standard is available online at http://www.unix-systems.org/version3/ , and the interfaces that it describes are also available in the Linux manual pages package under sections 1p and 3p (e.g., "man 3p open").

The standard defines two levels of conformance: POSIX conformance, which is a baseline set of interfaces required of a conforming system; and XSI Conformance, which additionally mandates a set of interfaces (the "XSI extension") which are only optional for POSIX conformance. XSI-conformant systems can be branded UNIX 03. (XSI conformance constitutes the Single UNIX Specification version 3 (SUSv3).)

The POSIX.1-2001 document is broken into four parts:

XBD: Definitions, terms and concepts, header file specifications.

XSH: Specifications of functions (i.e., system calls and library functions in actual implementations).

XCU: Specifications of commands and utilities (i.e., the area formerly described by POSIX.2).

XRAT: Informative text on the other parts of the standard.

POSIX.1-2001 is aligned with C99, so that all of the library functions standardized in C99 are also standardized in POSIX.1-1001.

Two Technical Corrigenda (minor fixes and improvements) of the original 2001 standard have occurred: TC1 in 2003 (referred to as POSIX.1-2003), and TC2 in 2004 (referred to as POSIX.1-2004).

SEE ALSO

feature_test_macros(7)


feature_test_macros(7)

FEATURE_TEST_MACROS

Section: Linux Programmer's Manual (7)
Updated: 2006-04-26 Return to Main Contents

NAME

feature_test_macros - feature test macros

SYNOPSIS

#include <features.h>

DESCRIPTION

Feature test macros allow the programmer to control the definitions that are exposed by system header files when a program is compiled. This can be useful for creating portable applications, by preventing non-standard definitions from being exposed. Other macros can be used to expose non-standard definitions that are not exposed by default. The precise effects of each of the feature test macros described below can be ascertained by inspecting the <features.h> header file.

In order to be effective, a feature test macro must be defined before including any header files. This can either be done in the compilation command (cc -DMACRO=value) or by defining the macro within the source code before including any headers.

Linux/glibc understands the following feature test macros:

_POSIX_C_SOURCE
Defining this macro with the value 1 causes header files to expose definitions conforming to POSIX.1-1990 and ISO C (1990). Defining with the value 199309 or greater additionally exposes definitions for POSIX.1b (real-time extensions). Defining with the value 199506 or greater additionally exposes definitions for POSIX.1c (threads). Defining with the value 200112 exposes definitions corresponding to the POSIX.1-2001 base specification (excluding the XSI extension).
_POSIX_SOURCE
Defining this obsolete macro with any value is equivalent to defining _POSIX_C_SOURCE with the value 1.
_XOPEN_SOURCE
Defining this macro with any value causes header files to expose definitions conforming to POSIX.1, POSIX.2, and XPG4. Defining with the value 500 or greater additionally exposes definitions for SUSv2 (UNIX 98). Defining with the value 600 or greater additionally exposes definitions for SUSv3 (UNIX 03; i.e., the POSIX.1-2001 base specification plus the XSI extension) and C 99 definitions.
_XOPEN_SOURCE_EXTENDED
If this macro is defined with the value 1, and the _XOPEN_SOURCE is defined, then expose definitions corresponding to the XPG4v2 UNIX extensions.
_ISOC99_SOURCE
Exposes C 99 extensions to ISO C (1990).
_LARGEFILE64_SOURCE
Expose definitions for the alternative API specified by the LFS (Large File Summit) as a "transitional extension" to the Single UNIX Specification. (See http://opengroup.org/platform/lfs.html.)
_FILE_OFFSET_BITS
Defining this macro with the value 64 automatically converts references to 32-bit functions and data types related to file I/O and file system operations into references to their 64-bit counterparts. This is useful for performing I/O on large files (> 2 Gigabytes) on 32-bit systems.
_BSD_SOURCE
Defining this macro with any value cause header files to expose BSD-derived definitions. Defining this macro also causes BSD definitions to be preferred in some situations where standards conflict.
_SVID_SOURCE
Defining this macro with any value cause header files to expose System V-derived definitions. (SVID == System V Interface Definition; see standards(7).)
_GNU_SOURCE
Defining this macro (with any value) is equivalent to defining _BSD_SOURCE, _SVID_SOURCE, _LARGEFILE64_SOURCE, _ISOC99_SOURCE _POSIX_C_SOURCE with the value 1999506, and _XOPEN_SOURCE with the value 600. In addition, various GNU-specific extensions are also exposed.
_REENTRANT
Defining this macro exposes definitions of certain reentrant functions. For multithreaded programs, use cc -pthread instead.
_THREAD_SAFE
Synonym for _REENTRANT, provided for compatibility with some other implementations.
_FORTIFY_SOURCE
Defining this macro causes some lightweight checks to be performed to detect some buffer overflow errors when employing various string and memory manipulation functions. Not all buffer overflows are detected, just some common cases. In the current implementation checks are added for calls to memcpy(3), mempcpy(3), memmove(3), memset(3), stpcpy(3), strcpy(3), strncpy(3), strcat(3), strncat(3), sprintf(3), snprintf(3), vsprintf(3), vsnprintf(3), and gets(3). If _FORTIFY_SOURCE is set to 1, with compiler optimization level 1 (gcc -O1) and above, checks that shouldn't change the behavior of conforming programs are performed. With _FORTIFY_SOURCE set to 2 some more checking is added, but some conforming programs might fail. Some of the checks can be performed at compile time, and result in compiler warnings; other checks take place at run time, and result in a run-time error if the check fails. Use of this macro requires compiler support, available with gcc(1) since version 4.0.

When gcc(1) is invoked, the following macros are defined by default: _BSD_SOURCE, _SVID_SOURCE, _POSIX_SOURCE, and _POSIX_C_SOURCE=199506. If individual macros are defined, then other macros are disabled unless they are also explicitly defined. (Exception: if _POSIX_C_SOURCE is not otherwise defined, then it is always defined with the value 200112 (199506 in glibc versions before 2.4), unless the compiler is invoked in one of its standard modes, for example, the -std=c99 flag.) Multiple macros can be defined; the results are additive.

CONFORMING TO

POSIX.1 specifies _POSIX_C_SOURCE, _POSIX_SOURCE, and _XOPEN_SOURCE. _XOPEN_SOURCE_EXTENDED was specified by XPG4v2 (aka SUSv1). _FILE_OFFSET_BITS is not specified by any standard, but is employed on some other implementations. _BSD_SOURCE, _SVID_SOURCE, _GNU_SOURCE, _FORTIFY_SOURCE, _REENTRANT, and _THREAD_SAFE are Linux (glibc) specific.

NOTES

<features.h> is a Linux/glibc specific header file. Other systems have an analogous file, but typically with a different name. This header file is automatically included by other header files as required: it is not necessary to explicitly include it in order to employ feature test macros.

According to which of the above feature test macros are defined, <features.h> internally defines various other macros that are checked by other glibc header files. These macros have names prefixed by two underscores (e.g., __USE_MISC). Programs should never define these macros directly: instead, the appropriate feature test macro(s) from the list above should be employed.


termio(7)

TERMIO

Section: Linux Programmer's Manual (7)
Updated: 2006-12-28 Return to Main Contents

NAME

termio - the System V terminal driver interface

DESCRIPTION

termio is the name of the old System V terminal driver interface. This interface defined a termio structure used to store terminal settings, and a range of ioctl(2) operations to get and set terminal attributes.

The termio interface is now obsolete: POSIX.1-1990 standardized a modified version of this interface, under the name termios. The POSIX.1 data structure differs slightly from the System V version, and POSIX.1 defined a suite of functions to replace the various ioctl(2) operations that existed in System V. (This was done because ioctl(2) was unstandardized, and its variadic third argument does not allow argument type checking.)

If you're looking for page called "termio", then you can probably find most of the information that you seek in either termios(3) or tty_ioctl(4).

SEE ALSO

termios(3), tty_ioctl(4)


epoll(7)

EPOLL

Section: Linux Programmer's Manual (7)
Updated: 2002-10-23 Return to Main Contents

NAME

epoll - I/O event notification facility

SYNOPSIS

#include <sys/epoll.h>

DESCRIPTION

epoll is a variant of poll(2) that can be used either as Edge or Level Triggered interface and scales well to large numbers of watched fds. Three system calls are provided to set up and control an epoll set: epoll_create(2), epoll_ctl(2), epoll_wait(2).

An epoll set is connected to a file descriptor created by epoll_create(2). Interest for certain file descriptors is then registered via epoll_ctl(2). Finally, the actual wait is started by epoll_wait(2).

Level Triggered and Edge Triggered

The epoll event distribution interface is able to behave both as Edge Triggered ( ET ) and Level Triggered ( LT ). The difference between ET and LT event distribution mechanism can be described as follows. Suppose that this scenario happens :
1
The file descriptor that represents the read side of a pipe ( RFD ) is added inside the epoll device.
2
Pipe writer writes 2Kb of data on the write side of the pipe.
3
A call to epoll_wait(2) is done that will return RFD as ready file descriptor.
4
The pipe reader reads 1Kb of data from RFD.
5
A call to epoll_wait(2) is done.

If the RFD file descriptor has been added to the epoll interface using the EPOLLET flag, the call to epoll_wait(2) done in step 5 will probably hang because of the available data still present in the file input buffers and the remote peer might be expecting a response based on the data it already sent. The reason for this is that Edge Triggered event distribution delivers events only when events happens on the monitored file. So, in step 5 the caller might end up waiting for some data that is already present inside the input buffer. In the above example, an event on RFD will be generated because of the write done in 2 and the event is consumed in 3. Since the read operation done in 4 does not consume the whole buffer data, the call to epoll_wait(2) done in step 5 might lock indefinitely. The epoll interface, when used with the EPOLLET flag ( Edge Triggered ) should use non-blocking file descriptors to avoid having a blocking read or write starve the task that is handling multiple file descriptors. The suggested way to use epoll as an Edge Triggered (EPOLLET) interface is below, and possible pitfalls to avoid follow.

i
with non-blocking file descriptors
ii
by going to wait for an event only after read(2) or write(2) return EAGAIN

On the contrary, when used as a Level Triggered interface, epoll is by all means a faster poll(2), and can be used wherever the latter is used since it shares the same semantics. Since even with the Edge Triggered epoll multiple events can be generated up on receipt of multiple chunks of data, the caller has the option to specify the EPOLLONESHOT flag, to tell epoll to disable the associated file descriptor after the receipt of an event with epoll_wait(2). When the EPOLLONESHOT flag is specified, it is caller responsibility to rearm the file descriptor using epoll_ctl(2) with EPOLL_CTL_MOD.

Example for Suggested Usage

While the usage of epoll when employed like a Level Triggered interface does have the same semantics of poll(2), an Edge Triggered usage requires more clarification to avoid stalls in the application event loop. In this example, listener is a non-blocking socket on which listen(2) has been called. The function do_use_fd() uses the new ready file descriptor until EAGAIN is returned by either read(2) or write(2). An event driven state machine application should, after having received EAGAIN, record its current state so that at the next call to do_use_fd() it will continue to read(2) or write(2) from where it stopped before.

struct epoll_event ev, *events;

for(;;) {
    nfds = epoll_wait(kdpfd, events, maxevents, -1);

    for (n = 0; n < nfds; ++n) {
        if (events[n].data.fd == listener) {
            client = accept(listener, (struct sockaddr *) &local,
                            &addrlen);
            if(client < 0){
                perror("accept");
                continue;
            }
            setnonblocking(client);
            ev.events = EPOLLIN | EPOLLET;
            ev.data.fd = client;
            if (epoll_ctl(kdpfd, EPOLL_CTL_ADD, client, &ev) < 0) {
                fprintf(stderr, "epoll set insertion error: fd=%d\n",
                        client);
                return -1;
            }
        } else {
            do_use_fd(events[n].data.fd);
        }
    }
}

When used as an Edge triggered interface, for performance reasons, it is possible to add the file descriptor inside the epoll interface ( EPOLL_CTL_ADD ) once by specifying ( EPOLLIN|EPOLLOUT ). This allows you to avoid continuously switching between EPOLLIN and EPOLLOUT calling epoll_ctl(2) with EPOLL_CTL_MOD.

Questions and Answers

Q1
What happens if you add the same fd to an epoll_set twice?
A1
You will probably get EEXIST. However, it is possible that two threads may add the same fd twice. This is a harmless condition.
Q2
Can two epoll sets wait for the same fd? If so, are events reported to both epoll sets fds?
A2
Yes. However, it is not recommended. Yes it would be reported to both.
Q3
Is the epoll fd itself poll/epoll/selectable?
A3
Yes.
Q4
What happens if the epoll fd is put into its own fd set?
A4
It will fail. However, you can add an epoll fd inside another epoll fd set.
Q5
Can I send the epoll fd over a unix-socket to another process?
A5
No.
Q6
Will the close of an fd cause it to be removed from all epoll sets automatically?
A6
Yes.
Q7
If more than one event comes in between epoll_wait(2) calls, are they combined or reported separately?
A7
They will be combined.
Q8
Does an operation on an fd affect the already collected but not yet reported events?
A8
You can do two operations on an existing fd. Remove would be meaningless for this case. Modify will re-read available I/O.
Q9
Do I need to continuously read/write an fd until EAGAIN when using the EPOLLET flag ( Edge Triggered behavior ) ?
A9
No you don't. Receiving an event from epoll_wait(2) should suggest to you that such file descriptor is ready for the requested I/O operation. You have simply to consider it ready until you will receive the next EAGAIN. When and how you will use such file descriptor is entirely up to you. Also, the condition that the read/write I/O space is exhausted can be detected by checking the amount of data read/write from/to the target file descriptor. For example, if you call read(2) by asking to read a certain amount of data and read(2) returns a lower number of bytes, you can be sure to have exhausted the read I/O space for such file descriptor. Same is valid when writing using the write(2) function.

Possible Pitfalls and Ways to Avoid Them

o Starvation ( Edge Triggered )

If there is a large amount of I/O space, it is possible that by trying to drain it the other files will not get processed causing starvation. This is not specific to epoll.

The solution is to maintain a ready list and mark the file descriptor as ready in its associated data structure, thereby allowing the application to remember which files need to be processed but still round robin amongst all the ready files. This also supports ignoring subsequent events you receive for fd's that are already ready.

o If using an event cache...

If you use an event cache or store all the fd's returned from epoll_wait(2), then make sure to provide a way to mark its closure dynamically (ie- caused by a previous event's processing). Suppose you receive 100 events from epoll_wait(2), and in event #47 a condition causes event #13 to be closed. If you remove the structure and close(2) the fd for event #13, then your event cache might still say there are events waiting for that fd causing confusion.

One solution for this is to call, during the processing of event 47, epoll_ctl(EPOLL_CTL_DEL) to delete fd 13 and close(2), then mark its associated data structure as removed and link it to a cleanup list. If you find another event for fd 13 in your batch processing, you will discover the fd had been previously removed and there will be no confusion.

VERSIONS

epoll(7) is a new API introduced in Linux kernel 2.5.44. Its interface should be finalized in Linux kernel 2.5.66.

CONFORMING TO

The epoll API is Linux specific. Some other systems provide similar mechanisms, for example, FreeBSD has kqueue, and Solaris has /dev/poll.

SEE ALSO

epoll_create(2), epoll_ctl(2), epoll_wait(2)


inotify(7)

INOTIFY

Section: Linux Programmer's Manual (7)
Updated: 2007-06-03 Return to Main Contents

NAME

inotify - monitoring file system events

DESCRIPTION

The inotify API provides a mechanism for monitoring file system events. Inotify can be used to monitor individual files, or to monitor directories. When a directory is monitored, inotify will return events for the directory itself, and for files inside the directory.

The following system calls are used with this API:
inotify_init(2),

inotify_add_watch(2),

inotify_rm_watch(2),

read(2),

and
close(2).

inotify_init(2) creates an inotify instance and returns a file descriptor referring to the inotify instance.

inotify_add_watch(2) manipulates the "watch list" associated with an inotify instance. Each item ("watch") in the watch list specifies the pathname of a file or directory, along with some set of events that the kernel should monitor for the file referred to by that pathname. inotify_add_watch(2) either creates a new watch item, or modifies an existing watch. Each watch has a unique "watch descriptor", an integer returned by inotify_add_watch(2) when the watch is created.

inotify_rm_watch(2) removes an item from an inotify watch list.

When all file descriptors referring to an inotify instance have been closed, the underlying object and its resources are freed for re-use by the kernel; all associated watches are automatically freed.

To determine what events have occurred, an application read(2)s from the inotify file descriptor. If no events have so far occurred, then, assuming a blocking file descriptor, read(2) will block until at least one event occurs.

Each successful read(2) returns a buffer containing one or more of the following structures:

struct inotify_event {
    int      wd;       /* Watch descriptor */
    uint32_t mask;     /* Mask of events */
    uint32_t cookie;   /* Unique cookie associating related
                          events (for rename(2)) */
    uint32_t len;      /* Size of 'name' field */
    char     name[];   /* Optional null-terminated name */
};

wd identifies the watch for which this event occurs. It is one of the watch descriptors returned by a previous call to inotify_add_watch(2).

mask contains bits that describe the event that occurred (see below).

cookie is a unique integer that connects related events. Currently this is only used for rename events, and allows the resulting pair of IN_MOVE_FROM and IN_MOVE_TO events to be connected by the application.

The name field is only present when an event is returned for a file inside a watched directory; it identifies the file pathname relative to the watched directory. This pathname is null-terminated, and may include further null bytes to align subsequent reads to a suitable address boundary.

The len field counts all of the bytes in name, including the null bytes; the length of each inotify_event structure is thus sizeof(inotify_event)+len.

The behavior when the buffer given to read(2) is too small to return information about the next event depends on the kernel version: in kernels before 2.6.21, read(2) returns 0; since kernel 2.6.21, read(2) fails with the error EINVAL.

inotify events

The inotify_add_watch(2) mask argument and the mask field of the inotify_event structure returned when read(2)ing an inotify file descriptor are both bit masks identifying inotify events. The following bits can be specified in mask when calling inotify_add_watch(2) and may be returned in the mask field returned by read(2):
Bit | Description
IN_ACCESS | File was accessed (read) (*)
IN_ATTRIB | Metadata changed (permissions, timestamps,
 | extended attributes, etc.) (*)
IN_CLOSE_WRITE | File opened for writing was closed (*)
IN_CLOSE_NOWRITE | File not opened for writing was closed (*)
IN_CREATE | File/directory created in watched directory (*)
IN_DELETE | File/directory deleted from watched directory (*)
IN_DELETE_SELF | Watched file/directory was itself deleted
IN_MODIFY | File was modified (*)
IN_MOVE_SELF | Watched file/directory was itself moved
IN_MOVED_FROM | File moved out of watched directory (*)
IN_MOVED_TO | File moved into watched directory (*)
IN_OPEN | File was opened (*)

When monitoring a directory, the events marked with an asterisk (*) above can occur for files in the directory, in which case the name field in the returned inotify_event structure identifies the name of the file within the directory.

The IN_ALL_EVENTS macro is defined as a bit mask of all of the above events. This macro can be used as the mask argument when calling inotify_add_watch(2).

Two additional convenience macros are IN_MOVE, which equates to IN_MOVED_FROM|IN_MOVED_TO, and IN_CLOSE which equates to IN_CLOSE_WRITE|IN_CLOSE_NOWRITE.

The following further bits can be specified in mask when calling inotify_add_watch(2):
Bit | Description
IN_DONT_FOLLOW | Don't dereference pathname if it is a symbolic link
IN_MASK_ADD | Add (OR) events to watch mask for this pathname if
 | it already exists (instead of replacing mask)
IN_ONESHOT | Monitor pathname for one event, then remove from
 | watch list
IN_ONLYDIR | Only watch pathname if it is a directory

The following bits may be set in the mask field returned by read(2):
Bit | Description
IN_IGNORED | Watch was removed explicitly (inotify_rm_watch(2))
 | or automatically (file was deleted, or
 | file system was unmounted)
IN_ISDIR | Subject of this event is a directory
IN_Q_OVERFLOW | Event queue overflowed (wd is -1 for this event)
IN_UNMOUNT | File system containing watched object was unmounted

/proc interfaces

The following interfaces can be used to limit the amount of kernel memory consumed by inotify:
/proc/sys/fs/inotify/max_queued_events
The value in this file is used when an application calls inotify_init(2) to set an upper limit on the number of events that can be queued to the corresponding inotify instance. Events in excess of this limit are dropped, but an IN_Q_OVERFLOW event is always generated.
/proc/sys/fs/inotify/max_user_instances
This specifies an upper limit on the number of inotify instances that can be created per real user ID.
/proc/sys/fs/inotify/max_user_watches
This specifies a limit on the number of watches that can be associated with each inotify instance.

VERSIONS

Inotify was merged into the 2.6.13 Linux kernel. The required library interfaces were added to glibc in version 2.4. (IN_DONT_FOLLOW, IN_MASK_ADD, and IN_ONLYDIR were only added in version 2.5.)

CONFORMING TO

The inotify API is Linux specific.

NOTES

Inotify file descriptors can be monitored using select(2), poll(2), and epoll(7).

If successive output inotify events produced on the inotify file descriptor are identical (same wd, mask, cookie, and name) then they are coalesced into a single event.

The events returned by reading from an inotify file descriptor form an ordered queue. Thus, for example, it is guaranteed that when renaming from one directory to another, events will be produced in the correct order on the inotify file descriptor.

The FIONREAD ioctl(2) returns the number of bytes available to read from an inotify file descriptor.

Inotify monitoring of directories is not recursive: to monitor subdirectories under a directory, additional watches must be created.

BUGS

In kernels before 2.6.16, the IN_ONESHOT mask flag does not work.

SEE ALSO

inotify_add_watch(2), inotify_init(2), inotify_rm_watch(2), read(2), stat(2), Documentation/filesystems/inotify.txt.


svipc(7)

SVIPC

Section: Linux Programmer's Manual (7)
Updated: 1993-11-01 Return to Main Contents

NAME

svipc - System V interprocess communication mechanisms

SYNOPSIS

# include <sys/types.h>
# include <sys/ipc.h>
# include <sys/msg.h>
# include <sys/sem.h>
# include <sys/shm.h>

DESCRIPTION

This manual page refers to the Linux implementation of the System V interprocess communication mechanisms: message queues, semaphore sets, and shared memory segments. In the following, the word resource means an instantiation of one among such mechanisms.

Resource Access Permissions

For each resource, the system uses a common structure of type struct ipc_perm to store information needed in determining permissions to perform an ipc operation. The ipc_perm structure, defined by the <sys/ipc.h> system header file, includes the following members:

       uid_t cuid;

/* creator user ID */

gid_t cgid;

/* creator group ID */

uid_t uid;

/* owner user ID */

gid_t gid;

/* owner group ID */

ushort mode;

/* r/w permissions */

The mode member of the ipc_perm structure defines, with its lower 9 bits, the access permissions to the resource for a process executing an ipc system call. The permissions are interpreted as follows:

        0400    Read by user.
        0200    Write by user.

        0040    Read by group.
        0020    Write by group.

        0004    Read by others.
        0002    Write by others.

Bits 0100, 0010, and 0001 (the execute bits) are unused by the system. Furthermore, "write" effectively means "alter" for a semaphore set.

The same system header file also defines the following symbolic constants:

IPC_CREAT
Create entry if key doesn't exist.
IPC_EXCL
Fail if key exists.
IPC_NOWAIT
Error if request must wait.
IPC_PRIVATE
Private key.
IPC_RMID
Remove resource.
IPC_SET
Set resource options.
IPC_STAT
Get resource options.

Note that IPC_PRIVATE is a key_t type, while all the other symbolic constants are flag fields and can be OR'ed into an int type variable.

Message Queues

A message queue is uniquely identified by a positive integer (its msqid) and has an associated data structure of type struct msqid_ds, defined in <sys/msg.h>, containing the following members:

       struct ipc_perm msg_perm;
msgqnum_t msg_qnum;

/* no of messages on queue */

msglen_t msg_qbytes;

/* bytes max on a queue */

pid_t msg_lspid;

/* PID of last msgsnd(2) call */

pid_t msg_lrpid;

/* PID of last msgrcv(2) call */

time_t msg_stime;

/* last msgsnd(2) time */

time_t msg_rtime;

/* last msgrcv(2) time */

time_t msg_ctime;

/* last change time */

msg_perm
ipc_perm structure that specifies the access permissions on the message queue.
msg_qnum
Number of messages currently on the message queue.
msg_qbytes
Maximum number of bytes of message text allowed on the message queue.
msg_lspid
ID of the process that performed the last msgsnd(2) system call.
msg_lrpid
ID of the process that performed the last msgrcv(2) system call.
msg_stime
Time of the last msgsnd(2) system call.
msg_rtime
Time of the last msgrcv(2) system call.
msg_ctime
Time of the last system call that changed a member of the msqid_ds structure.

Semaphore Sets

A semaphore set is uniquely identified by a positive integer (its semid) and has an associated data structure of type struct semid_ds, defined in <sys/sem.h>, containing the following members:

       struct ipc_perm sem_perm;
time_t sem_otime;

/* last operation time */

time_t sem_ctime;

/* last change time */

ulong sem_nsems;

/* count of sems in set */

sem_perm
ipc_perm structure that specifies the access permissions on the semaphore set.
sem_otime
Time of last semop(2) system call.
sem_ctime
Time of last semctl(2) system call that changed a member of the above structure or of one semaphore belonging to the set.
sem_nsems
Number of semaphores in the set. Each semaphore of the set is referenced by a non-negative integer ranging from 0 to sem_nsems-1.

A semaphore is a data structure of type struct sem containing the following members:

       int semval;

/* semaphore value */

int sempid;

/* PID for last operation */

semval
Semaphore value: a non-negative integer.
sempid
ID of the last process that performed a semaphore operation on this semaphore.

Shared Memory Segments

A shared memory segment is uniquely identified by a positive integer (its shmid) and has an associated data structure of type struct shmid_ds, defined in <sys/shm.h>, containing the following members:

       struct ipc_perm shm_perm;
size_t shm_segsz;

/* size of segment */

pid_t shm_cpid;

/* PID of creator */

pid_t shm_lpid;

/* PID, last operation */

shmatt_t shm_nattch;

/* no. of current attaches */

time_t shm_atime;

/* time of last attach */

time_t shm_dtime;

/* time of last detach */

time_t shm_ctime;

/* time of last change */

shm_perm
ipc_perm structure that specifies the access permissions on the shared memory segment.
shm_segsz
Size in bytes of the shared memory segment.
shm_cpid
ID of the process that created the shared memory segment.
shm_lpid
ID of the last process that executed a shmat(2) or shmdt(2) system call.
shm_nattch
Number of current alive attaches for this shared memory segment.
shm_atime
Time of the last shmat(2) system call.
shm_dtime
Time of the last shmdt(2) system call.
shm_ctime
Time of the last shmctl(2) system call that changed shmid_ds.

SEE ALSO

msgctl(2), msgget(2), msgrcv(2), msgsnd(2), semctl(2), semget(2), semop(2), shmat(2), shmctl(2), shmdt(2), shmget(2), ftok(3)


fifo(7)

FIFO

Section: Linux Programmer's Manual (7)
Updated: 1999-06-20 Return to Main Contents

NAME

fifo - first-in first-out special file, named pipe

DESCRIPTION

A FIFO special file (a named pipe) is similar to a pipe, except that it is accessed as part of the file system. It can be opened by multiple processes for reading or writing. When processes are exchanging data via the FIFO, the kernel passes all data internally without writing it to the file system. Thus, the FIFO special file has no contents on the file system, the file system entry merely serves as a reference point so that processes can access the pipe using a name in the file system.

The kernel maintains exactly one pipe object for each FIFO special file that is opened by at least one process. The FIFO must be opened on both ends (reading and writing) before data can be passed. Normally, opening the FIFO blocks until the other end is opened also.

A process can open a FIFO in non-blocking mode. In this case, opening for read only will succeed even if no-one has opened on the write side yet; opening for write only will fail with ENXIO (no such device or address) unless the other end has already been opened.

Under Linux, opening a FIFO for read and write will succeed both in blocking and non-blocking mode. POSIX leaves this behavior undefined. This can be used to open a FIFO for writing while there are no readers available. A process that uses both ends of the connection in order to communicate with itself should be very careful to avoid deadlocks.

NOTES

When a process tries to write to a FIFO that is not opened for read on the other side, the process is sent a SIGPIPE signal.

FIFO special files can be created by mkfifo(3), and are specially indicated in ls -l.

SEE ALSO

mkfifo(1), open(2), pipe(2), sigaction(2), signal(2), socketpair(2), mkfifo(3), pipe(7)


futex(7)

FUTEX

Section: Linux Programmer's Manual (7)
Updated: 2002-12-31 Return to Main Contents

NAME

futex - Fast Userspace Locking

SYNOPSIS

#include <linux/futex.h>

DESCRIPTION

The Linux kernel provides futexes ('Fast Userspace muTexes') as a building block for fast userspace locking and semaphores. Futexes are very basic and lend themselves well for building higher level locking abstractions such as POSIX mutexes.

This page does not set out to document all design decisions but restricts itself to issues relevant for application and library development. Most programmers will in fact not be using futexes directly but instead rely on system libraries built on them, such as the NPTL pthreads implementation.

A futex is identified by a piece of memory which can be shared between different processes. In these different processes, it need not have identical addresses. In its bare form, a futex has semaphore semantics; it is a counter that can be incremented and decremented atomically; processes can wait for the value to become positive.

Futex operation is entirely userspace for the non-contended case. The kernel is only involved to arbitrate the contended case. As any sane design will strive for non-contention, futexes are also optimized for this situation.

In its bare form, a futex is an aligned integer which is only touched by atomic assembler instructions. Processes can share this integer using mmap(2), via shared memory segments or because they share memory space, in which case the application is commonly called multithreaded.

Semantics

Any futex operation starts in userspace, but it may necessary to communicate with the kernel using the futex(2) system call.

To 'up' a futex, execute the proper assembler instructions that will cause the host CPU to atomically increment the integer. Afterwards, check if it has in fact changed from 0 to 1, in which case there were no waiters and the operation is done. This is the non-contended case which is fast and should be common.

In the contended case, the atomic increment changed the counter from -1 (or some other negative number). If this is detected, there are waiters. Userspace should now set the counter to 1 and instruct the kernel to wake up any waiters using the FUTEX_WAKE operation.

Waiting on a futex, to 'down' it, is the reverse operation. Atomically decrement the counter and check if it changed to 0, in which case the operation is done and the futex was uncontended. In all other circumstances, the process should set the counter to -1 and request that the kernel wait for another process to up the futex. This is done using the FUTEX_WAIT operation.

The futex(2) system call can optionally be passed a timeout specifying how long the kernel should wait for the futex to be upped. In this case, semantics are more complex and the programmer is referred to futex(2) for more details. The same holds for asynchronous futex waiting.

VERSIONS

Initial futex support was merged in Linux 2.5.7 but with different semantics from those described above. Current semantics are available from Linux 2.5.40 onwards.

NOTES

To reiterate, bare futexes are not intended as an easy to use abstraction for end-users. Implementors are expected to be assembly literate and to have read the sources of the futex userspace library referenced below.

This man page illustrates the most common use of the futex(2) primitives: it is by no means the only one.

SEE ALSO

futex(2), `Fuss, Futexes and Furwocks: Fast Userlevel Locking in Linux' (proceedings of the Ottawa Linux Symposium 2002), futex example library, futex-*.tar.bz2 <URL:ftp://ftp.kernel.org:/pub/linux/kernel/people/rusty/>.


pipe(7)

PIPE

Section: Linux Programmer's Manual (7)
Updated: 2005-12-08 Return to Main Contents

NAME

pipe - overview of pipes and FIFOs

DESCRIPTION

Pipes and FIFOs (also known as named pipes) provide a unidirectional interprocess communication channel. A pipe has a read end and a write end. Data written to the write end of a pipe can be read from the read end of the pipe.

A pipe is created using pipe(2), which creates a new pipe and returns two file descriptors, one referring to the read end of the pipe, the other referring to the write end. Pipes can be used to create a communication channel between related processes; see pipe(2) for an example.

A FIFO (short for First In First Out) has a name within the file system (created using mkfifo(3)), and is opened using open(2). Any process may open a FIFO, assuming the file permissions allow it. The read end is opened using the O_RDONLY flag; the write end is opened using the O_WRONLY flag. See fifo(7) for further details. Note: although FIFOs have a pathname in the file system, I/O on FIFOs does not involve operations on the underlying device (if there is one).

I/O on Pipes and FIFOs

The only difference between pipes and FIFOs is the manner in which they are created and opened. Once these tasks have been accomplished, I/O on pipes and FIFOs has exactly the same semantics.

If a process attempts to read from an empty pipe, then read(2) will block until data is available. If a process attempts to write to a full pipe (see below), then write(2) blocks until sufficient data has been read from the pipe to allow the write to complete. Non-blocking I/O is possible by using the fcntl(2) F_SETFL operation to enable the O_NONBLOCK open file status flag.

The communication channel provided by a pipe is a byte stream: there is no concept of message boundaries.

If all file descriptors referring to the write end of a pipe have been closed, then an attempt to read(2) from the pipe will see end-of-file (read(2) will return 0). If all file descriptors referring to the read end of a pipe have been closed, then a write(2) will cause a SIGPIPE signal to be generated for the calling process. If the calling process is ignoring this signal, then write(2) fails with the error EPIPE. An application that uses pipe(2) and fork(2) should use suitable close(2) calls to close unnecessary duplicate file descriptors; this ensures that end-of-file and SIGPIPE/EPIPE are delivered when appropriate.

It is not possible to apply lseek(2) to a pipe.

Pipe Capacity

A pipe has a limited capacity. If the pipe is full, then a write(2) will block or fail, depending on whether the O_NONBLOCK flag is set (see below). Different implementations have different limits for the pipe capacity. Applications should not rely on a particular capacity: an application should be designed so that a reading process consumes data as soon as it is available, so that a writing process does not remain blocked.

In Linux versions before 2.6.11, the capacity of a pipe was the same as the system page size (e.g., 4096 bytes on x86). Since Linux 2.6.11, the pipe capacity is 65536 bytes.

PIPE_BUF

POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic: the output data is written to the pipe as a contiguous sequence. Writes of more than PIPE_BUF bytes may be non-atomic: the kernel may interleave the data with data written by other processes. POSIX.1-2001 requires PIPE_BUF to be at least 512 bytes. (On Linux, PIPE_BUF is 4096 bytes.) The precise semantics depend on whether the file descriptor is non-blocking (O_NONBLOCK), whether there are multiple writers to the pipe, and on n, the number of bytes to be written:
O_NONBLOCK disabled, n <= PIPE_BUF
All n bytes are written atomically; write(2) may block if there is not room for n bytes to be written immediately
O_NONBLOCK enabled, n <= PIPE_BUF
If there is room to write n bytes to the pipe, then write(2) succeeds immediately, writing all n bytes; otherwise write(2) fails, with errno set to EAGAIN.
O_NONBLOCK disabled, n > PIPE_BUF
The write is non-atomic: the data given to write(2) may be interleaved with write(2)s by other process; the write(2) blocks until n bytes have been written.
O_NONBLOCK enabled, n > PIPE_BUF
If the pipe is full, then write(2) fails, with errno set to EAGAIN. Otherwise, from 1 to n bytes may be written (i.e., a "partial write" may occur; the caller should check the return value from write(2) to see how many bytes were actually written), and these bytes may be interleaved with writes by other processes.

Open File Status Flags

The only open file status flags that can be meaningfully applied to a pipe or FIFO are O_NONBLOCK and O_ASYNC.

Setting the O_ASYNC flag for the read end of a pipe causes a signal (SIGIO by default) to be generated when new input becomes available on the pipe (see fcntl(2) for details). On Linux, O_ASYNC is supported for pipes and FIFOs only since kernel 2.6.

Portability notes

On some systems (but not Linux), pipes are bidirectional: data can be transmitted in both directions between the pipe ends. According to POSIX.1-2001, pipes only need to be unidirectional. Portable applications should avoid reliance on bidirectional pipe semantics.

SEE ALSO

dup(2), fcntl(2), open(2), pipe(2), poll(2), select(2), socketpair(2), stat(2), mkfifo(3), epoll(7), fifo(7)


time(7)

TIME

Section: Linux Programmer's Manual (7)
Updated: 2006-04-28 Return to Main Contents

NAME

time - overview of time

DESCRIPTION

Real time and process time

Real time is defined as time measured from some fixed point, either from a standard point in the past (see the description of the Epoch and calendar time below), or from some point (e.g., the start) in the life of a process (elapsed time).

Process time is defined as the amount of CPU time used by a process. This is sometimes divided into user and system components. User CPU time is the time spent executing code in user mode. System CPU time is the time spent by the kernel executing in system mode on behalf of the process (e.g., executing system calls). The time(1) command can be used to determine the amount of CPU time consumed during the execution of a program. A program can determine the amount of CPU time it has consumed using times(2), getrusage(2), or clock(3).

The Hardware Clock

Most computers have a (battery-powered) hardware clock which the kernel reads at boot time in order to initialize the software clock. For further details, see rtc(4) and hwclock(8).

The Software Clock, HZ, and Jiffies

The accuracy of many system calls and timestamps is limited by the resolution of the software clock, a clock maintained by the kernel which measures time in jiffies. The size of a jiffy is determined by the value of the kernel constant HZ. The value of HZ varies across kernel versions and hardware platforms. On x86 the situation is as follows: on kernels up to and including 2.4.x, HZ was 100, giving a jiffy value of 0.01 seconds; starting with 2.6.0, HZ was raised to 1000, giving a jiffy of 0.001 seconds; since kernel 2.6.13, the HZ value is a kernel configuration parameter and can be 100, 250 (the default) or 1000, yielding a jiffies value of, respectively, 0.01, 0.004, or 0.001 seconds. Since kernel 2.6.20, a further frequency is available: 300, a number that divides evenly for the common video frame rates (PAL, 25 HZ; NTSC, 30 HZ).

The Epoch

Unix systems represent time in seconds since the Epoch, which is defined as 0:00:00 UTC on the morning of 1 January 1970.

A program can determine the calendar time using gettimeofday(2), which returns time (in seconds and microseconds) that have elapsed since the Epoch; time(2) provides similar information, but only with accuracy to the nearest second. The system time can be changed using settimeofday(2).

Broken-down time

Certain library functions use a structure of type tm to represent broken-down time, which stores time value separated out into distinct components (year, month, day, hour, minute, second, etc.). This structure is described in ctime(3), which also describes functions that convert between calendar time and broken-down time. Functions for converting between broken-down time and printable string representations of the time are described in ctime(3), strftime(3), and strptime(3).

Sleeping and Setting Timers

Various system calls and functions allow a program to sleep (suspend execution) for a specified period of time; see nanosleep(2) and sleep(3).

Various system calls allow a process to set a timer that expires at some point in the future, and optionally at repeated intervals; see alarm(2), getitimer(2), and timer_create(3).

SEE ALSO

date(1), time(1), adjtimex(2), alarm(2), getitimer(2), getrlimit(2), getrusage(2), gettimeofday(2), nanosleep(2), stat(2), time(2), times(2), utime(2), adjtime(3), clock(3), sleep(3), ctime(3), strftime(3), strptime(3), usleep(3), rtc(4), hwclock(8)


credentials(7)

CREDENTIALS

Section: Linux Programmer's Manual (7)
Updated: 2007-06-13 Return to Main Contents

NAME

credentials - process identifiers

DESCRIPTION

Process ID (PID)

Each process has a unique non-negative integer identifier that is assigned when the process is created using fork(2). A process can obtain its PID using getpid(2). A PID is represented using the type pid_t (defined in <sys/types.h>).

PIDs are used in a range of system calls to identify the process
affected by the call, for example:
kill(2),

ptrace(2),

setpriority(2)

setpgid(2),

setsid(2),

sigqueue(2),

and
waitpid(2).

A process's PID is preserved across an execve(2).

Parent Process ID (PPID)

A process's parent process ID identifies the process that created this process using fork(2). A process can obtain its PPID using getppid(2). A PPID is represented using the type pid_t.

A process's PPID is preserved across an execve(2).

Process Group ID and Session ID

Each process has a session ID and a process group ID, both represented using the type pid_t. A process can obtain its session ID using getsid(2), and its process group ID using getpgrp(2).

A child created by fork(2) inherits its parent's session ID and process group ID. A process's session ID and process group ID are preserved across an execve(2).

Sessions and process groups are abstractions devised to support shell job control. A process group (sometimes called a "job") is a collection of processes that share the same process group ID; the shell creates a new process group for the process(es) used to execute single command or pipeline (e.g., the two processes created to execute the command "ls | wc" are placed in the same process group). A process's group membership can be set using setpgid(2). The process whose process ID is the same as its process group ID is the process group leader for that group.

A session is a collection of processes that share the same session ID. All of the members of a process group also have the same session ID (i.e., all of the members of a process group always belong to the same session, so that sessions and process groups form a strict two-level hierarchy of processes.) A new session is created when a process calls setsid(2), which creates a new session whose session ID is the same as the PID of the process that called setsid(2). The creator of the session is called the session leader.

User and Group Identifiers

Each process has various associated user and groups IDs. These IDs are integers, respectively represented using the types uid_t and gid_t (defined in <sys/types.h>).

On Linux, each process has the following user and group identifiers:

*
Real user ID and real group ID. These IDs determine who owns the process. A process can obtain its real user (group) ID using getuid(2) (getgid(2)).
*
Effective user ID and effective group ID. These IDs are used by the kernel to determine the permissions that the process will have when accessing shared resources such as message queues, shared memory, and semaphores. On most Unix systems, these IDs also determine the permissions when accessing files. However, Linux uses the file system IDs described below for this task. A process can obtain its effective user (group) ID using geteuid(2) (getegid(2)).
*
Saved set-user-ID and saved set-group-ID. These IDs are used in set-user-ID and set-group-ID programs to save a copy of the corresponding effective IDs that were set when the program was executed (see execve(2)). A set-user-ID program can assume and drop privileges by switching its effective user ID back and forth between the values in its real user ID and saved set-user-ID. This switching is done via calls to seteuid(2), setreuid(2), or setresuid(2). A set-group-ID program performs the analogous tasks using setegid(2), setregid(2), or setresgid(2). A process can obtain its saved set-user-ID (set-group-ID) using getresuid(2) (getresgid(2)).
*
File system user ID and file system group ID. These IDs, in conjunction with the supplementary group IDs described below, are used to determine permissions for accessing files; see path_resolution(7) for details. Whenever a process's effective user (group) ID is changed, the kernel also automatically changes the file system user (group) ID to the same value. Consequently, the file system IDs normally have the same values as the corresponding effective ID, and the semantics for file-permission checks are thus the same on Linux as on other Unix systems. The file system IDs can be made to differ from the effective IDs by calling setfsuid(2) and setfsgid(2).
*
Supplementary group IDs. This is a set of additional group IDs that are used for permission checks when accessing files and other shared resources. On Linux kernels before 2.6.4, a process can be a member of up to 32 supplementary groups; since kernel 2.6.4, a process can be a member of up to 65536 supplementary groups. A process can obtain its set of supplementary group IDs using and can modify the set using setgroups(2).

A child process created by fork(2) inherits copies of its parent's user and groups IDs. During an execve(2), a process's real user and group ID and supplementary group IDs are preserved; the effective and saved set IDs may be changed, as described in execve(2).

Aside from the purposes noted above, a process's user IDs are also employed in a number of other contexts:

*
when determining the permissions for sending signals --- see kill(2);
*
when determining the permissions for setting process-scheduling parameters (nice value, real time scheduling policy and priority, CPU affinity, I/O priority) using setpriority(2), sched_setaffinity(2), sched_setscheduler(2), sched_setparam(2), and ioprio_set(2);
*
when checking resource limits; see getrlimit(2);
*
when checking the limit on the number of inotify instances that the process may create; see inotify(7).

CONFORMING TO

Process IDs, parent process IDs, process group IDs and session IDs are specified in POSIX.1-2001. The real, effective and saved set IDs are specified in POSIX.1-2001. The file system IDs are a Linux extension.

NOTES

Credentials are shared by all of the threads in a process.

SEE ALSO

csh(1), bash(1), ps(1), access(2), execve(2), faccessat(2), fork(2), getpgrp(2), getpid(2), getppid(2), getsid(2), kill(2), killpg(2), setegid(2), seteuid(2), setfsgid(2), setfsuid(2), setgid(2), setgroups(2), setresgid(2), setresuid(2), setuid(2), waitpid(2), euidaccess(3), initgroups(3), tcgetpgrp(3), tcsetpgrp(3), capabilities(7), path_resolution(7), unix(7)


pthreads(7)

PTHREADS

Section: Linux Programmer's Manual (7)
Updated: 2005-06-07 Return to Main Contents

NAME

pthreads - POSIX threads

DESCRIPTION

POSIX.1 specifies a set of interfaces (functions, header files) for threaded programming commonly known as POSIX threads, or Pthreads. A single process can contain multiple threads, all of which are executing the same program. These threads share the same global memory (data and heap segments), but each thread has its own stack (automatic variables).

POSIX.1 also requires that threads share a range of other attributes (i.e., these attributes are process-wide rather than per-thread):

-
process ID
-
parent process ID
-
process group ID and session ID
-
controlling terminal
-
user and group IDs
-
open file descriptors
-
record locks (see fcntl(2))
-
signal dispositions
-
file mode creation mask (umask(2))
-
current directory (chdir(2)) and root directory (chroot(2))
-
interval timers (setitimer(2)) and POSIX timers (timer_create(3))
-
nice value (setpriority(2))
-
resource limits (setrlimit(2))
-
measurements of the consumption of CPU time (times(2)) and resources (getrusage(2))

As well as the stack, POSIX.1 specifies that various other attributes are distinct for each thread, including:

-
thread ID (the pthread_t data type)
-
signal mask (pthread_sigmask(3))
-
the errno variable
-
alternate signal stack (sigaltstack(2))
-
real-time scheduling policy and priority (sched_setscheduler(2) and sched_setparam(2))

The following Linux-specific features are also per-thread:

-
capabilities (see capabilities(7))
-
CPU affinity (sched_setaffinity(2))

Compiling on Linux

On Linux, programs that use the Pthreads API should be compiled using cc -pthread.

Linux Implementations of POSIX Threads

Over time, two threading implementations have been provided by the GNU C library on Linux:
-
LinuxThreads This is the original (now obsolete) Pthreads implementation.
-
NPTL (Native POSIX Threads Library) This is the modern Pthreads implementation. By comparison with LinuxThreads, NPTL provides closer conformance to the requirements of the POSIX.1 specification and better performance when creating large numbers of threads. NPTL requires features that are present in the Linux 2.6 kernel.

Both of these are so-called 1:1 implementations, meaning that each thread maps to a kernel scheduling entity.

Both threading implementations employ the Linux clone(2) system call. In NPTL, thread synchronization primitives (mutexes, thread joining, etc.) are implemented using the Linux futex(2) system call.

Modern GNU C libraries provide both LinuxThreads and NPTL, with the latter being the default (if supported by the underlying kernel).

LinuxThreads

The notable features of this implementation are the following:
-
In addition to the main (initial) thread, and the threads that the program creates using pthread_create(3), the implementation creates a "manager" thread. This thread handles thread creation and termination. (Problems can result if this thread is inadvertently killed.)
-
Signals are used internally by the implementation. On Linux 2.2 and later, the first three real-time signals are used. On older Linux kernels, SIGUSR1 and SIGUSR2 are used. Applications must avoid the use of whichever set of signals is employed by the implementation.
-
Threads do not share process IDs. (In effect, LinuxThreads threads are implemented as processes which share more information than usual, but which do not share a common process ID.) LinuxThreads threads (including the manager thread) are visible as separate processes using ps(1).

The LinuxThreads implementation deviates from the POSIX.1 specification in a number of ways, including the following:

-
Calls to getpid(2) return a different value in each thread.
-
Calls to getppid(2) in threads other than the main thread return the process ID of the manager thread; instead getppid(2) in these threads should return the same value as getppid(2) in the main thread.
-
When one thread creates a new child process using fork(2), any thread should be able to wait(2) on the child. However, the implementation only allows the thread that created the child to wait(2) on it.
-
When a thread calls execve(2), all other threads are terminated (as required by POSIX.1). However, the resulting process has the same PID as the thread that called execve(2): it should have the same PID as the main thread.
-
Threads do not share user and group IDs. This can cause complications with set-user-ID programs and can cause failures in Pthreads functions if an application changes its credentials using seteuid(2) or similar.
-
Threads do not share a common session ID and process group ID.
-
Threads do not share record locks created using fcntl(2).
-
The information returned by times(2) and getrusage(2) is per-thread rather than process-wide.
-
Threads do not share semaphore undo values (see semop(2)).
-
Threads do not share interval timers.
-
Threads do not share a common nice value.
-
POSIX.1 distinguishes the notions of signals that are directed to the process as a whole and signals are directed to individual threads. According to POSIX.1, a process-directed signal (sent using kill(2), for example) should be handled by a single, arbitrarily selected thread within the process. LinuxThreads does not support the notion of process-directed signals: signals may only be sent to specific threads.
-
Threads have distinct alternate signal stack settings. However, a new thread's alternate signal stack settings are copied from the thread that created it, so that the threads initially share an alternate signal stack. (A new thread should start with no alternate signal stack defined. If two threads handle signals on their shared alternate signal stack at the same time, unpredictable program failures are likely to occur.)

NPTL

With NPTL, all of the threads in a process are placed in the same thread group; all members of a thread groups share the same PID. NPTL does not employ a manager thread. NPTL makes internal use of the first two real-time signals; these signals cannot be used in applications.

NPTL still has a few non-conformances with POSIX.1:

-
Threads do not share a common nice value.

Some NPTL non-conformances only occur with older kernels:

-
The information returned by times(2) and getrusage(2) is per-thread rather than process-wide (fixed in kernel 2.6.9).
-
Threads do not share resource limits (fixed in kernel 2.6.10).
-
Threads do not share interval timers (fixed in kernel 2.6.12).
-
Only the main thread is permitted to start a new session using setsid(2) (fixed in kernel 2.6.16).
-
Only the main thread is permitted to make the process into a process group leader using setpgid(2) (fixed in kernel 2.6.16).
-
Threads have distinct alternate signal stack settings. However, a new thread's alternate signal stack settings are copied from the thread that created it, so that the threads initially share an alternate signal stack (fixed in kernel 2.6.16).

Note the following further points about the NPTL implementation:

-
If the stack size soft resource limit (see the description of RLIMIT_STACK in setrlimit(2)) is set to a value other than unlimited, then this value defines the default stack size for new threads. To be effective, this limit must be set before the program is executed, perhaps using the ulimit -s shell built-in command (limit stacksize in the C shell).

Determining the Threading Implementation

Since glibc 2.3.2, the getconf(1) command can be used to determine the system's default threading implementation, for example:

bash$ getconf GNU_LIBPTHREAD_VERSION
NPTL 2.3.4

With older glibc versions, a command such as the following should be sufficient to determine the default threading implementation:

bash$ $( ldd /bin/ls | grep libc.so | awk '{print $3}' ) | \
                egrep -i 'threads|ntpl'
        Native POSIX Threads Library by Ulrich Drepper et al

Selecting the Threading Implementation: LD_ASSUME_KERNEL

On systems with a glibc that supports both LinuxThreads and NPTL, the LD_ASSUME_KERNEL environment variable can be used to override the dynamic linker's default choice of threading implementation. This variable tells the dynamic linker to assume that it is running on top of a particular kernel version. By specifying a kernel version that does not provide the support required by NPTL, we can force the use of LinuxThreads. (The most likely reason for doing this is to run a (broken) application that depends on some non-conformant behavior in LinuxThreads.) For example:

bash$ $( LD_ASSUME_KERNEL=2.2.5 ldd /bin/ls | grep libc.so | \
                awk '{print $3}' ) | egrep -i 'threads|ntpl'
        linuxthreads-0.10 by Xavier Leroy

SEE ALSO

clone(2), futex(2), gettid(2), futex(7), and various Pthreads manual pages, for example: pthread_atfork(3), pthread_cleanup_push(3), pthread_cond_signal(3), pthread_cond_wait(3), pthread_create(3), pthread_detach(3), pthread_equal(3), pthread_exit(3), pthread_key_create(3), pthread_kill(3), pthread_mutex_lock(3), pthread_mutex_unlock(3), pthread_once(3), pthread_setcancelstate(3), pthread_setcanceltype(3), pthread_setspecific(3), pthread_sigmask(3), and pthread_testcancel(3).


sem_overview(7)

SEM_OVERVIEW

Section: Linux Programmer's Manual (7)
Updated: 2006-03-25 Return to Main Contents

NAME

sem_overview - Overview of POSIX semaphores

DESCRIPTION

POSIX semaphores allow processes and threads to synchronize their actions.

A semaphore is an integer whose value is never allowed to fall below zero. Two operations can be performed on semaphores: increment the semaphore value by one (sem_post(3)); and decrement the semaphore value by one (sem_wait(3)). If the value of a semaphore is currently zero, then a sem_wait(3) operation will block until the value becomes greater than zero.

POSIX semaphores come in two forms: named semaphores and unnamed semaphores.

Named semaphores

A named semaphore is identified by a name of the form /somename. Two processes can operate on the same named semaphore by passing the same name to sem_open(3).

The sem_open(3) function creates a new named semaphore or opens an existing named semaphore. After the semaphore has been opened, it can be operated on using sem_post(3) and sem_wait(3). When a process has finished using the semaphore, it can use sem_close(3) to close the semaphore. When all processes have finished using the semaphore, it can be removed from the system using sem_unlink(3).

Unnamed semaphores (memory-based semaphores)

An unnamed semaphore does not have a name. Instead the semaphore is placed in a region of memory that is shared between multiple threads (a thread-shared semaphore) or processes (a process-shared semaphore). A thread-shared semaphore is placed in an area of memory shared between by the threads of a process, for example, a global variable. A process-shared semaphore must be placed in a shared memory region (e.g., a System V shared memory segment created using semget(2), or a POSIX shared memory object built created using shm_open(3)).

Before being used, an unnamed semaphore must be initialized using sem_init(3). It can then be operated on using sem_post(3) and sem_wait(3). When the semaphore is no longer required, and before the memory in which it is located is deallocated, the semaphore should be destroyed using sem_destroy(3).

LINUX SPECIFIC DETAILS

Versions

Prior to kernel 2.6, Linux only supported unnamed, thread-shared semaphores. On a system with Linux 2.6 and a glibc that provides the NPTL threading implementation, a complete implementation of POSIX semaphores is provided.

Persistence

POSIX named semaphores have kernel persistence: if not removed by sem_unlink(3), a semaphore will exist until the system is shut down.

Linking

Programs using the POSIX semaphores API must be compiled with cc -lrt to link against the real-time library, librt.

Accessing named semaphores via the file system

On Linux, named semaphores are created in a virtual file system, normally mounted under /dev/shm, with names of the form sem.name.

CONFORMING TO

POSIX.1-2001.

NOTES

System V semaphores (semget(2), semop(2), etc.) are an older semaphore API. POSIX semaphores provide a simpler, and better designed interface than System V semaphores; on the other hand POSIX semaphores are less widely available (especially on older systems) than System V semaphores.

EXAMPLE

An example of the use of various POSIX semaphore functions is shown in sem_wait(3).

SEE ALSO

sem_close(3), sem_destroy(3), sem_init(3), sem_getvalue(3), sem_open(3), sem_post(3), sem_unlink(3), sem_wait(3), pthreads(7)


mq_overview(7)

MQ_OVERVIEW

Section: Linux Programmer's Manual (7)
Updated: 2006-02-25 Return to Main Contents

NAME

mq_overview - Overview of POSIX message queues

DESCRIPTION

POSIX message queues allow processes to exchange data in the form of messages. This API is distinct from that provided by System V message queues (msgget(2), msgsnd(2), msgrcv(2), etc.), but provides similar functionality.

Message queues are created and opened using mq_open(3); this function returns a message queue descriptor (mqd_t), which is used to refer to the open message queue in later calls. Each message queue is identified by a name of the form /somename. Two processes can operate on the same queue by passing the same name to mq_open(3).

Messages are transferred to and from a queue using mq_send(3) and mq_receive(3). When a process has finished using the queue, it closes it using mq_close(3), and when the queue is no longer required, it can be deleted using mq_unlink(3). Queue attributes can be retrieved and (in some cases) modified using mq_getattr(3) and mq_setattr(3). A process can request asynchronous notification of the arrival of a message on a previously empty queue using mq_notify(3).

A message queue descriptor is a reference to an open message queue description (cf. open(2)). After a fork(2), a child inherits copies of its parent's message queue descriptors, and these descriptors refer to the same open message queue descriptions as the corresponding descriptors in the parent. Corresponding descriptors in the two processes share the flags (mq_flags) that are associated with the open message queue description.

Each message has an associated priority, and messages are always delivered to the receiving process highest priority first. Message priorities range from 0 (low) to sysconf(_SC_MQ_PRIO_MAX) - 1 (high). On Linux, sysconf(_SC_MQ_PRIO_MAX) returns 32768, but POSIX.1-2001 only requires an implementation to support priorities in the range 0 to 31; some implementations only provide this range.

Library interfaces and system calls

In most cases the mq_*() library interfaces listed above are implemented on top of underlying system calls of the same name. Deviations from this scheme are indicated in the following table:
Library interface | System call
mq_close(3) | close(2)
mq_getattr(3) | mq_getsetattr(2)
mq_open(3) | mq_open(2)
mq_receive(3) | mq_timedreceive(2)
mq_send(3) | mq_timedsend(2)
mq_setattr(3) | mq_getsetattr(2)
mq_timedreceive(3) | mq_timedreceive(2)
mq_timedsend(3) | mq_timedsend(2)
mq_unlink(3) | mq_unlink(2)

LINUX SPECIFIC DETAILS

Versions

POSIX message queues have been supported on Linux since kernel 2.6.6. Glibc support has been provided since version 2.3.4.

Kernel configuration

Support for POSIX message queues is configurable via the CONFIG_POSIX_MQUEUE kernel configuration option. This option is enabled by default.

Persistence

POSIX message queues have kernel persistence: if not removed by mq_unlink(3), a message queue will exist until the system is shut down.

Linking

Programs using the POSIX message queue API must be compiled with cc -lrt to link against the real-time library, librt.

/proc interfaces

The following interfaces can be used to limit the amount of kernel memory consumed by POSIX message queues:
/proc/sys/fs/mqueue/msg_max
This file can be used to view and change the ceiling value for the maximum number of messages in a queue. This value acts as a ceiling on the attr->mq_maxmsg argument given to mq_open(3). The default and minimum value for msg_max is 10; the upper limit is HARD_MAX: (131072 / sizeof(void *)) (32768 on Linux/86). This limit is ignored for privileged processes (CAP_SYS_RESOURCE), but the HARD_MAX ceiling is nevertheless imposed.
/proc/sys/fs/mqueue/msgsize_max
This file can be used to view and change the ceiling on the maximum message size. This value acts as a ceiling on the attr->mq_msgsize argument given to mq_open(3). The default and minimum value for msgsize_max is 8192 bytes; the upper limit is INT_MAX (2147483647 on Linux/86). This limit is ignored for privileged processes (CAP_SYS_RESOURCE).
/proc/sys/fs/mqueue/queues_max
This file can be used to view and change the system-wide limit on the number of message queues that can be created. Only privileged processes (CAP_SYS_RESOURCE) can create new message queues once this limit has been reached. The default value for queues_max is 256; it can be changed to any value in the range 0 to INT_MAX.

Resource limit

The RLIMIT_MSGQUEUE resource limit, which places a limit on the amount of space that can be consumed by all of the message queues belonging to a process's real user ID, is described in getrlimit(2).

Mounting the message queue file system

On Linux, message queues are created in a virtual file system. (Other implementations may also provide such a feature, but the details are likely to differ.) This file system can be mounted using the following commands:

$ mkdir /dev/mqueue
$ mount -t mqueue none /dev/mqueue
The sticky bit is automatically enabled on the mount directory.

After the file system has been mounted, the message queues on the system can be viewed and manipulated using the commands usually used for files (e.g., ls(1) and rm(1)).

The contents of each file in the directory consist of a single line containing information about the queue:

$ ls /dev/mqueue/mymq
QSIZE:129     NOTIFY:2    SIGNO:0    NOTIFY_PID:8260
$ mount -t mqueue none /dev/mqueue
These fields are as follows:
QSIZE
Number of bytes of data in all messages in the queue.
NOTIFY_PID
If this is non-zero, then the process with this PID has used mq_notify(3) to register for asynchronous message notification, and the remaining fields describe how notification occurs.
NOTIFY
Notification method: 0 is SIGEV_SIGNAL; 1 is SIGEV_NONE; and 2 is SIGEV_THREAD.
SIGNO
Signal number to be used for SIGEV_SIGNAL.

Polling message queue descriptors

On Linux, a message queue descriptor is actually a file descriptor, and can be monitored using select(2), poll(2), or epoll(7). This is not portable.

CONFORMING TO

POSIX.1-2001.

NOTES

System V message queues (msgget(2), msgsnd(2), msgrcv(2), etc.) are an older API for exchanging messages between processes. POSIX message queues provide a better designed interface than System V message queues; on the other hand POSIX message queues are less widely available (especially on older systems) than System V message queues.

EXAMPLE

An example of the use of various message queue functions is shown in mq_notify(3).

SEE ALSO

getrlimit(2), mq_getsetattr(2), mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), poll(2), select(2), epoll(4)


environ(7)

ENVIRON

Section: Linux Programmer's Manual (7)
Updated: 2001-12-14 Return to Main Contents

NAME

environ - user environment

SYNOPSIS

extern char **environ;

DESCRIPTION

The variable environ points to an array of strings called the `environment'. (This variable must be declared in the user program, but is declared in the header file <unistd.h> in case the header files came from libc4 or libc5, and in case they came from glibc and _GNU_SOURCE was defined.) This array of strings is made available to the process by the exec(3) call that started the process. By convention these strings have the form `name=value'. Common examples are:
USER
The name of the logged-in user (used by some BSD-derived programs).
LOGNAME
The name of the logged-in user (used by some System-V derived programs).
HOME
A user's login directory, set by login(1) from the password file passwd(5).
LANG
The name of a locale to use for locale categories when not overridden by LC_ALL or more specific environment variables like LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME, cf. locale(5).
PATH
The sequence of directory prefixes that sh(1) and many other programs apply in searching for a file known by an incomplete pathname. The prefixes are separated by `:'. (Similarly one has CDPATH used by some shells to find the target of a change directory command, MANPATH used by man(1) to find manual pages, etc.)
PWD
The current working directory. Set by some shells.
SHELL
The pathname of the user's login shell.
TERM
The terminal type for which output is to be prepared.
PAGER
The user's preferred utility to display text files.
EDITOR/VISUAL
The user's preferred utility to edit text files.

Further names may be placed in the environment by the export command and `name=value' in sh(1), or by the setenv command if you use csh(1). Arguments may also be placed in the environment at the point of an exec(3). A C program can manipulate its environment using the functions getenv(3), putenv(3), setenv(3), and unsetenv(3).

Note that the behavior of many programs and library routines is influenced by the presence or value of certain environment variables. A random collection:

The variables LANG, LANGUAGE, NLSPATH, LOCPATH, LC_ALL, LC_MESSAGES, etc. influence locale handling, cf. locale(5).

TMPDIR influences the path prefix of names created by tmpnam(3) and other routines, the temporary directory used by sort(1) and other programs, etc.

LD_LIBRARY_PATH, LD_PRELOAD and other LD_* variables influence the behavior of the dynamic loader/linker.

POSIXLY_CORRECT makes certain programs and library routines follow the prescriptions of POSIX.

The behavior of malloc(3) is influenced by MALLOC_* variables.

The variable HOSTALIASES gives the name of a file containing aliases to be used with gethostbyname(3).

TZ and TZDIR

give time zone information used by
tzset(3)

and through that by functions like
ctime(3),

localtime(3),

mktime(3),

strftime(3).

See also
tzselect(8).

TERMCAP gives information on how to address a given terminal (or gives the name of a file containing such information).

COLUMNS and LINES tell applications about the window size, possibly overriding the actual size.

PRINTER or LPDEST may specify the desired printer to use. See lpr(1).

Etc.

BUGS

Clearly there is a security risk here. Many a system command has been tricked into mischief by a user who specified unusual values for IFS or LD_LIBRARY_PATH.

There is also the risk of name space pollution. Programs like make and autoconf allow overriding of default utility names from the environment with similarly named variables in all caps. Thus one uses CC to select the desired C compiler (and similarly MAKE, AR, AS, FC, LD, LEX, RM, YACC, etc.). However, in some traditional uses such an environment variable gives options for the program instead of a pathname. Thus, one has MORE, LESS, and GZIP. Such usage is considered mistaken, and to be avoided in new programs. The authors of gzip should consider renaming their option to GZIP_OPT.

SEE ALSO

bash(1), csh(1), login(1), sh(1), tcsh(1), execve(2), clearenv(3), exec(3), getenv(3), putenv(3), setenv(3), unsetenv(3), locale(5)


zdump(8)

ZDUMP

Section: Linux System Administration (8)
Updated: 2007-05-18 Return to Main Contents

NAME

zdump - time zone dumper

SYNOPSIS

zdump [ -v ] [ -c cutoffyear ] [ zonename ... ]

DESCRIPTION

Zdump prints the current time in each zonename named on the command line.

These options are available:

-v
For each zonename on the command line, print the time at the lowest possible time value, the time one day after the lowest possible time value, the times both one second before and exactly at each detected time discontinuity, the time at one day less than the highest possible time value, and the time at the highest possible time value. Each line ends with isdst=1 if the given time is Daylight Saving Time or isdst=0 otherwise.
-c cutoffyear
Cut off the verbose output near the start of the given year.

SEE ALSO

tzfile(5), zic(8)


intro(8)

INTRO

Section: Linux Programmer's Manual (8)
Updated: 1993-07-24 Return to Main Contents

NAME

intro - Introduction to administration and privileged commands

DESCRIPTION

This chapter describes commands which either can be or are only used by the superuser, like daemons and hardware-related commands.

Authors and Copyright Conditions

Look at the header of the manual page for the author(s) and copyright conditions. Note that these can be different from page to page!


zic(8)

ZIC

Section: Linux System Administration (8)
Updated: 2007-05-18 Return to Main Contents

NAME

zic - time zone compiler

SYNOPSIS

zic [ -v ] [ -d directory ] [ -l localtime ] [ -p posixrules ] [ -L leapsecondfilename ] [ -s ] [ -y command ] [ filename ... ]

DESCRIPTION

Zic reads text from the file(s) named on the command line and creates the time conversion information files specified in this input. If a filename is -, the standard input is read.

These options are available:

-d directory
Create time conversion information files in the named directory rather than in the standard directory named below.
-l timezone
Use the given time zone as local time. Zic will act as if the input contained a link line of the form

Link      timezone                localtime

-p timezone
Use the given time zone's rules when handling POSIX-format time zone environment variables. Zic will act as if the input contained a link line of the form

Link      timezone                posixrules

-L leapsecondfilename
Read leap second information from the file with the given name. If this option is not used, no leap second information appears in output files.
-v
Complain if a year that appears in a data file is outside the range of years representable by time(2) values.
-s
Limit time values stored in output files to values that are the same whether they're taken to be signed or unsigned. You can use this option to generate SVVS-compatible files.
-y command
Use the given command rather than yearistype when checking year types (see below).

Input lines are made up of fields. Fields are separated from one another by any number of white space characters. Leading and trailing white space on input lines is ignored. An unquoted sharp character (#) in the input introduces a comment which extends to the end of the line the sharp character appears on. White space characters and sharp characters may be enclosed in double quotes (") if they're to be used as part of a field. Any line that is blank (after comment stripping) is ignored. Non-blank lines are expected to be of one of three types: rule lines, zone lines, and link lines.

A rule line has the form

Rule  NAME  FROM  TO    TYPE  IN   ON       AT    SAVE  LETTER/S

For example:

Rule  US    1967  1973  -     Apr  lastSun  2:00  1:00  D
The fields that make up a rule line are:
NAME
Gives the (arbitrary) name of the set of rules this rule is part of.
FROM
Gives the first year in which the rule applies. Any integer year can be supplied; the Gregorian calendar is assumed. The word minimum (or an abbreviation) means the minimum year representable as an integer. The word maximum (or an abbreviation) means the maximum year representable as an integer. Rules can describe times that are not representable as time values, with the unrepresentable times ignored; this allows rules to be portable among hosts with differing time value types.
TO
Gives the final year in which the rule applies. In addition to minimum and maximum (as above), the word only (or an abbreviation) may be used to repeat the value of the FROM field.
TYPE
Gives the type of year in which the rule applies. If TYPE is - then the rule applies in all years between FROM and TO inclusive. If TYPE is something else, then zic executes the command
yearistype year type
to check the type of a year: an exit status of zero is taken to mean that the year is of the given type; an exit status of one is taken to mean that the year is not of the given type.
IN
Names the month in which the rule takes effect. Month names may be abbreviated.
ON
Gives the day on which the rule takes effect. Recognized forms include:

5        the fifth of the month
lastSun  the last Sunday in the month
lastMon  the last Monday in the month
Sun>=8   first Sunday on or after the eighth
Sun<=25  last Sunday on or before the 25th

Names of days of the week may be abbreviated or spelled out in full. Note that there must be no spaces within the ON field.

AT
Gives the time of day at which the rule takes effect. Recognized forms include:

2        time in hours
2:00     time in hours and minutes
15:00    24-hour format time (for times after noon)
1:28:14  time in hours, minutes, and seconds
-        equivalent to 0

where hour 0 is midnight at the start of the day, and hour 24 is midnight at the end of the day. Any of these forms may be followed by the letter w if the given time is local time, s if the given time is local time, or u (or g or z) if the given time is universal time; in the absence of an indicator, wall clock time is assumed.

SAVE
Gives the amount of time to be added to local standard time when the rule is in effect. This field has the same format as the AT field (although, of course, the w and s suffixes are not used).
LETTER/S
Gives the (for example, the or in or of time zone abbreviations to be used when this rule is in effect. If this field is -, the variable part is null.

A zone line has the form

Zone  NAME                GMTOFF  RULES/SAVE  FORMAT  [UNTIL]

For example:

     Zone                 Australia/Adelaide  9:30    AusCST1971 Oct 31 2:00
The fields that make up a zone line are:
NAME
The name of the time zone. This is the name used in creating the time conversion information file for the zone.
GMTOFF
The amount of time to add to UTC to get standard time in this zone. This field has the same format as the AT and SAVE fields of rule lines; begin the field with a minus sign if time must be subtracted from UTC.
RULES/SAVE
The name of the rule(s) that apply in the time zone or, alternately, an amount of time to add to local standard time. If this field is - then standard time always applies in the time zone.
FORMAT
The format for time zone abbreviations in this time zone. The pair of characters %s is used to show where the of the time zone abbreviation goes. Alternately, a slash (/) separates standard and daylight abbreviations.
UNTIL
The time at which the UTC offset or the rule(s) change for a location. It is specified as a year, a month, a day, and a time of day. If this is specified, the time zone information is generated from the given UTC offset and rule change until the time specified. The month, day, and time of day have the same format as the IN, ON, and AT columns of a rule; trailing columns can be omitted, and default to the earliest possible value for the missing columns.
The next line must be a line; this has the same form as a zone line except that the string and the name are omitted, as the continuation line will place information starting at the time specified as the UNTIL field in the previous line in the file used by the previous line. Continuation lines may contain an UNTIL field, just as zone lines do, indicating that the next line is a further continuation.

A link line has the form

Link  LINK-FROM        LINK-TO

For example:

     Link              Europe/IstanbulAsia/Istanbul
The LINK-FROM field should appear as the NAME field in some zone line; the LINK-TO field is used as an alternate name for that zone.

Except for continuation lines, lines may appear in any order in the input.

Lines in the file that describes leap seconds have the following form:

Leap  YEAR  MONTH  DAY  HH:MM:SS  CORR  R/S

For example:

Leap  1974  Dec    31   23:59:60  +     S
The YEAR, MONTH, DAY, and HH:MM:SS fields tell when the leap second happened. The CORR field should be if a second was added or if a second was skipped. The R/S field should be (an abbreviation of) if the leap second time given by the other fields should be interpreted as UTC or (an abbreviation of) if the leap second time given by the other fields should be interpreted as local wall clock time.

FILES

/usr/local/etc/zoneinfo          standard directory used for created files

NOTES

For areas with more than two types of local time, you may need to use local standard time in the AT field of the earliest transition time's rule to ensure that the earliest transition time recorded in the compiled file is correct.

SEE ALSO

tzfile(5), zdump(8)


ld.so(8)

LD.SO

Section: Linux Programmer's Manual (8)
Updated: 2007-05-31 Return to Main Contents

NAME

ld.so, ld-linux.so* - dynamic linker/loader

SYNOPSIS

The dynamic linker can be run either indirectly through running some dynamically linked program or library (in which case no command line options to the dynamic linker can be passed and, in the ELF case, the dynamic linker which is stored in the .interp section of the program is executed) or directly by running: /lib/ld-linux.so.* [OPTIONS] [PROGRAM [ARGUMENTS]]

DESCRIPTION

The programs ld.so and ld-linux.so* find and load the shared libraries needed by a program, prepare the program to run, and then run it.

Linux binaries require dynamic linking (linking at run time) unless the -static option was given to ld during compilation.

The program ld.so handles a.out binaries, a format used long ago; ld-linux.so* handles ELF (/lib/ld-linux.so.1 for libc5, /lib/ld-linux.so.2 for glibc2), which everybody has been using for years now. Otherwise both have the same behavior, and use the same support files and programs ldd(1), ldconfig(8) and /etc/ld.so.conf.

The shared libraries needed by the program are searched for in various places:

o
(ELF only) Using the DT_RPATH dynamic section attribute of the binary if present and DT_RUNPATH attribute does not exist. Use of DT_RPATH is deprecated.
o
Using the environment variable LD_LIBRARY_PATH. Except if the executable is a set-user-ID/set-group-ID binary, in which case it is ignored.
o
(ELF only) Using the DT_RUNPATH dynamic section attribute of the binary if present.
o
From the cache file /etc/ld.so.cache which contains a compiled list of candidate libraries previously found in the augmented library path. If, however, the binary was linked with -z nodeflib linker option, libraries in the default library paths are skipped.
o
In the default path /lib, and then /usr/lib. If the binary was linked with -z nodeflib linker option, this step is skipped.

$ORIGIN and rpath

ld.so understands the string $ORIGIN (or equivalently ${ORIGIN}) in an rpath specification (DT_RPATH or DT_RUNPATH) to mean the directory containing the application executable. Thus, an application located in somedir/app could be compiled with gcc -Wl,-rpath,'$ORIGIN/../lib' so that it finds an associated shared library in somedir/lib no matter where somedir is located in the directory hierarchy. This facilitates the creation of "turn-key" applications that do not need to be installed into special directories, but can instead be unpacked into any directory and still find their own shared libraries.

OPTIONS

--list
List all dependencies and how they are resolved.
--verify
Verify that program is dynamically linked and this dynamic linker can handle it.
--library-path PATH
Override LD_LIBRARY_PATH environment variable setting (see below).
--inhibit-rpath LIST
Ignore RPATH and RUNPATH information in object names in LIST.

ENVIRONMENT

There are four important environment variables.
LD_LIBRARY_PATH
A colon-separated list of directories in which to search for ELF libraries at execution-time. Similar to the PATH environment variable.
LD_PRELOAD
A whitespace-separated list of additional, user-specified, ELF shared libraries to be loaded before all others. This can be used to selectively override functions in other shared libraries. For set-user-ID/set-group-ID ELF binaries, only libraries in the standard search directories that are also set-user-ID will be loaded.
LD_BIND_NOW
(libc5; glibc since 2.1.1) If set to non-empty string, causes the dynamic linker to resolve all symbols at program startup instead of deferring function call resolval to the point when they are first referenced. This is useful when using a debugger.
LD_TRACE_LOADED_OBJECTS
(ELF only) If set to non-empty string, causes the program to list its dynamic library dependencies, as if run by ldd(1), instead of running normally.

Then there are lots of more or less obscure variables, many obsolete or only for internal use.

LD_WARN
(ELF only)(glibc since 2.1.3) If set to non-empty string, warn about unresolved symbols.
LD_NOWARN
(a.out only)(libc5) Suppress warnings about a.out libraries with incompatible minor version numbers.
LD_BIND_NOT
(glibc since 2.1.95) Do not update the GOT (global offset table) and PLT (procedure linkage table) after resolving a symbol.
LD_DEBUG
(glibc since 2.1) Output verbose debugging information about the dynamic linker. If set to all prints all debugging information it has, if set to help prints a help message about which categories can be specified in this environment variable.
LD_DEBUG_OUTPUT
(glibc since 2.1) File where LD_DEBUG output should be fed into, default is standard output. LD_DEBUG_OUTPUT is ignored for set-user-ID/set-group-ID binaries.
LD_VERBOSE
(glibc since 2.1) If set to non-empty string, output symbol versioning information about the program if querying information about the program (ie. either LD_TRACE_LOADED_OBJECTS has been set, or --list or --verify options have been given to the dynamic linker).
LD_PROFILE
(glibc since 2.1) Shared object to be profiled.
LD_PROFILE_OUTPUT
(glibc since 2.1) File where LD_PROFILE output should be stored, default is standard output. LD_PROFILE_OUTPUT is ignored for set-user-ID/set-group-ID binaries.
LD_AOUT_LIBRARY_PATH
(libc5) Version of LD_LIBRARY_PATH for a.out binaries only. Old versions of ld-linux.so.1 also supported LD_ELF_LIBRARY_PATH.
LD_AOUT_PRELOAD
(libc5) Version of LD_PRELOAD for a.out binaries only. Old versions of ld-linux.so.1 also supported LD_ELF_PRELOAD.
LD_SHOW_AUXV
(glibc since 2.1) Show auxiliary array passed up from the kernel.
LD_HWCAP_MASK
(glibc since 2.1) Mask for hardware capabilities.
LD_ORIGIN_PATH
(glibc since 2.1) Path where the binary is found (for non-set-user-ID programs).
LD_DYNAMIC_WEAK
(glibc since 2.1.91) Allow weak symbols to be overridden (reverting to old glibc behavior).
LD_KEEPDIR
(a.out only)(libc5) Don't ignore the directory in the names of a.out libraries to be loaded. Use of this option is strongly discouraged.
LDD_ARGV0
(libc5) argv[0] to be used by ldd(1) when none is present.

FILES

/lib/ld.so
a.out dynamic linker/loader
/lib/ld-linux.so.{1,2}
ELF dynamic linker/loader
/etc/ld.so.cache
File containing a compiled list of directories in which to search for libraries and an ordered list of candidate libraries.
/etc/ld.so.preload
File containing a whitespace separated list of ELF shared libraries to be loaded before the program.
lib*.so*
shared libraries

NOTES

The ld.so functionality is available for executables compiled using libc version 4.4.3 or greater. ELF functionality is available since Linux 1.1.52 and libc5.

SEE ALSO

ldd(1), ldconfig(8)


tzselect(8)

TZSELECT

Section: Linux System Administration (8)
Updated: 2007-05-18 Return to Main Contents

NAME

tzselect - select a time zone

SYNOPSIS

tzselect

DESCRIPTION

The tzselect program asks the user for information about the current location, and outputs the resulting time zone description to standard output. The output is suitable as a value for the TZ environment variable.

All interaction with the user is done via standard input and standard error.

EXIT STATUS

The exit status is zero if a time zone was successfully obtained from the user, non-zero otherwise.

ENVIRONMENT

AWK
Name of a Posix-compliant awk program (default: awk).
TZDIR
Name of the directory containing time zone data files (default: /usr/share/zoneinfo).

FILES

TZDIR/iso3166.tab
Table of ISO 3166 2-letter country codes and country names.
TZDIR/zone.tab
Table of country codes, latitude and longitude, TZ values, and descriptive comments.
TZDIR/TZ
Time zone data file for time zone TZ.

SEE ALSO

tzfile(5), zdump(8), zic(8)


sync(8)

SYNC

Section: Linux Programmer's Manual (8)
Updated: 1998-11-01 Return to Main Contents

NAME

sync - synchronize data on disk with memory

SYNOPSIS

sync [--help] [--version]

DESCRIPTION

sync writes any data buffered in memory out to disk. This can include (but is not limited to) modified superblocks, modified inodes, and delayed reads and writes. This must be implemented by the kernel; The sync program does nothing but exercise the sync(2) system call.

The kernel keeps data in memory to avoid doing (relatively slow) disk reads and writes. This improves performance, but if the computer crashes, data may be lost or the filesystem corrupted as a result. sync ensures that everything in memory is written to disk.

sync should be called before the processor is halted in an unusual manner (e.g., before causing a kernel panic when debugging new kernel code). In general, the processor should be halted using the shutdown(8) or reboot(8) or halt(8) commands, which will attempt to put the system in a quiescent state before calling sync(2). (Various implementations of these commands exist; consult your documentation; on some systems one should not call reboot(8) and halt(8) directly.)

OPTIONS

--help
Print a usage message on standard output and exit successfully.
--version
Print version information on standard output, then exit successfully.
--
Terminate option list.

ENVIRONMENT

The variables LANG, LC_ALL, LC_CTYPE, and LC_MESSAGES have the usual meaning.

CONFORMING TO

POSIX.2

NOTES

On Linux, sync is only guaranteed to schedule the dirty blocks for writing; it can actually take a short time before all the blocks are finally written. The reboot(8) and halt(8) commands take this into account by sleeping for a few seconds after calling sync(2).

This page describes sync as found in the fileutils-4.0 package; other versions may differ slightly.

SEE ALSO

sync(2), halt(8), reboot(8), update(8)


ldconfig(8)

LDCONFIG

Section: Linux Programmer's Manual (8)
Updated: 2002-05-06 Return to Main Contents

NAME

/sbin/ldconfig - configure dynamic linker run time bindings

SYNOPSIS

/sbin/ldconfig [ -nNvXV ] [ -f conf ] [ -C cache ] [ -r root ] directory ...

/sbin/ldconfig -l [ -v ] library ...

/sbin/ldconfig -p

DESCRIPTION

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib). The cache is used by the run-time linker, ld.so or ld-linux.so. ldconfig checks the header and filenames of the libraries it encounters when determining which versions should have their links updated.

ldconfig will attempt to deduce the type of ELF libs (ie. libc5 or libc6/glibc) based on what C libs, if any, the library was linked against.

Some existing libs do not contain enough information to allow the deduction of their type. Therefore, the /etc/ld.so.conf file format allows the specification of an expected type. This is only used for those ELF libs which we can not work out. The format is "dirname=TYPE", where TYPE can be libc4, libc5, or libc6. (This syntax also works on the command line.) Spaces are not allowed. Also see the -p option. ldconfig should normally be run by the superuser as it may require write permission on some root owned directories and files.

OPTIONS

-v
Verbose mode. Print current version number, the name of each directory as it is scanned, and any links that are created. Overrides quiet mode.
-n
Only process directories specified on the command line. Don't process the trusted directories (/lib and /usr/lib) nor those specified in /etc/ld.so.conf. Implies -N.
-N
Don't rebuild the cache. Unless -X is also specified, links are still updated.
-X
Don't update links. Unless -N is also specified, the cache is still rebuilt.
-f conf
Use conf instead of /etc/ld.so.conf.
-C cache
Use cache instead of /etc/ld.so.cache.
-r root
Change to and use root as the root directory.
-l
Library mode. Manually link individual libraries. Intended for use by experts only.
-p
Print the lists of directories and candidate libraries stored in the current cache.

FILES

/lib/ld.so
run-time linker/loader
/etc/ld.so.conf
File containing a list of colon, space, tab, newline, or comma-separated directories in which to search for libraries.
/etc/ld.so.cache
File containing an ordered list of libraries found in the directories specified in /etc/ld.so.conf.


nscd(8)

NSCD

Section: Linux Programmer's Manual (8)
Updated: 1999-10-01 Return to Main Contents

NAME

/usr/sbin/nscd - name service cache daemon

DESCRIPTION

Nscd is a daemon that provides a cache for the most common name service requests. The default configuration file, /etc/nscd.conf, determines the behavior of the cache daemon. See nscd.conf(5).

Nscd provides caching for accesses of the
passwd(5),

group(5),

and
hosts(5)

databases through standard libc interfaces, such as
getpwnam(3),

getpwuid(3),

getgrnam(3),

getgrgid(3),

gethostbyname(3),

and others.

There are two caches for each database: a positive one for items found, and a negative one for items not found. Each cache has a separate TTL (time-to-live) period for its data. Note that the shadow file is specifically not cached. getspnam(3) calls remain uncached as a result.

OPTIONS

--help
will give you a list with all options and what they do.

NOTES

Nscd doesn't know anything about the underlying protocols for a service. This also means, that if you change /etc/resolv.conf for DNS queries, nscd will continue to use the old one if you have configured /etc/nsswitch.conf to use DNS for host lookups. In such a case, you need to restart nscd.

SEE ALSO

nscd.conf(5), nsswitch.conf(5)


ld-linux(8)

Status: 403 Forbidden ld-linux(8)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man8/ld-linux.8 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


ld-linux.so(8)

Status: 403 Forbidden ld-linux.so(8)

Invalid Man Page

The requested file /home/daniel/public_html/chm/man-pages/man8/ld-linux.so.8 is not a valid (unformatted) man page. If the file is a formatted man page, you could try to load the plain file.


ksoftirqd(9)

KSOFTIRQD

Section: Linux Programmer's Manual (9)
Updated: 2003-08-24 Return to Main Contents

NAME

ksoftirqd - Softirq daemon

DESCRIPTION

ksoftirqd is a per-cpu kernel thread that runs when the machine is under heavy soft-interrupt load. Soft interrupts are normally serviced on return from a hard interrupt, but it's possible for soft interrupts to be triggered more quickly than they can be serviced. If a soft interrupt is triggered for a second time while soft interrupts are being handled, the ksoftirq daemon is triggered to handle the soft interrupts in process context. If ksoftirqd is taking more than a tiny percentage of CPU time, this indicates the machine is under heavy soft interrupt load.

HISTORY

ksoftirqd was introduced during the 2.3 development series as part of the softnet work by Alexey Kuznetsov and David Miller.


 This package contains the Linux man pages for all chapters except 1, 6 and 8. Some more information is given in the `Announce' file.

Install by copying to your favourite location. "make install" will just copy them to /usr/share/man/man[1-8]. "make" will move the pages from this package that are older than the already installed ones to a subdirectory `not_installed', then remove old versions (compressed or not), compress the pages, and copy them to /usr/share/man/man[1-8].

Note that you may have to remove preformatted pages.

Note that sometimes these pages are duplicates of pages also distributed in other packages. This has been reported about dlclose.3, dlerror.3, dlopen.3, dlsym.3 (found in ld.so), about resolver.3, resolv.conf.5 (found in bind-utils), and about passwd.5, and mailaddr.7. Be careful not to overwrite more up-to-date versions.
Reports on further duplicates are welcome.
Formerly present and now removed duplicates:
*_module.2, get_kernel_syms.2 (found in modutils-2.1.*),
exports.5 (found in nfs-server-2.2*),
fstab.5, nfs.5 (found in util-linux-2.12*),
lilo.8, lilo.conf.5 (found in lilo-21.6*).

Note that the pages that come with GNU fileutils are really help texts (indeed, are generated automatically from help texts), and worse than worthless. Without them people would have good detailed man pages, such as those found here in man1.
As it is, many distributions install these "man pages", to the detriment of their users.

Copyrights: These man pages come under various copyrights.
For the POSIX pages, see the file POSIX-COPYRIGHT. All other pages are freely distributable when the nroff source is included.

Send corrections and additions to mtk-manpages@gmx.net
(man.7 has some info on the macros to use).


The Institute of Electrical and Electronics Engineers (IEEE) and
The Open Group, have given us permission to reprint portions of
their documentation.

In the following statement, the phrase ``this text'' refers to
portions of the system documentation.

Portions of this text are reprinted and reproduced in electronic form
in the linux-manpages package, from IEEE Std 1003.1 (TM), 2003 Edition,
Standard for Information Technology -- Portable Operating System
Interface (POSIX (R)), The Open Group Base Specifications Issue 6,
Copyright (C) 2001-2003 by the Institute of Electrical and Electronics
Engineers, Inc and The Open Group.  In the event of any discrepancy
between these versions and the original IEEE and The Open Group
Standard, the original IEEE and The Open Group Standard is the referee
document.  The original Standard can be obtained online at
http://www.opengroup.org/unix/online.html .

This notice shall appear on any product containing this material.

Redistribution of this material is permitted so long as this notice and
the corresponding notices within each POSIX manual page are retained on
any distribution, and the nroff source is included.  Modifications to
the text are permitted so long as any conflicts with the standard
are clearly marked as such in the text.