Your program should include the header file errno. Most library functions return a special value to indicate that they have failed. The special value is typically -1 , a null pointer, or a constant such as EOF that is defined for that purpose.
But this return value tells you only that an error has occurred. To find out what kind of error it was, you need to look at the error code stored in the variable errno. This variable is declared in the header file errno. The variable errno contains the system error number. You can change the value of errno. Since errno is declared volatile , it might be changed asynchronously by a signal handler; see Defining Handlers.
However, a properly written signal handler saves and restores the value of errno , so you generally do not need to worry about this possibility except when writing signal handlers. The initial value of errno at program startup is zero. In many cases, when a library function encounters an error, it will set errno to a non-zero value to indicate what specific error condition occurred. The documentation for each function lists the error conditions that are possible for that function.
Not all library functions use this mechanism; some return an error code directly, instead. Warning: Many library functions may set errno to some meaningless non-zero value even if they did not encounter any errors, and even if they return error codes directly. Therefore, it is usually incorrect to check whether an error occurred by inspecting the value of errno. The proper way to check for error is documented for each function. There are a few library functions, like sqrt and atan , that return a perfectly legitimate value in case of an error, but also set errno.
For these functions, if you want to check to see whether an error occurred, the recommended method is to set errno to zero before calling the function, and then check its value afterward.
All the error codes have symbolic names; they are macros defined in errno. See Reserved Names. Your program should not make any other assumptions about the specific values of these symbolic constants. The only values that are guaranteed to be meaningful for a particular library function are the ones that this manual lists for that function. In some Unix systems, many system calls can also return EFAULT if given as an argument a pointer into the stack, and the kernel for some obscure reason fails in its attempt to extend the stack.
If this ever happens, you should probably try using statically or dynamically allocated memory instead of stack memory on that system. The error code macros are defined in the header file errno. All of them expand into integer constant values. When this happens, you should try the call again. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.
This condition is detected by the exec functions; see Executing a File. The system does not guarantee that it will notice all such situations.
This error means you got lucky and the system noticed; it might just hang. See File Locks , for an example. For example, trying to mount an ordinary file as a file system in Unix gives this error. For example, if you try to delete a file that is the root of a currently mounted filesystem, you get this error.
This happens not only when you use link see Hard Links but also when you rename a file with rename see Renaming Files. Duplicate descriptors do count toward this limit.
Note that any number of linked channels count as just one file opening; see Linked Channels. Often using a debugger to run a program is considered having it open for writing and will cause this error.
Every library function that returns this error code also generates a SIGPIPE signal; this signal terminates the program if not handled or blocked.
To make your program portable, you should check for both codes and treat them the same. The values are always the same, on every operating system. See Socket Options. See Creating a Socket. See Sockets. See Socket Addresses. See Connecting. You get this error when you try to transmit data over a socket, without first specifying a destination for the data.
You get this error when you try to transmit data over a connectionless socket, without first specifying a destination for the data with connect. This often indicates a cycle of symbolic links. Typically, this error occurs when you are trying to delete a directory. Repairing this condition usually requires unmounting, possibly repairing and remounting the file system. On some systems chmod returns this error if you try to set the sticky bit on a non-directory file; see Setting Permissions.
When you get this error, you can be sure that this particular function will always fail with ENOSYS unless you install a new version of the C library or the operating system.
This can mean that the function does not implement a particular command or option value or flag bit at all. For functions that operate on some object given in a parameter, such as a file descriptor or a port, it might instead mean that only that specific object file descriptor, port, etc. See Job Control , for information on process groups and these signals. They are not yet documented. The library has functions and variables designed to make it easy for your program to report informative error messages in the customary format about the failure of a library call.
The strerror function maps the error code see Checking for Errors specified by the errnum argument to a descriptive error message string. The return value is a pointer to this string. You should not modify the string returned by strerror. Also, if you make subsequent calls to strerror , the string might be overwritten.
This might be either some permanent global data or a message string in the user supplied buffer starting at buf with the length of n bytes. At most n characters are written including the NUL byte so it is up to the user to select a buffer large enough. This function should always be used in multi-threaded programs since there is no way to guarantee the string returned by strerror really belongs to the last call of the current thread.
This function prints an error message to the stream stderr ; see Standard Streams. The orientation of stderr is not changed. If you call perror with a message that is either a null pointer or an empty string, perror just prints the error message corresponding to errno , adding a trailing newline.
If you supply a non-null message argument, then perror prefixes its output with this string. It adds a colon and a space character to separate the message from the error string corresponding to errno. This function returns the name describing the error errnum or NULL if there is no known constant with this value e. This function returns the message describing the error errnum or NULL if there is no known constant with this value e.
Different than strerror the returned description is not translated. With the GNU C Library, the messages are fairly short; there are no multi-line messages or embedded newlines. Each error message begins with a capital letter and does not include any terminating punctuation.
It is the same as argv[0]. Note that this is not necessarily a useful file name; often it contains no directory names. See Program Arguments. The library initialization code sets up both of these variables before calling main. Portability Note: If you want your program to work with non-GNU libraries, you must save the value of argv[0] in main , and then strip off the directory names yourself.
We added these extensions to make it possible to write self-contained error-reporting subroutines that require no explicit cooperation from main. Here is an example showing how to handle failure to open a file correctly. Using perror has the advantage that the function is portable and available on all systems implementing ISO C. But often the text perror generates is not what is wanted and there is no way to extend or change what perror does. The GNU coding standard, for instance, requires error messages to be preceded by the program name and programs which read some input files should provide information about the input file name and the line number in case an error is encountered while reading the file.
For these occasions there are two functions available which are widely used throughout the GNU project. These functions are declared in error.
The error function can be used to report general problems during program execution. The format argument is a format string just like those given to the printf family of functions. The arguments required for the format can follow the format parameter. Just like perror , error also can report an error code in textual form. But unlike perror the error value is explicitly passed to the function in the errnum parameter.
This eliminates the problem mentioned above that the error reporting function must be called immediately after the function causing the error since otherwise errno might have a different value. The program name is followed by a colon and a space which in turn is followed by the output produced by the format string.
If the errnum parameter is non-zero the format string output is followed by a colon and a space, followed by the error message for the error code errnum. In any case is the output terminated with a newline. The output is directed to the stderr stream. The function will return unless the status parameter has a non-zero value. In this case the function will call exit with the status value for its parameter and therefore never return.
The only differences are the additional parameters fname and lineno. The handling of the other parameters is identical to that of error except that between the program name and the string generated by the format string additional text is inserted. Directly following the program name a colon, followed by the file name pointed to by fname , another colon, and the value of lineno is printed.
This additional output of course is meant to be used to locate an error in an input file like a programming language source code file etc. Repetition which are not directly following each other are not caught. Just like error this function only returns if status is zero. Otherwise exit is called with the non-zero value.
It is expected to print the program name or do something similarly useful. The function is expected to print to the stderr stream and must be able to handle whatever orientation the stream has.
The variable is global and shared by all threads. This variable is global and shared by all threads. These functions are declared in err. It is generally advised to not use these functions.
They are included only for compatibility. The difference to warn is that no error number string is printed. The difference to err is that no error number string is printed.
They vary in generality and in efficiency. The library also provides functions for controlling paging and allocation of real memory. One of the most basic resources a process has available to it is memory. There are a lot of different ways systems organize memory, but in a typical one, each process has one linear virtual address space, with addresses running from zero to some huge maximum.
It need not be contiguous; i. The virtual memory is divided into pages 4 kilobytes is typical. Backing each page of virtual memory is a page of real memory called a frame or some secondary storage, usually disk space. The disk space might be swap space or just some ordinary disk file. The same frame of real memory or backing store can back multiple virtual pages belonging to multiple processes. The same real memory frame containing the printf function backs a virtual memory page in each of the existing processes that has a printf call in its program.
But because there is usually a lot more virtual memory than real memory, the pages must move back and forth between real memory and backing store regularly, coming into real memory when a process needs to access them and then retreating to backing store when not needed anymore. This movement is called paging. When a program attempts to access a page which is not at that moment backed by real memory, this is known as a page fault.
In fact, to the process, all pages always seem to be in real memory. For programs sensitive to that, the functions described in Locking Pages can control it. Within each virtual address space, a process has to keep track of what is at which addresses, and that process is called memory allocation. Processes allocate memory in two major ways: by exec and programmatically. See Creating a Process. Exec is the operation of creating a virtual address space for a process, loading its basic program into it, and executing the program.
The operation takes a program file an executable , it allocates space to load all the data in the executable, loads it, and transfers control to it. That data is most notably the instructions of the program the text , but also literals and constants in the program and even some variables: C variables with the static storage class see Memory Allocation and C. Once that program begins to execute, it uses programmatic allocation to gain additional memory.
See Memory Allocation and C. The system makes the virtual memory initially contain the contents of the file, and if you modify the memory, the system writes the same modification to the file. Just as it programmatically allocates memory, the program can programmatically deallocate free it. When the program exits or execs, you might say that all its memory gets freed, but since in both cases the address space ceases to exist, the point is really moot.
See Program Termination. A segment is a contiguous range of virtual addresses. Three important segments are:. This section covers how ordinary programs manage storage for their data, including the famous malloc function and some fancier facilities special to the GNU C Library and GNU Compiler.
In GNU C, the size of the automatic storage can be an expression that varies. In other C implementations, it must be a constant. A third important kind of memory allocation, dynamic allocation , is not supported by C variables but is available via GNU C Library functions. Dynamic memory allocation is a technique in which programs determine as they are running where to store some information. You need dynamic allocation when the amount of memory you need, or how long you continue to need it, depends on factors that are not known before the program runs.
For example, you may need a block to store a line read from an input file; since there is no limit to how long a line can be, you must allocate the memory dynamically and make it dynamically larger as you read more of the line. When you use dynamic allocation, the allocation of a block of memory is an action that the program requests explicitly. You call a function or macro when you want to allocate space, and specify the size with an argument. If you want to free the space, you do so by calling another function or macro.
You can do these things whenever you want, as often as you want. The only way to get dynamically allocated memory is via a system call which is generally via a GNU C Library function call , and the only way to refer to dynamically allocated space is through a pointer.
Because it is less convenient, and because the actual process of dynamic allocation requires more computation time, programmers generally use dynamic allocation only when neither static nor automatic allocation will serve. For example, if you want to allocate dynamically some space to hold a struct foobar , you cannot declare a variable of type struct foobar whose contents are the dynamically allocated space.
The malloc implementation in the GNU C Library is derived from ptmalloc pthreads malloc , which in turn is derived from dlmalloc Doug Lea malloc. This malloc may allocate memory in two different ways depending on their size and certain parameters that may be controlled by users. The most common way is to allocate portions of memory called chunks from a large contiguous area of memory and manage these areas to optimize their use and reduce wastage in the form of unusable chunks.
Traditionally the system heap was set up to be the one large memory area but the GNU C Library malloc implementation maintains multiple such areas to optimize their use in multi-threaded applications.
Each such area is internally referred to as an arena. As opposed to other versions, the malloc in the GNU C Library does not round up chunk sizes to powers of two, neither for large nor for small sizes. Neighboring chunks can be coalesced on a free no matter what their size is. This makes the implementation suitable for all kinds of allocation patterns without generally incurring high memory waste through fragmentation.
The presence of multiple arenas allows multiple threads to allocate memory simultaneously in separate arenas, thus improving performance. The other way of memory allocation is for very large blocks, i.
This has the great advantage that these chunks are returned to the system immediately when they are freed. The size threshold for mmap to be used is dynamic and gets adjusted according to allocation patterns of the program.
It is possible to use your own custom malloc instead of the built-in allocator provided by the GNU C Library. See Replacing malloc. The most general dynamic allocation facility is malloc. It allows you to allocate blocks of memory of any size at any time, make them bigger or smaller at any time, and free the blocks individually at any time or never.
To allocate a block of memory, call malloc. The prototype for this function is in stdlib. This function returns a pointer to a newly allocated block size bytes long, or a null pointer setting errno if the block could not be allocated. The contents of the block are undefined; you must initialize it yourself or use calloc instead; see Allocating Cleared Space.
Normally you would convert the value to a pointer to the kind of object that you want to store in the block. Here we show an example of doing so, and of initializing the space with zeros using the library function memset see Copying Strings and Arrays :. However, a cast is necessary if the type is needed but not specified by context.
Remember that when allocating space for a string, the argument to malloc must be one plus the length of the string. For example:. See Representation of Strings , for more information about this. If no more space is available, malloc returns a null pointer. You should check the value of every call to malloc. It is useful to write a subroutine that calls malloc and reports an error if the value is a null pointer, returning only if the value is nonzero.
This function is conventionally called xmalloc. Here it is:. Here is a real example of using malloc by way of xmalloc. The function savestring will copy a sequence of characters into a newly allocated null-terminated string:. The block that malloc gives you is guaranteed to be aligned so that it can hold any type of data. On GNU systems, the address is always a multiple of eight on bit systems, and a multiple of 16 on bit systems.
Note that the memory located after the end of the block is likely to be in use for something else; perhaps a block already allocated by another call to malloc. If you attempt to treat the block as longer than you asked for it to be, you are liable to destroy the data that malloc uses to keep track of its blocks, or you may destroy the contents of another block.
If you have already allocated a block and discover you want it to be bigger, use realloc see Changing Block Size. When you no longer need a block that you got with malloc , use the function free to make the block available to be allocated again.
Freeing a block alters the contents of the block. Do not expect to find any data such as a pointer to the next block in a chain of blocks in the block after freeing it. Copy whatever you need out of the block before freeing it! Here is an example of the proper way to free all the blocks in a chain, and the strings that they point to:. Occasionally, free can actually return memory to the operating system and make the process smaller.
Usually, all it can do is allow a later call to malloc to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by malloc. The free function preserves the value of errno , so that cleanup code need not worry about saving and restoring errno around a call to free. Often you do not know for certain how big a block you will ultimately need at the time you must begin to use the block.
For example, the block might be a buffer that you use to hold a line being read from a file; no matter how long you make the buffer initially, you may encounter a line that is longer. You can make the block longer by calling realloc or reallocarray. These functions are declared in stdlib. The realloc function changes the size of the block whose address is ptr to be newsize. Since the space after the end of the block may be in use, realloc may find it necessary to copy the block to a new address where more free space is available.
The value of realloc is the new address of the block. If the block needs to be moved, realloc copies the old contents. Otherwise, if newsize is zero realloc frees the block and returns NULL.
Otherwise, if realloc cannot reallocate the requested size it returns NULL and sets errno ; the original block is left undisturbed. The reallocarray function changes the size of the block whose address is ptr to be long enough to contain a vector of nmemb elements, each of size size. Portability Note: This function is not part of any standard. It was first introduced in OpenBSD 5. Like malloc , realloc and reallocarray may return a null pointer if no memory space is available to make the block bigger.
When this happens, the original block is untouched; it has not been modified or relocated. In most cases it makes no difference what happens to the original block when realloc fails, because the application program cannot continue when it is out of memory, and the only thing to do is to give a fatal error message.
Often it is convenient to write and use subroutines, conventionally called xrealloc and xreallocarray , that take care of the error message as xmalloc does for malloc :.
You can also use realloc or reallocarray to make a block smaller. The reason you would do this is to avoid tying up a lot of memory space when only a little is needed. In several allocation implementations, making a block smaller sometimes necessitates copying it, so it can fail if no other space is available. The function calloc allocates memory and clears it to zero.
It is declared in stdlib. This function allocates a block long enough to contain a vector of count elements, each of size eltsize. Its contents are cleared to zero before calloc returns. But in general, it is not guaranteed that calloc calls reallocarray and memset internally.
For example, if the calloc implementation knows for other reasons that the new memory block is zero, it need not zero out the block again with memset. Also, if an application provides its own reallocarray outside the C library, calloc might not use that redefinition. The address of a block returned by malloc or realloc in GNU systems is always a multiple of eight or sixteen on bit systems. The alignment must be a power of two and size must be a multiple of alignment.
The memalign function allocates a block of size bytes whose address is a multiple of boundary. The boundary must be a power of two! The function memalign works by allocating a somewhat larger block, and then returning an address within the block that is on the specified boundary.
The memalign function returns a null pointer on error and sets errno to one of the following values:. Asked 9 years, 9 months ago. Active 9 years, 9 months ago. Viewed times. Improve this question. Each header usually have a copyright notice inside. Use gcc -H to understand which header files are used.
Add a comment. Active Oldest Votes. In addition, some individual header files reserve names beyond those that they actually define. You only need to worry about these restrictions if your program includes that particular header file. The exact set of features available when you compile a source file is controlled by which feature test macros you define. These directives must come before any include of a system header file.
It is best to make them the very first thing in the file, preceded only by comments. This system exists to allow the library to conform to multiple standards. Although the different standards are often described as supersets of each other, they are usually incompatible because larger standards require functions with names that smaller ones reserve to the user program. This is not mere pedantry -- it has been a problem in practice. For instance, some non-GNU programs define functions named getline that have nothing to do with this library's getline.
They would not be compilable if all features were enabled indiscriminately. This should not be used to verify that a program conforms to a limited standard. It is insufficient for this purpose, as it will not protect you from including header files outside the standard, or relying on semantics undefined within the standard.
The greater the value of this macro, the more functionality is made available. If you define this macro to a value greater than or equal to 1 , then the functionality from the edition of the POSIX. If you define this macro to a value greater than or equal to 2 , then the functionality from the edition of the POSIX.
If you define this macro to a value greater than or equal to L , then the functionality from the edition of the POSIX. Some of the features derived from 4. If this macro is defined, the 4. Due to the nature of some of the conflicts between 4. This is because some functions must be defined in two different ways, one of them in the normal C library, and one of them in the compatibility library. Specifically, the functions fseeko and ftello are available. This interface is not available if the system does not support files that large.
On systems where the natural file size limit is greater than 2GB i. The new functionality is made available by a new set of types and functions which replace the existing ones. The names of these new objects contain 64 to indicate the intention, e. If the macro is defined to the value 64 , the large file interface replaces the old interface.
The values are integer constants. Each file has three time stamps associated with it: its access time, its modification time, and its attribute modification time. For more information about representation and manipulation of time values, see section Calendar Time. Reading from a file updates its access time attribute, and writing updates its modification time.
When a file is created, all three time stamps for that file are set to the current time. In addition, the attribute change time and modification time fields of the directory that contains the new entry are updated. Adding a new name for a file with the link function updates the attribute change time field of the file being linked, and both the attribute change time and modification time fields of the directory containing the new name.
These same fields are affected if a file name is deleted with unlink , remove or rmdir. Renaming a file with rename affects only the attribute change time and modification time fields of the two parent directories involved, and not the times for the file being renamed.
Changing the attributes of a file for example, with chmod updates its attribute change time field. You can also change some of the time stamps of a file explicitly using the utime function--all except the attribute change time. Data Type: struct utimbuf The utimbuf structure is used with the utime function to specify new access and modification times for a file. It contains the following members:. If times is a null pointer, then the access and modification times of the file are set to the current time.
Otherwise, they are set to the values from the actime and modtime members respectively of the utimbuf structure pointed to by times. The attribute modification time for the file is set to the current time in either case since changing the time stamps is itself a modification of the file attributes.
The utime function returns 0 if successful and -1 on failure. Each of the three time stamps has a corresponding microsecond part, which extends its resolution. The utimes function is like utime , but also lets you specify the fractional part of the file times. The new file access time is specified by tvp [0] , and the new modification time by tvp [1]. This function comes from BSD. The return values and error conditions are the same as for the utime function.
Normally file sizes are maintained automatically. It is also possible to empty a file completely by an open or fopen call. However, sometimes it is necessary to reduce the size of a file.
This can be done with the truncate and ftruncate functions. They were introduced in BSD Unix. Some systems allow you to extend a file creating holes with these functions.
However, it is not portable but must be implemented if mmap allows mapping of files i. Using these functions on anything other than a regular file gives undefined results. On many systems, such a call will appear to succeed, without actually accomplishing anything. The truncate function changes the size of filename to length. If length is shorter than the previous length, data at the end will be lost.
The file must be writable by the user to perform this operation. If length is longer, holes will be added to the end. However, some systems do not support this feature and will leave the file unchanged. In addition to the usual file name errors, the following errors may occur:.
This is like truncate , but it works on a file descriptor fd for an opened file instead of a file name to identify the object.
The file must be opened for writing to successfully carry out the operation. The POSIX standard leaves it implementation defined what happens if the specified new length of the file is bigger than the original size. The ftruncate function might simply leave the file alone and do nothing or it can increase the size to the desired size. In this later case the extended area should be zero-filled.
So using ftruncate is no reliable way to increase the file size but if it is possible it is probably the fastest way. Since the mapped region must have a fixed size one cannot enlarge the file by writing something beyond the last mapped page. Instead one has to enlarge the file itself and then remap the file with the new size.
The example below shows how this works. The following errors may occur:. As announced here is a little example of how to use ftruncate in combination with mmap :. The function add writes a block of memory at an arbitrary position in the file. If the current size of the file is too small it is extended. Note the it is extended by a round number of pages.
This is a requirement of mmap. The program has to keep track of the real size, and when it has finished a final ftruncate call should set the real size of the file.
The mknod function is the primitive for making special files, such as files that correspond to devices. See section Testing the Type of a File. The dev argument specifies which device the special file refers to. Its exact interpretation depends on the kind of special file being created. The return value is 0 on success and -1 on error.
If you need to use a temporary file in your program, you can use the tmpfile function to open it. The tempnam function is like tmpnam but lets you choose what directory temporary files will go in, and something about what their file names will look like.
Important for multi-threaded programs is that tempnam is reentrant, while tmpnam is not since it returns a pointer to a static buffer. The file is deleted automatically when it is closed or when the program terminates.
On some other ISO C systems the file may fail to be deleted if the program terminates abnormally. If the result argument is a null pointer, the return value is a pointer to an internal static string, which might be modified by subsequent calls and therefore makes this function non-reentrant. It is possible for tmpnam to fail if you call it too many times without removing previously-created files. This is because the limited length of the temporary file names gives room for only a finite number of different names.
If tmpnam fails it returns a null pointer. Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using tmpnam , leading to a possible security hole. Using tmpfile or mkstemp is a safe way to avoid this problem.
This guarantees reentrancy because the non-reentrant situation of tmpnam cannot happen here. Warning : This function has the same security problems as tmpnam. You can rely on being able to call tmpnam at least this many times before it might fail saying you have made too many temporary file names.
With the GNU library, you can create a very large number of temporary file names. If you actually created the files, you would probably run out of disk space before you ran out of names. Some other systems have a fixed, small limit on the number of temporary files. The limit is never less than If prefix is not a null pointer, up to five characters of this string are used as a prefix for the file name. The return value is a string newly allocated with malloc , so you should release its storage with free when it is no longer needed.
The directory prefix for the temporary file name is determined by testing each of the following in sequence. The directory must exist and be writable. Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using tempnam , leading to a possible security hole. Older Unix systems did not have the functions just described. Instead they used mktemp and mkstemp.
Both of these functions work by modifying a file name template string you pass. Note: Because mktemp and mkstemp modify the template string, you must not pass string constants to them. String constants are normally in read-only storage, so your program would crash when mktemp or mkstemp tried to modify the string.
If successful, it returns template as modified. If mktemp cannot find a unique file name, it makes template an empty string and returns that. Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using mktemp , leading to a possible security hole.
Using mkstemp is a safe way to avoid this problem. If successful, it modifies template in place and returns a file descriptor for that file open for reading and writing. If mkstemp cannot create a uniquely-named file, it returns The file is opened using mode If the file is meant to be used by other users this mode must be changed explicitly.
Unlike mktemp , mkstemp is actually guaranteed to create a unique file that cannot possibly clash with any other program trying to create a temporary file.
If it succeeds, it overwrites template with the name of the directory, and returns template. If mkdtemp cannot create an uniquely named directory, it returns NULL and sets errno appropriately.
The directory created by mkdtemp cannot clash with temporary files or directories created by other users. See section Creating Directories.
0コメント