pwrite, write - write on a file
#include <unistd.h>
ssize_t pwrite(intfildes, const void *buf, size_tnbyte,
off_toffset);
ssize_t write(intfildes, const void *buf, size_tnbyte);
Thewrite() function shall attempt to writenbyte bytes from the buffer pointed to bybuf to the fileassociated with the open file descriptor,fildes.
Before any action described below is taken, and ifnbyte is zero and the file is a regular file, thewrite()function may detect and return errors as described below. In the absence of errors, or if error detection is not performed, thewrite() function shall return zero and have no other results. Ifnbyte 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 fileindicated by the file offset associated withfildes. Before successful return fromwrite(), the file offset shall beincremented by the number of bytes actually written. On a regular file, if the position of the last byte written is greater than orequal to the length of the file, the length of the file shall be set to this position plus one.
On a file not capable of seeking, writing shall always take place starting at the current position. The value of a file offsetassociated 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 writeand no intervening file modification operation shall occur between changing the file offset and the write operation.
If awrite() requests that more bytes be written than there is room for (for example,[XSI]
the filesize limit of the process or
the physical end of a medium), only asmany bytes as there is room for shall be written. For example, suppose there is space for 20 bytes more in a file before reaching alimit. A write of 512 bytes will return 20. The next write of a non-zero number of bytes would give a failure return (except asnoted below).
[XSI]
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 tobe written, the request shall fail and the implementation shall generate the SIGXFSZ signal for the thread.
Ifwrite() is interrupted by a signal before it writes any data, it shall return -1 witherrno set to [EINTR].
Ifwrite() is interrupted by a signal after it successfully writes some data, it shall return the number of byteswritten.
If the value ofnbyte is greater than {SSIZE_MAX}, the result is implementation-defined.
After awrite() to a regular file has successfully returned:
Any successfulread() from each byte position in the file that was modified by thatwrite shall return the data specified by thewrite() for that position until such byte positions are again modified.
Any subsequent successfulwrite() 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 samepipe. 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 returnnbyte.
If the O_NONBLOCK flag is set,write() requests shall be handled differently, in the following ways:
Thewrite() 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 thepipe,write() shall transfer all the data and return the number of bytes requested. Otherwise,write() shall transferno data and return -1 witherrno 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 previouslywritten 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 witherrno set to [EAGAIN].
When attempting to write to a file descriptor (other than a pipe or FIFO) that supports non-blocking writes and cannot acceptthe 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 thethread,write() shall write what it can and return the number of bytes written. Otherwise, it shall return -1 and seterrno to [EAGAIN].
Upon successful completion, wherenbyte is greater than 0,write() shall mark for update the last datamodification and last file status change timestamps of the file, and if the file is a regular file, the S_ISUID and S_ISGID bits ofthe file mode may be cleared.
For regular files, no data transfer shall occur past the offset maximum established in the open file description associated withfildes.
Iffildes refers to a socket,write() shall be equivalent tosend()with no flags set.
[SIO]
If the O_DSYNC bit has been set, write I/O operations on the file descriptor shall complete as defined by synchronized I/O dataintegrity 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 fileintegrity completion.
[SHM]
Iffildes refers to a shared memory object, the result of thewrite() function is unspecified.
[TYM]
Iffildes refers to a typed memory object, the result of thewrite() function is unspecified.
[OB XSR]
Iffildes refers to a STREAM, the operation ofwrite() shall be determined by the values of the minimum andmaximumnbyte range (packet size) accepted by the STREAM. These values are determined by the topmost STREAM module. Ifnbyte falls within the packet size range,nbyte bytes shall be written. Ifnbyte does not fall within therange and the minimum packet size value is 0,write() shall break the buffer into maximum packet size segments prior tosending the data downstream (the last segment may contain less than the maximum packet size). Ifnbyte does not fall withinthe range and the minimum value is non-zero,write() shall fail witherrno set to [ERANGE]. Writing a zero-lengthbuffer (nbyte is 0) to a STREAMS device sends 0 bytes with 0 returned. However, writing a zero-length buffer to aSTREAMS-based pipe or FIFO sends no message and 0 is returned. The process may issue I_SWROPTioctl() 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 orFIFO:
If O_NONBLOCK is clear, and the STREAM cannot accept data (the STREAM write queue is full due to internal flow controlconditions),write() shall block until data can be accepted.
If O_NONBLOCK is set and the STREAM cannot accept data,write() shall return -1 and seterrno 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 dataoccurs,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, thevalue oferrno does not reflect the result ofwrite(), but reflects the prior error.
Thepwrite() function shall be equivalent towrite(), except that it writes into a given position and does notchange the file offset (regardless of whether O_APPEND is set). The first three arguments topwrite() are the same aswrite() with the addition of a fourth argumentoffset for the desired position inside the file. An attempt to performapwrite() on a file that is incapable of seeking shall result in an error.
Upon successful completion, these functions shall return the number of bytes actually written to the file associated withfildes. This number shall never be greater thannbyte. Otherwise, -1 shall be returned anderrno set toindicate the error.
These functions shall fail if:
- [EAGAIN]
- The file is neither a pipe, nor a FIFO, nor a socket, the O_NONBLOCK flag is set for the file descriptor, and the thread wouldbe delayed in thewrite() operation.
- [EBADF]
- Thefildes 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[XSI]
or the filesize limit of the process,
and there was no room for anybytes 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 offsetmaximum established in the open file description associated withfildes.
- [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, thecalling thread is not blocking SIGTTOU, the process is not ignoring SIGTTOU, and the process group of the process is orphaned. Thiserror may also be returned under implementation-defined conditions.
- [ENOSPC]
- There was no free space remaining on the device containing the file.
- [ERANGE]
- [OB XSR]
The transfer request size was outside the range supported by the STREAMS file associated withfildes.
Thepwrite() function shall fail if:
- [EINVAL]
- The file is a regular file or block special file, and theoffset argument is negative. The file offset shall remainunchanged.
- [ESPIPE]
- The file is incapable of seeking.
Thewrite() function shall fail if:
- [EAGAIN]
- The file is a pipe or FIFO, the O_NONBLOCK flag is set for the file descriptor, and the thread would be delayed in the writeoperation.
- [EAGAIN] or [EWOULDBLOCK]
- The file is a socket, the O_NONBLOCK flag is set for the file descriptor, and the thread would be delayed in the writeoperation.
- [ECONNRESET]
- A write was attempted on a socket that is not connected.
- [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. ASIGPIPE signal shall also be sent to the thread.
- [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 socketis of type SOCK_STREAM, a SIGPIPE signal shall also be sent to the thread.
These functions may fail if:
- [EINVAL]
- [OB XSR]
The STREAM or multiplexer referenced byfildes 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]
- [OB XSR]
A hangup occurred on the STREAM being written to.
[OB XSR]
A write to a STREAMS file may fail if an error message has been received at the STREAM head. In this case,errno is setto the value included in the error message.
Thewrite() 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.
Writing from a Buffer
The following example writes data from the buffer pointed to bybuf to the file associated with the file descriptorfd.
#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);...
None.
See also the RATIONALE section inread().
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 anyother process. This is useful when there are multiple writers sending data to a single reader. Applications need to know how largea write request can be expected to be performed atomically. This maximum is called {PIPE_BUF}. This volume of POSIX.1-2017 does notsay whether write requests for more than {PIPE_BUF} bytes are atomic, but requires that writes of {PIPE_BUF} or fewer bytes shallbe atomic.
Blocking/immediate: Blocking is only possible with O_NONBLOCK clear. If there is enough space for all the data requestedto be written immediately, the implementation should do so. Otherwise, the calling thread may block; that is, pause until enoughspace is available for writing. The effective size of a pipe or FIFO (the maximum amount that can be written in one operationwithout 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 ifnbyte<= {PIPE_BUF}. If it does happen (withnbyte> {PIPE_BUF}), this volume ofPOSIX.1-2017 does not guarantee atomicity, even ifret<= {PIPE_BUF}, because atomicity is guaranteed according to theamountrequested, not the amountwritten.
- Deferred:
- ret=-1,errno=[EAGAIN]
This error indicates that a later request may succeed. It does not indicate that itshall succeed, even ifnbyte<= {PIPE_BUF}, because if no process reads from the pipe or FIFO, the write never succeeds. An application couldusefully count the number of times [EAGAIN] is caused by a particular value ofnbyte> {PIPE_BUF} and perhaps do laterwrites 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_NONBLOCKclear
Immediately Writable:
None
Some
nbyte
nbyte<={PIPE_BUF}
Atomic blocking
Atomic blocking
Atomic immediate
nbyte
nbyte
nbyte
nbyte>{PIPE_BUF}
Blockingnbyte
Blockingnbyte
Blockingnbyte
If the O_NONBLOCK flag is clear, a write request shall block if the amount writable immediately is less than that requested. Ifthe flag is set (byfcntl()), a write request shall never block.
Write to a Pipe or FIFO with O_NONBLOCKset
Immediately Writable:
None
Some
nbyte
nbyte<={PIPE_BUF}
-1, [EAGAIN]
-1, [EAGAIN]
Atomicnbyte
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, thisvolume of POSIX.1-2017 does not specify exactly when a partial write is performed since that would require specifying internaldetails of the implementation. Every application should be prepared to handle partial writes when O_NONBLOCK is set and therequested amount is greater than {PIPE_BUF}, just as every application should be prepared to handle partial writes on other kindsof 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 isany room in the pipe. If the pipe is empty, {PIPE_BUF} bytes must be written; if not, at least some progress must have beenmade.
Where this volume of POSIX.1-2017 requires -1 to be returned anderrno set to [EAGAIN], most historical implementationsreturn zero (with the O_NDELAY flag set, which is the historical predecessor of O_NONBLOCK, but is not itself in this volume ofPOSIX.1-2017). The error indications in this volume of POSIX.1-2017 were chosen so that an application can distinguish these casesfrom end-of-file. Whilewrite() cannot receive an indication of end-of-file,read() can, and the two functions have similar return values. Also, some existing systems (forexample, Eighth Edition) permit a write of zero bytes to mean that the reader should get an end-of-file indication; for thosesystems, a return value of zero fromwrite() indicates a successful write of an end-of-file indication.
Implementations are allowed, but not required, to perform error checking forwrite() 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 inread().
Writes can be serialized with respect to other reads and writes. If aread() of filedata can be proven (by any means) to occur after awrite() of the data, it must reflect thatwrite(), even if thecalls are made by different processes. A similar requirement applies to multiple write operations to the same file position. Thisis needed to guarantee the propagation of data fromwrite() calls to subsequentread() calls. This requirement is particularly significant for networked file systems, wheresome caching schemes violate these semantics.
Note that this is specified in terms ofread() andwrite(). The XSIextensionsreadv() andwritev() alsoobey these semantics. A new "high-performance" write analog that did not follow these serialization requirements would also bepermitted by this wording. This volume of POSIX.1-2017 is also silent about any effects of application-level caching (such as thatdone bystdio).
This volume of POSIX.1-2017 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 detectedimmediately, such as [EAGAIN], clearly the pointer should not change. After an interrupt or hardware error, however, an updatedvalue would be very useful and is the behavior of many implementations.
This volume of POSIX.1-2017 does not specify the behavior of concurrent writes to a regular file from multiple threads, exceptthat each write is atomic (seeThread Interactions with Regular FileOperations). Applications should use some form of concurrency control.
This volume of POSIX.1-2017 intentionally does not specify anypwrite() errors related to pipes, FIFOs, and sockets otherthan [ESPIPE].
None.
chmod,creat,dup,fcntl,getrlimit,lseek,open,pipe,read,ulimit,writev
First released in Issue 1. Derived from Issue 1 of the SVID.
The DESCRIPTION is updated for alignment with the POSIX Realtime Extension and the POSIX Threads Extension.
Large File Summit extensions are added.
Thepwrite() function is added.
The DESCRIPTION states that thewrite() function does not block the thread. Previously this said "process" rather than"thread".
The DESCRIPTION and ERRORS sections are updated so that references to STREAMS are marked as part of the XSI STREAMS OptionGroup.
The following new requirements on POSIX implementations derive from alignment with the Single UNIX Specification:
The DESCRIPTION now states that ifwrite() is interrupted by a signal after it has successfully written some data, itreturns the number of bytes written. In the POSIX.1-1988 standard, it was optional whetherwrite() returned the number ofbytes written, or whether it returned -1 witherrno set to [EINTR]. This is a FIPS requirement.
The following changes are made to support large files:
For regular files, no data transfer occurs past the offset maximum established in the open file description associated with thefildes.
A second [EFBIG] error condition is added.
The [EIO] error condition is added.
The [EPIPE] error condition is added for when a pipe has only one end open.
The [ENXIO] optional error condition is added.
Text referring to sockets is added to the DESCRIPTION.
The following changes were made to align with the IEEE P1003.1a draft standard:
The effect of reading zero bytes is clarified.
The DESCRIPTION is updated for alignment with IEEE Std 1003.1j-2000 by specifying thatwrite() results areunspecified for typed memory objects.
The following error conditions are added for operations on sockets: [EAGAIN], [EWOULDBLOCK], [ECONNRESET], [ENOTCONN], and[EPIPE].
The [EIO] error is made optional.
The [ENOBUFS] error is added for sockets.
The following error conditions are added for operations on sockets: [EACCES], [ENETDOWN], and [ENETUNREACH].
Thewritev() function is split out into a separate reference page.
IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/146 is applied, updating text in the ERRORS section from "aSIGPIPE signal is generated to the calling process" to "a SIGPIPE signal shall also be sent to the thread".
IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/147 is applied, making a correction to the RATIONALE.
Thepwrite() function is moved from the XSI option to the Base.
Functionality relating to the XSI STREAMS option is marked obsolescent.
SD5-XSH-ERN-160 is applied, updating the DESCRIPTION to clarify the requirements for thepwrite() function, and to changethe use of the phrase "file pointer" to "file offset".
POSIX.1-2008, Technical Corrigendum 1, XSH/TC1-2008/0742 [219], XSH/TC1-2008/0743 [215], XSH/TC1-2008/0744 [79], andXSH/TC1-2008/0745 [215] are applied.
POSIX.1-2008, Technical Corrigendum 2, XSH/TC2-2008/0401 [676,710] and XSH/TC2-2008/0402 [966] are applied.
return to top of page